Search code examples
javascriptcryptojs

reading encrypted object in javascript


var token = "WMwiDeJrawUKHif7D5a8yd4ne6Mv";
var salt =  "ERtrg56hfg5";

var key = CryptoJS.enc.Hex.parse('B374A26A71490437AA024E4FADD5B497FDFF1A8EA6FF12F6FB65AF2720B59CCF');
var iv  = CryptoJS.enc.Hex.parse('7E892875A52C59A3B588306B13C31FBD');

var encrypted = CryptoJS.AES.encrypt(token, key, { iv: iv });

context.setVariable("encryptedtoken", encrypted);

but it is not setting to variable saying it is an object. what I need to do


Solution

  • I think you have to use encrypted.ciphertext

    var encrypted = CryptoJS.AES.encrypt(token, key, { iv: iv });
    
    context.setVariable("encryptedtoken", encrypted.ciphertext);
    

    From CryptoJS documentation:

    The ciphertext you get back after encryption isn't a string yet. It's a CipherParams object. A CipherParams object gives you access to all the parameters used during encryption. When you use a CipherParams object in a string context, it's automatically converted to a string according to a format strategy. The default is an OpenSSL-compatible format.

    <script>
        var encrypted = CryptoJS.AES.encrypt("Message", "Secret Passphrase");
    
        alert(encrypted.key);        // 74eb593087a982e2a6f5dded54ecd96d1fd0f3d44a58728cdcd40c55227522223
        alert(encrypted.iv);         // 7781157e2629b094f0e3dd48c4d786115
        alert(encrypted.salt);       // 7a25f9132ec6a8b34
        alert(encrypted.ciphertext); // 73e54154a15d1beeb509d9e12f1e462a0
    
        alert(encrypted);            // U2FsdGVkX1+iX5Ey7GqLND5UFUoV0b7rUJ2eEvHkYqA=
    </script>