'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?
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Topaco |