AES是开发中常用的加密算法之一。AES的算法总是相同的, 但经常遇到前端加密结果,后台无法解密,这是因为加密设置的参数不一致导致的。如果要保持一致,必须使下列参数一致密钥长度、加密模式、填充方式、初始向量。
一、引入Java类
import javax.crypto.*;//AES加密解密
import sun.misc.*;//BASE64转码
二、加密
/**
* 加密
*/
public static String encrypt(String content,String CRYPT_KEY,String IV_STRING) {
byte[] encryptedBytes = new byte[0];
try {
byte[] byteContent = content.getBytes("UTF-8");
//key
byte[] enCodeFormat = CRYPT_KEY.getBytes();
SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
//偏移量
byte[] initParam = IV_STRING.getBytes();
IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
// 指定加密的算法、工作模式和填充方式
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
encryptedBytes = cipher.doFinal(byteContent);
} catch (Exception e) {
System.out.println("AES encrypt Exception,content = {"+content+"},Exception = {"+e.getStackTrace()+"}");
}
return new BASE64Encoder().encode(encryptedBytes);
}
三、解密
/**
* 解密
*/
public static String decrypt(String content,String CRYPT_KEY,String IV_STRING) {
try {
// base64 解码
byte[] encryptedBytes = new BASE64Decoder().decodeBuffer(content);
//key
byte[] enCodeFormat = CRYPT_KEY.getBytes();
SecretKeySpec secretKey = new SecretKeySpec(enCodeFormat, "AES");
//偏移量
byte[] initParam = IV_STRING.getBytes();
IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
// 指定加密的算法、工作模式和填充方式
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
byte[] result = cipher.doFinal(encryptedBytes);
return new String(result, "UTF-8");
} catch (Exception e) {
System.out.println( "AES decrypt Exception,content = {"+content+"},Exception = {"+e.getStackTrace()+"}");
}
return null;
}
四、测试
public static void main(String[] args) {
String CRYPT_KEY = "0123456789abcdef";//key
String IV_STRING = "0123456789abcdef";//偏移量
String content = "12345";//原文
System.out.println("原文:"+content);
String contenCrypt = encrypt(content.toString().replaceAll("(\r\n|\r|\n|\n\r)",""),CRYPT_KEY,IV_STRING);
System.out.println("加密:"+contenCrypt);
System.out.println("解密:"+decrypt(contenCrypt,CRYPT_KEY,IV_STRING));
System.out.println("JS加密密文解密:"+decrypt("xWngUO1XD+BavHm1YkdTxA==",CRYPT_KEY,IV_STRING));
}
五、输出结果
Java后台加密解密与上一篇文章《数据AES加密安全传输之前端JS加密解密》对应
参考:https://blog.csdn.net/coyote1994/article/details/52368921