我的后端AES-128解密逻辑是正确的,因为当我在Java中进行AES-128加密后,它将正确解密。现在我尝试在Angular 8中复制加密逻辑,然后解密后的文本现在在初始字节处包含垃圾值,而剩下的一半字符串是正确的(类似``da%:���mL���͔1'', “ add”:“ uk”,“ com”:“哇”})。
下面是我的加密角度代码
encryptData(value: any) {
var iv = CryptoJS.enc.Base64.parse(this.generateIV());
var key = CryptoJS.enc.Hex.parse('0123456789abcdef0123456789abcdef');
var aesEncrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(value.toString()), key,{
keySize: 128 / 8,
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
console.log(JSON.stringify({
payloadToken: this.getRSAEncryption("0123456789abcdef0123456789abcdef"),
payloadVariable: aesEncrypted.iv.toString() ,
payloadText: aesEncrypted.toString()}
));
return aesEncrypted.toString();
}
generateIV() {
var key = "";
var hex = "0123456789abcdef";
for (var i = 0; i < 15; i++) {
key += hex.charAt(Math.floor(Math.random() * 15));
}
return key;
}
以下是我在Java中的解密逻辑
public static String packetDecryption(String requestPacket){
DecryptedTokenPacket decryptedTokenPacket = GSON.fromJson(requestPacket,
DecryptedTokenPacket.class);
SecretKey key2 = new SecretKeySpec(decryptedTokenPacket.getDecData(), 0,
decryptedTokenPacket.getDecData().length, EncConstants.ENC_ALGO);
// Instantiate the cipher
Cipher cipher = Cipher.getInstance(EncConstants.CBC_ALGO);
byte[] ivBytes = new Base64().decode(decryptedTokenPacket.getPayloadVariable());
cipher.init(Cipher.DECRYPT_MODE, key2, new IvParameterSpec(ivBytes));
byte[] encryptedTextBytes = new Base64().decode(decryptedTokenPacket.getPayloadText());
byte[] decryptedTextBytes;
decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
return new String(decryptedTextBytes);
}
//this function is used in the gateway for decrypting the secret key and then pass through
public DecryptedTokenPacket decryptKeyUsingRSA(EncryptedPacket encryptedPacket){
Cipher cipher = Cipher.getInstance(RSA_ALGO);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decData = cipher.doFinal(new Base64().decode(encryptedPacket.getPayloadToken()));
decryptedTokenPacket.setPayloadText(encryptedPacket.getPayloadText());
decryptedTokenPacket.setPayloadVariable(encryptedPacket.getPayloadVariable());
decryptedTokenPacket.setDecData(decData);
return decryptedTokenPacket;
}
豆子
public class DecryptedTokenPacket {
private String payloadVariable;
private String payloadText;
private byte[] decData;
}
public class EncryptedPacket {
private String payloadVariable;
private String payloadText;
private String payloadToken;
}
不确定在开始时是什么导致此垃圾值。有人可以帮我解决这个问题吗?
答案 0 :(得分:0)
const iv = CryptoJS.lib.WordArray.random(128/8);