案例代码
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
/**
* @author sovereign君
* @date 2024/3/30
* @ClassName AESExample
*/
public class AESExample {
public static void main(String[] args) throws Exception {
// 初始化密钥和IV(初始化向量)
String key = "0123456789ABCDEF"; // 16字节密钥
String initVector = "ABCDEF9876543210"; // 16字节IV
// 要加密的字符串
String originalString = "sovereign";
System.out.println("原始字符串: " + originalString);
// 加密
String encryptedString = encrypt(key, initVector, originalString);
System.out.println("加密后的字符串: " + encryptedString);
// 解密
String decryptedString = decrypt(key, initVector, encryptedString);
System.out.println("解密后的字符串: " + decryptedString);
}
public static String encrypt(String key, String initVector, String value) throws Exception {
//1 表示加密 2 是解密
Cipher cipher = getCipher(1,key, initVector);
byte[] encrypted = cipher.doFinal(value.getBytes());
return Base64.getEncoder().encodeToString(encrypted);
}
public static String decrypt(String key, String initVector, String encrypted) throws Exception {
Cipher cipher = getCipher(2,key, initVector);
byte[] original = cipher.doFinal(Base64.getDecoder().decode(encrypted));
return new String(original);
}
//创建密码器
public static Cipher getCipher(int enOrdecrypt,String key,String initVector) throws Exception{
IvParameterSpec ivParameterSpec = new IvParameterSpec(initVector.getBytes(StandardCharsets.UTF_8));
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
Cipher instance = Cipher.getInstance("AES/CBC/PKCS5PADDING");
instance.init(enOrdecrypt,secretKeySpec,ivParameterSpec);
return instance;
}
}
前端javascript需要使用 crypto-js ,所以我在vue项目中使用,安装依赖
npm install crypto-js
直接在项目根目录创建一个test.js文件
案例代码
const crypto =require('crypto-js');
const secret='0123456789ABCDEF'
const initVector='ABCDEF9876543210'
const message='jun'
const encrypted='PpdK6OoS0E7iQnM0AliUKA=='
// 将密钥和初始化向量从字符串转换为字节
const keyBytes = crypto.enc.Utf8.parse(secret);
const initVectorBytes = crypto.enc.Utf8.parse(initVector);
const encrypt=crypto.AES.encrypt(message,keyBytes,{iv:initVectorBytes,mode:crypto.mode.CBC}).toString()
console.log(encrypt)
const decrypt=crypto.AES.decrypt(encrypted,keyBytes,{iv:initVectorBytes,mode:crypto.mode.CBC,padding: crypto.pad.Pkcs7,}).toString(crypto.enc.Utf8)
console.log(decrypt)
这样Java和javascript加密的数据两个语言都能互相加密