2

A simple encryption/decryption using CryptoJS gives me a weird output. Can anyone point me to where the code is wrong? (I'm looking for the output in the console)

var code = "Testcode";
var diterations = 1000;
var defaultkeyBytes = new CryptoJS.PBKDF2(code, code, { hasher: CryptoJS.algo.SHA512, keySize: 48 / 4, iterations: diterations });
var key = new CryptoJS.lib.WordArray.init(defaultkeyBytes.words, 32);
var iv = new CryptoJS.lib.WordArray.init(defaultkeyBytes.words.splice(32 / 4), 16);
var data = "test message new test message";
var h = CryptoJS.AES.encrypt(data, key, { iv: iv, mode: CryptoJS.mode.CBC });
console.log(h.toString());
var z = CryptoJS.AES.decrypt(h, key, { iv: iv, mode: CryptoJS.mode.CBC });
console.log(z.toString());

Output :

"Running fiddle"

"qx84iCiNL1YYWJhE6nG8KZxOCh4VGOBTaeCEAjy1P+s=" "74657374206d657373616765206e65772074657374206d657373616765"

https://jsfiddle.net/3q7tozph/

kenlukas
  • 835
  • 6
  • 18
newbie
  • 23
  • 2
  • Salt should be unique (usually random) when reusing a passphrase, although for CBC it's not as insecure as keystream modes like OFB or CTR. – dave_thompson_085 Jun 22 '22 at 02:30

1 Answers1

1

Details about the decryption/encryption output can be found on the documentation page for CryptoJS: Cipher Output.

Encrypt

As @dave_thompson_085 says in his comment, the output you see from h.toString() is a CipherParams object whose formatting defaults to base64, but whose WordArray components can be separated.

> data = "qx84iCiNL1YYWJhE6nG8KZxOCh4VGOBTaeCEAjy1P+s="
> base64.b64decode(data)
b'\xab\x1f8\x88(\x8d/V\x18X\x98D\xeaq\xbc)\x9cN\n\x1e\x15\x18\xe0Si\xe0\x84\x02<\xb5?\xeb'

Decrypt

It's working it's just a HexString that is being output. Quick Python code to show it.

> from binascii import unhexlify
> unhexlify("74657374206d657373616765206e65772074657374206d657373616765")
b'test message new test message'

The decryption output is a WordArray. The toString() method prints the full HexString instead of an array of 32-bit values. The z object itself decrypted correctly.

RoraΖ
  • 12,317
  • 4
  • 51
  • 83
  • Excellent .thankyou.. so I guess I need to convert from hex to ascii or utf8 string – newbie Jun 21 '22 at 13:32
  • @newbie Yes that would be correct. There might also be an object method for `z` that will output the string in the form you want. I'm not an expert in CryptoJS's API. – RoraΖ Jun 21 '22 at 13:34
  • 1
    https://cryptojs.gitbook.io/docs/#the-hashing-output (which describes WordArray, the same type used for decrypt output; as described lower on that page, encrypt output is a CipherParams object whose formatting defaults to base64, but whose WordArray components can be separated) – dave_thompson_085 Jun 22 '22 at 02:30