Js和Java用CryptoJS.pad.PkcsAES/CBC/PKCS7Padding 实现加解密数据(crypto-js、bouncycastle、hutool-java)
在JavaScript中使用CryptoJS实现AES加密时,可以使用CryptoJS.pad.Pkcs7
来填充数据。以下是一个简单的示例:
var CryptoJS = require("crypto-js");
// 密钥和初始化向量(IV)
var key = CryptoJS.enc.Utf8.parse('1234567812345678');
var iv = CryptoJS.enc.Utf8.parse('1234567812345678');
// 需要加密的数据
var message = "Hello World";
// 加密
function encrypt(message, key, iv) {
var encrypted = CryptoJS.AES.encrypt(message, key, {
iv: iv,
padding: CryptoJS.pad.Pkcs7
});
return encrypted.toString();
}
// 解密
function decrypt(encrypted, key, iv) {
var decrypted = CryptoJS.AES.decrypt(encrypted, key, {
iv: iv,
padding: CryptoJS.pad.Pkcs7
});
return decrypted.toString(CryptoJS.enc.Utf8);
}
// 执行加密和解密
var encrypted = encrypt(message, key, iv);
var decrypted = decrypt(encrypted, key, iv);
console.log('Encrypted:', encrypted);
console.log('Decrypted:', decrypted);
在Java中,你可以使用PKCS5Padding
或PKCS7Padding
(它们在Java中是同义词)来实现AES加解密。以下是一个简单的示例:
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class AESUtil {
private static final String ALGORITHM = "AES/CBC/PKCS7Padding";
private static final String SECRET_KEY = "1234567812345678";
private static final String IV = "1234567812345678";
public static String encrypt(String data, String key, String iv) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] encrypted = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encrypted);
}
评论已关闭