我想在 Javascript 中进行加密并在 Java 中解密它,但它一直让我遇到错误的填充异常。我不知道该怎么做。
这是代码
key: string;
iv:string
keySize:256
iterations:1000;
constructor() { }
encrypt(keys, passw){
var salt = "12345678123456781234567812345678"
// var salt = CryptoJS.lib.WordArray.random(128/8);
console.log(passw)
console.log(salt)
var key = CryptoJS.PBKDF2(passw, salt, {
keySize: this.keySize/32,
iterations: this.iterations
});
var iv = CryptoJS.lib.WordArray.random(128/8);
var encrypted = CryptoJS.AES.encrypt(keys, key,{
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
})
var transitmessage = salt.toString() + iv.toString() + encrypted.toString()
console.log("tl: " + transitmessage.length)
return transitmessage;
}
public String decrypt(String encryptText) throws Exception {
try {
System.out.println("begin: " + encryptText);
String saltt = encryptText.substring(0,32);
String iv = encryptText.substring(32,64);
String encText = encryptText.substring(64);
System.out.println("enc: " + encText);
byte[] encryptTextBytes = Base64.getDecoder().decode(encText);
System.out.println("encbytes: " + encryptTextBytes);
SecretKeySpec key;
try {
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(this.secretKeyFactoryAlgorithm);
KeySpec keySpec = new PBEKeySpec(TOKEN.toCharArray(), hex(saltt), this.pwdIterations, this.keySize);
SecretKey secretKeyTemp = secretKeyFactory.generateSecret(keySpec);
key = new SecretKeySpec(secretKeyTemp.getEncoded(),keyAlgorithm);
}catch(NoSuchAlgorithmException | InvalidKeySpecException e) {
e.printStackTrace();
return null;
}
//decrypt the message
Cipher cipher = Cipher.getInstance(this.encryptAlgorithm);
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(hex(iv)));
byte[] decryptTextBytes = null;
try {
decryptTextBytes = cipher.doFinal(encryptTextBytes);
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
String text = new String(decryptTextBytes);
System.out.println("text: " + text);
return text;
}catch(Exception e) {
e.printStackTrace();
return null;
}
}
错误是这样的:javax.crypto.BadPaddingException:给定最终块未正确填充。如果在解密期间使用了错误的密钥,则可能会出现此类问题。
iv : [0000: A7 18 56 5D 79 22 2D C8 3F 3A 62 A0 BE 22 A1 D2 ..V]y"-.?:b.."..]
请帮助我,我需要尽快完成它。谢谢。