AES加解密算法工具类(AES/ECB AES/CBC),包括了加解密过程中出现乱码问题的解决方案
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
* @author : chenfan
* @className : MyAESUtil
* @date : Created in 2021/8/31 11:06
* @description :
*/
public class MyAESUtil {
/**
* AES ECB加密
* @param str 待加密字符串
* @param key 密钥
* @return 加密结果字符串
* @throws Exception
*/
public static String ecbEncrypt(String str, String key) throws Exception {
if (key == null) {
System.out.print("Key为空null");
return null;
}
// 判断Key是否为16位
if (key.length() != 16) {
System.out.print("Key长度不是16位");
return null;
}
byte[] raw = key.getBytes("utf-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(str.getBytes("utf-8"));
return new BASE64Encoder().encode(encrypted);//此处使用BASE64做转码功能,同时能起到2次加密的作用。
}
/**
* AES ECB解密
* @param str 待解密字符串
* @param key 密钥
* @return 解密结果字符串
* @throws Exception
*/
public static String ecbDecrypt(String str, String key) throws Exception {
try {
// 判断Key是否正确
if (key == null) {
System.out.print("Key为空null");
return null;
}
// 判断Key是否为16位
if (key.length() != 16) {
System.out.print("Key长度不是16位");
return null;
}
byte[] raw = key.getBytes("utf-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] encrypted = new BASE64Decoder().decodeBuffer(str);//先用base64解密
try {
byte[] original = cipher.doFinal(encrypted);
String originalString = new String(original,"utf-8");
return originalString;
} catch (Exception e) {
System.out.println(e.toString());
return null;
}
} catch (Exception ex) {
System.out.println(ex.toString());
return null;
}
}
/**
* AES CBC 加密
* @param str 待加密字符串
* @param key 密钥
* @param initVector 偏移量
* @return 加密结果字符串
*/
public static String cbcEncrypt(String str, String key, String initVector) {
try {
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(str.getBytes("UTF-8"));
//BASE64处理的密文包含有换行符“\n”,需要去除,否则某些场景下后台解密会出错
return (new BASE64Encoder().encode(encrypted)).replaceAll("\r\n", "");
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* AES CBC 解密
* @param str 待解密字符串
* @param key 密钥
* @param initVector 偏移量
* @return 解密结果字符串
*/
public static String cbcDecrypt(String str, String key, String initVector) {
try {
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] original = cipher.doFinal(new BASE64Decoder().decodeBuffer(str));
//某些场景下返回字符串明文会乱码,可将本方法改成:byte[]cbcDecrypt(),然后直接return original
//在调用本方法的时候进行如下处理:new String(cbcDecrypt(), "UTF-8"),即可解决解密中乱码的问题
return new String(original);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}
测试样例:
public static void main(String[] args) throws Exception {
//需要加密的字符串
String str = "{\n" +
"\t\"username\":\"admin\",\n" +
"\t\"password\":\"123456\",\n" +
"\t\"info\":\"加解密测试信息\"\n" +
"}";
// 密钥
String key = "1234567890abcdef";
//偏移量
String iv = "1234567890abcdef";
// AES ECB加密
String ecbEnString = MyAESUtil.ecbEncrypt(str, key);
System.out.println("ECB加密后的字串是:" + ecbEnString);
// AES ECB解密
String ecbDeString = MyAESUtil.ecbDecrypt(ecbEnString, key);
System.out.println("ECB解密后的字串是:" + ecbDeString);
// AES CBC加密
String cbcEnString = MyAESUtil.cbcEncrypt(str, key, iv);
System.out.println("CBC加密后的字串是:" + cbcEnString);
// AES CBC解密
String cbcDeString = MyAESUtil.cbcDecrypt(cbcEnString, key, iv);
System.out.println("CBC解密后的字串是:" + cbcDeString);
}
测试结果:
"C:\Program Files (x86)\Java \jdk1.8.0_74\bin/java.exe" ...
ECB加密后的字串是:Yq6qXC5yhmHrxkJ61LbA9YvE7Ztqo5B5hsUWVWC8EEI2ZZguHw+pdM1jAa2aa77CsTvpCLZvnx8Q
6ddpnhGLplOP033089dQnMlTLGaLIgI=
ECB解密后的字串是:{
"username":"admin",
"password":"123456",
"info":"加解密测试信息"
}
CBC加密后的字串是:17IW8iguqre0R/tOLiqptFYG/zT9olvaRnKQvJyGGoEcJg7xF7gaJO+UVbxX598Y0vNPcse/XZ2gRc9loMY61ahluNbCKklrCmXxHIf4B5A=
CBC解密后的字串是:{
"username":"admin",
"password":"123456",
"info":"加解密测试信息"
}
Process finished with exit code 0