Java-AES256加密Util
1 public class AES256Util { 2 3 /** 4 * 密钥, 256位32个字节 5 */ 6 public static final String DEFAULT_SECRET_KEY = "uBdUx82vPHkDKb284d7NkjFoNcKWBuka"; 7 8 private static final String AES = "AES"; 9 10 /** 11 * 初始向量IV, 初始向量IV的长度规定为128位16个字节, 初始向量的来源为随机生成. 12 */ 13 private static final byte[] KEY_VI = "c558Gq0YQK2QUlMc".getBytes(); 14 15 /** 16 * 加密解密算法/加密模式/填充方式 17 */ 18 private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding"; 19 20 private static java.util.Base64.Encoder base64Encoder = java.util.Base64.getEncoder(); 21 private static java.util.Base64.Decoder base64Decoder = java.util.Base64.getDecoder(); 22 23 static { 24 java.security.Security.setProperty("crypto.policy", "unlimited"); 25 } 26 27 /** 28 * AES加密 29 */ 30 public static String encode(String key, String content) { 31 try { 32 javax.crypto.SecretKey secretKey = new javax.crypto.spec.SecretKeySpec(key.getBytes(), AES); 33 javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance(CIPHER_ALGORITHM); 34 cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, secretKey, new javax.crypto.spec.IvParameterSpec(KEY_VI)); 35 36 // 获取加密内容的字节数组(这里要设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码 37 byte[] byteEncode = content.getBytes(java.nio.charset.StandardCharsets.UTF_8); 38 39 // 根据密码器的初始化方式加密 40 byte[] byteAES = cipher.doFinal(byteEncode); 41 42 // 将加密后的数据转换为字符串 43 return base64Encoder.encodeToString(byteAES); 44 } catch (Exception e) { 45 e.printStackTrace(); 46 } 47 return null; 48 } 49 50 /** 51 * AES解密 52 */ 53 public static String decode(String key, String content) { 54 try { 55 javax.crypto.SecretKey secretKey = new javax.crypto.spec.SecretKeySpec(key.getBytes(), AES); 56 javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance(CIPHER_ALGORITHM); 57 cipher.init(javax.crypto.Cipher.DECRYPT_MODE, secretKey, new javax.crypto.spec.IvParameterSpec(KEY_VI)); 58 59 // 将加密并编码后的内容解码成字节数组 60 byte[] byteContent = base64Decoder.decode(content); 61 // 解密 62 byte[] byteDecode = cipher.doFinal(byteContent); 63 return new String(byteDecode, java.nio.charset.StandardCharsets.UTF_8); 64 } catch (Exception e) { 65 e.printStackTrace(); 66 } 67 return null; 68 } 69 70 public static void main(String[] args) { 71 String dbPassword = "123456"; 72 String encryptDbPwd = AES256Util.encode(DEFAULT_SECRET_KEY, dbPassword); 73 System.out.println("encrypt: " + encryptDbPwd); 74 75 String decrypt = AES256Util.decode(DEFAULT_SECRET_KEY, encryptDbPwd); 76 System.out.println("decrypt:" + decrypt); 77 } 78 79 }