Reputation: 150
i am trying to get decrypted data with crypto-js but getting blank. while same keys works online aes decryption.
var CryptoJS = require("crypto-js");
var key = '+MbQeThVmYq3t6w9z$C&F)J@NcRfUjXn';
var iv = '5ty76ujie324$567';
var encdata = 'ad06c28a5c9d933bc73451f86fcaa69a';
cipher = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Hex.parse(encdata))
var decrypt = CryptoJS.AES.decrypt(cipher, Buffer.from(key), {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
var ddd = decrypt.toString(CryptoJS.enc.Utf8);
console.log(ddd,"hey");
unable to understand why it is behaving like this. but if i use crypto it is working with below code
var crypto = require("crypto");
let encryptedText = Buffer.from(encdata, 'hex');
let decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(key), iv);
let decrypted = decipher.update(encryptedText);
decrypted = Buffer.concat([decrypted, decipher.final()]);
console.log(decrypted.toString());
Upvotes: 2
Views: 4404
Reputation: 49141
Key and IV must be passed as WordArray
-objects (and not as strings or NodeJS-buffer) [1]. Since both are specified as UTF8-strings, they can be converted into WordArray
-objects with the corresponding UTF8-encoder (CryptoJS.enc.Utf8.parse(...)
) [2]:
var key = CryptoJS.enc.Utf8.parse('+MbQeThVmYq3t6w9z$C&F)J@NcRfUjXn'); // Key: Use a WordArray-object instead of a UTF8-string / NodeJS-buffer
var iv = CryptoJS.enc.Utf8.parse('5ty76ujie324$567'); // IV: Use a WordArray-object instead of a UTF8-string
var encdata = 'ad06c28a5c9d933bc73451f86fcaa69a';
var cipher = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Hex.parse(encdata));
var decrypt = CryptoJS.AES.decrypt(cipher, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
var decrypted = decrypt.toString(CryptoJS.enc.Utf8);
console.log(decrypted);
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.min.js"></script>
Note that the ciphertext is usually passed as CipherParams
-object [1]. Alternatively, it can be passed as a string (like in this example), which is then implicitly converted into a CipherParams
-object with a definable format strategy (by default, a Base64 encoded string is expected).
The decryption returns a WordArray
to be converted into a UTF8-string [4]:
Upvotes: 5