简体   繁体   中英

Unable to decrypt message using Crypto-Js

I am new to encryption. What I am trying to do is decrypt a cipher text using javascript library, CryptoJS . This code example works fine. The encryption part returns ciphertext "ae06b481cecfa67c98c125" (which is right) while decrypting the same object returns the original string "Hello World".

 var key = CryptoJS.enc.Latin1.parse("bad8deadcafef00d");
 var iv = CryptoJS.enc.Latin1.parse("bad8deadcafef00d");
 var encrypted = CryptoJS.AES.encrypt("Hello World", key, {iv: iv, mode: CryptoJS.mode.CTR, padding: CryptoJS.pad.NoPadding });
 alert(encrypted.ciphertext);

 var decryptedData = CryptoJS.AES.decrypt(encrypted, key, {iv: iv, mode: CryptoJS.mode.CTR, padding: CryptoJS.pad.NoPadding });
 originalData = decryptedData.toString(CryptoJS.enc.Utf8);
 alert(originalData);

Well this part works fine but when I try this chunk of code by passing the cipher text as a string independently, I don't get the decrypted message.

var key = CryptoJS.enc.Latin1.parse("bad8deadcafef00d");
var iv = CryptoJS.enc.Latin1.parse("bad8deadcafef00d");
var ciphertext = "ae06b481cecfa67c98c125";
// raw = CryptoJS.enc.Base64.parse(cipher);
var decryptedData = CryptoJS.AES.decrypt(ciphertext, key, {iv: iv, mode: CryptoJS.mode.CTR, padding: CryptoJS.pad.NoPadding });
originalData = decryptedData.toString(CryptoJS.enc.Utf8);
alert(originalData);
console.log(originalData);

Can somebody please point out why?

I have the following libraries included in the html file.

<script src="js/rollups/aes.js"></script>
<script src="js/components/mode-ctr.js"></script>
<script src="js/components/pad-nopadding.js"></script>

CryptoJS.AES.decrypt expects either a CipherParams object or an OpenSSL-formatted string. If the passed key is a string then the OpenSSL-formatted string is expected and otherwise the CipherParams object.

Since your key is not a string, you need this:

var decryptedData = CryptoJS.AES.decrypt({
    ciphertext: CryptoJS.enc.Hex.parse("ae06b481cecfa67c98c125")
}, key, {
    iv: iv, 
    mode: CryptoJS.mode.CTR, 
    padding: CryptoJS.pad.NoPadding
});

If the key is a string, then it isn't actually a key, but assumed to be a password and a key will be derived from that password with a random 8 byte salt. This would be comparable to OpenSSL's EVP_BytesToKey function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM