我有一个 JavaScript 前端,用于使用 AES/CBC/PKCS7Padding 加密数据并发送到 Java 后端进行解密。
这是我的 JavaScript 代码的摘录:
export const encryptPaymentData = (data) => {
var encrypt = new JSEncrypt()
encrypt.setPublicKey(publicKey)
// convert the JSON object to a string
const jsonDataString = JSON.stringify(data)
// Create iv and secret_key
let iv = crypto.randomBytes(16)
let secret_key = crypto.randomBytes(32)
// iv = Buffer.from(iv).toString("base64")
// secret_key = Buffer.from(secret_key).toString("base64")
iv = CryptoJS.enc.Base64.stringify(CryptoJS.lib.WordArray.create(iv))
secret_key = CryptoJS.enc.Base64.stringify(
CryptoJS.lib.WordArray.create(secret_key)
)
// Encrypt the plaintext using AES/CBC/PKCS5Padding
console.log("iv", iv)
console.log("Secret", secret_key)
const ciphertext = CryptoJS.AES.encrypt(jsonDataString, secret_key, {
iv: iv,
padding: CryptoJS.pad.Pkcs7,
mode: CryptoJS.mode.CBC,
})
console.log("cipherText", ciphertext)
// Print the ciphertext
console.log(ciphertext.toString())
}
这是我的 Java 代码的摘录:
private static final String ALGORITHM = "AES/CBC/PKCS7Padding";
public String decryptAES(String ciphertext, String secretKey, String iv) throws Exception {
IvParameterSpec ivSpec = new IvParameterSpec(Base64.getDecoder().decode(iv));
SecretKeySpec keySpec = new SecretKeySpec(Base64.getDecoder().decode(secretKey), "AES");
Cipher cipher = Cipher.getInstance(ALGORITHM, "BC");
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(ciphertext));
return new String(decrypted);
}
当我复制密钥和 iv 以及加密值并尝试在我的 Java 程序中解密时,我不断收到错误消息:javax.crypto.BadPaddingException: pad block corrupted
请问,可能是什么问题?