I try to use progressive ciphering from CryptoJS to decrypt files. The files are encrypted & base64 encoded with OpenSSL as shown in the CryptoJS documentation (CryptoJS).
When I use CryptoJS.AES.decrypt everything works fine:
var encryptedText = "U2FsdGVkX19X2wD+xFnLd3WLuzW5qA0dppGtV+VPOFdjslLsZpwfdqd02BOe4pvxG2zZok06DchVfZBBBS/JWg==";
var key = CryptoJS.enc.Hex.parse("A6420198998C341308AF100CF7CCAC95884E4084581A4F8CFB8DFA7FEAD045EF");
var iv = CryptoJS.enc.Hex.parse("7F418B4532F8BC83261639DBA60C0A50");
var decrypted = CryptoJS.AES.decrypt(encryptedText, key, {iv: iv});
var base64 = CryptoJS.enc.Base64.stringify(decrypted);
var result = atob(base64);
But when I try progressive decryption the result is corrupted:
var decrypted;
var cipher = CryptoJS.algo.AES.createDecryptor(key, { iv: iv});
decrypted = cipher.process(encryptedText);
decrypted.concat(cipher.finalize());
var base64 = CryptoJS.enc.Base64.stringify(decrypted);
var result = atob(base64);
Has anyone an idea what I am doing wrong?
The problem is that encryptedText
is a string which is OpenSSL formatted. It is not the pure ciphertext which you get from the ciphertext
property after encryption:
var ct = CryptoJS.AES.encrypt(plaintext, key, {iv: iv}).ciphertext;
The Cipher.process
function only accepts a WordArray
or the data string and encryptedText
is neither. You either need to use CryptoJS.format.OpenSSL.parse()
to retrieve the ciphertext WordArray
:
var ct = CryptoJS.format.OpenSSL.parse(encryptedText).ciphertext;
or directly retrieve ciphertext
when you encrypt it like in the first snippet.
After that, you can do:
var decrypted = cipher.process(ct);
decrypted = decrypted.concat(cipher.finalize());
I'm also not sure why you stringify as Base64 and then use atob
, because there is an easier way to get the original string back:
console.log(decrypted.toString(CryptoJS.enc.Utf8));