Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to print hex string with CryptoJS

I am trying to use CryptoJS to encrypt something and then generate a hexadecimal string of the encrypted text.

function EncryptAES(text, key) {
  var encrypted = CryptoJS.AES.encrypt(text, key);
  return CryptoJS.enc.Hex.stringify(encrypted);
}

var encrypted = EncryptAES("Hello, World!", "SuperSecretPassword");

console.log(encrypted);

However, instead of a hexadecimal string, a blank line is printed to the console. What am I doing wrong?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

CryptoJS.AES.encrypt() returns a CipherParams object that encapsulates several data, including the ciphertext as WordArray (s. here). By default, .toString() returns the hex encoded data for a WordArray:

function EncryptAES(text, key) {
    var encrypted = CryptoJS.AES.encrypt(text, key);
    return encrypted.ciphertext.toString()
}

var encrypted = EncryptAES("Hello, World!", "SuperSecretPassword");

console.log(encrypted);
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>

Note that in your example the key material is passed as string and therefore interpreted as passphrase (s. here), inferring key and IV via a key derivation function in conjunction with a random 8 bytes salt, which is why the ciphertext changes each time for the same input data.
Therefore, decryption requires not only the ciphertext but also the salt, which is also encapsulated in the CipherParams object.
For a CipherParams object, .toString() returns the data in the Base64 encoded OpenSSL format consisting of the ASCII encoding of Salted__ followed by the 8 bytes salt and the actual ciphertext, and thus contains all the information needed for decryption.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading