Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
873 views
in Technique[技术] by (71.8m points)

javascript - crypto-js aes can't decrypt what it encrypted

Hello I'm trying to decrypt a encrypted aes string with crypto-js but it seems like it doesn't work right.

I'm using:

<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes.js"></script>
<script>
    var encrypted = CryptoJS.AES.encrypt("Message", "Secret Passphrase");

    var decrypted = CryptoJS.AES.decrypt(encrypted, "Secret Passphrase");
</script>

But my results are:

encrypted: U2FsdGVkX19whKq54yOQt3l1erbtEtn/M0qJjAH+E/E=
decrypted: 4d657373616765

My expectation was the it returns back "Message". What am I missing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The return type of all CryptoJS.<blockcipher>.decrypt() functions is a WordArray which is the native representation of binary data in CryptoJS. When you force it to be printed (automatically calling toString()), the binary data that it contains will be Hex encoded.

If you want to have a different encoding, then you need to specify it. Here are some examples:

console.log(decrypted.toString()); // Hex encoded
console.log(decrypted.toString(CryptoJS.enc.Hex)); // Hex encoded
console.log(CryptoJS.enc.Hex.stringify(decrypted)); // Hex encoded

console.log(decrypted.toString(CryptoJS.enc.Utf8)); // UTF-8 encoded
console.log(CryptoJS.enc.Utf8.stringify(decrypted)); // UTF-8 encoded

console.log(decrypted.toString(CryptoJS.enc.Base64)); // Base64 encoded
console.log(CryptoJS.enc.Base64.stringify(decrypted)); // Base64 encoded

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...