AES对称加解密
import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class Aes { public static final String algorithm = "AES"; // AES/CBC/NOPaddin // AES 默认模式 // 使用CBC模式, 在初始化Cipher对象时, 需要增加参数, 初始化向量IV : IvParameterSpec iv = new // IvParameterSpec(key.getBytes()); // NOPadding: 使用NOPadding模式时, 原文长度必须是8byte的整数倍 public static final String transformation = "AES/CBC/NOPadding"; public static final String key = "1111111111111111"; /*** * BASE64解密 * @param key * @return * @throws Exception */ public static byte[] decryBASE64(String key) throws Exception{ return (new BASE64Decoder()).decodeBuffer(key); } /*** * BASE64加密 * @param key * @return * @throws Exception */ public static String encryptBASE64(byte[] key) throws Exception{ return (new BASE64Encoder()).encode(key); } /*** * 加密 * @param original 需要加密的参数(注意必须是16位) * @return * @throws Exception */ public static String encryptByAES(String original) throws Exception { // 获取Cipher Cipher cipher = Cipher.getInstance(transformation); // 生成密钥 SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), algorithm); // 指定模式(加密)和密钥 // 创建初始化向量 IvParameterSpec iv = new IvParameterSpec(key.getBytes()); cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv); // cipher.init(Cipher.ENCRYPT_MODE, keySpec); // 加密 byte[] bytes = cipher.doFinal(original.getBytes()); return encryptBASE64(bytes); } /** * 解密 * @param encrypted 需要解密的参数 * @return * @throws Exception */ public static String decryptByAES(String encrypted) throws Exception { // 获取Cipher Cipher cipher = Cipher.getInstance(transformation); // 生成密钥 SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), algorithm); // 指定模式(解密)和密钥 // 创建初始化向量 IvParameterSpec iv = new IvParameterSpec(key.getBytes()); cipher.init(Cipher.DECRYPT_MODE, keySpec, iv); // cipher.init(Cipher.DECRYPT_MODE, keySpec); // 解密 byte[] bytes = cipher.doFinal(decryBASE64(encrypted)); return new String(bytes); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?