I want to encrypt and decrypt a value using crypto-js
but I am getting Malformed UTF-8 data
on decryption.
Here's my code :
Encryption part:
const keyUTF = CryptoJS.enc.Utf8.parse(SECRET_KEY);
const iv = CryptoJS.enc.Base64.parse(SECRET_KEY);
const tokenKey = getTokenKey();
const encryptedToken = CryptoJS.AES.encrypt(
JSON.stringify({ token }),
keyUTF,
{
iv,
// mode: CryptoJS.mode.CBC,
// padding: CryptoJS.pad.Pkcs7,
}
).toString();
console.log("Token:", tokenKey, encryptedToken);
Decryption Part:
const keyUTF = CryptoJS.enc.Utf8.parse(SECRET_KEY);
const iv = CryptoJS.enc.Base64.parse(SECRET_KEY);
const tokenKey = getTokenKey();
const encryptedToken = cookies.get(tokenKey);
console.log(tokenKey, encryptedToken);
let decryptedToken;
if (encryptedToken) {
// console.log(encryptedToken, encryptedToken.toString(CryptoJS.enc.Utf8));
decryptedToken = CryptoJS.AES.decrypt(encryptedToken.toString(), keyUTF, {
iv,
}).toString(CryptoJS.enc.Utf8);
console.log("Decrypted :", decryptedToken.toString());
}
I have looked at multiple questions related to this and tried all of their solutions but I still get the error. I have tried:
- Passing an object as
{ciphertext:value}
to the decrypt function - Using JSON.stringify with both the string and as an object(in current code)
- Passed mode and padding to encrypt/decrypt function (commented out)