特别注意 java使用aes 加密语js交互 key是16为才可以匹配
package com.dl.utils;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class AESCoder{
public static String encrypt(String strKey, String strIn) throws Exception {
SecretKeySpec skeySpec = getKey(strKey);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec("01Gx03Yx05WW0607".getBytes());
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(strIn.getBytes());
return new BASE64Encoder().encode(encrypted);
}
public static String decrypt(String strKey, String strIn) throws Exception {
SecretKeySpec skeySpec = getKey(strKey);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec("01Gx03Yx05WW0607".getBytes());
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] encrypted1 = new BASE64Decoder().decodeBuffer(strIn);
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original);
return originalString;
}
private static SecretKeySpec getKey(String strKey) throws Exception {
byte[] arrBTmp = strKey.getBytes();
byte[] arrB = new byte[16]; // 创建一个空的16位字节数组(默认值为0)
for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
arrB[i] = arrBTmp[i];
}
SecretKeySpec skeySpec = new SecretKeySpec(arrB, "AES");
return skeySpec;
}
//key 为16位 截取 key的前后 8位 为16位 code为原文
// public static void main(String[] args) throws Exception {
// String Code = "123abc";
// String key = "12345678@#pqweg&11";
// String codE;
// codE = AESCoder.encrypt(key, Code);
// System.out.println("原文:" + Code);
// System.out.println("密钥:" + key);
// System.out.println("密文:" + codE);
// System.out.println("解密:" + AESCoder.decrypt(key, codE));
// }
}