java
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AESUtil {
public static void main(String[] args) throws Exception {
String plainText = "admin123";
System.out.println(AESEncrypt(plainText));
System.out.println(AESDecrypt(AESEncrypt(plainText)));
}
/**
* 获取AES编码规则
* 定义密钥和向量
*
* @return
*/
public static byte[] genEncodeRule() throws Exception {
// 定义密钥和向量
return "jsi43idkw6mqk12i".getBytes("utf-8");
}
/**
* AES加密
*
* @param content 参数
* @return
*/
public static String AESEncrypt(String content) throws Exception {
// 加密
SecretKeySpec keySpec = new SecretKeySpec(genEncodeRule(), "AES");
IvParameterSpec ivSpec = new IvParameterSpec(genEncodeRule());
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
byte[] encryptedBytes = cipher.doFinal(content.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
/**
* AES解密
*
* @param content 加密后的值
* @return
*/
public static String AESDecrypt(String content) throws Exception {
// 解密
SecretKeySpec keySpec = new SecretKeySpec(genEncodeRule(), "AES");
IvParameterSpec ivSpec = new IvParameterSpec(genEncodeRule());
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
byte[] decode = Base64.getDecoder().decode(content);
byte[] decryptedBytes = cipher.doFinal(decode);
return new String(decryptedBytes, "UTF-8");
}
}
js
js导入后直接调用 encryptData(‘admin’) 加密方法,decryptData(‘ZE4bck/oYCTmVKwBizgXyw==’)解密方法
其中 : jsi43idkw6mqk12i 是自定义加密值。如果更改要两端同步改
完了。谢谢!