Javascript 我的 CryptoJS 加密/解密不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12574160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
My CryptoJS encryption/decryption is not working
提问by Viktor
I have an array of JSON arrays whose values I am trying to encrypt with CryptoJS and then print for use in another file, where these values should be decrypted using a user-given passphrase.
我有一个 JSON 数组数组,我尝试使用 CryptoJS 对其值进行加密,然后打印以在另一个文件中使用,其中应使用用户给定的密码解密这些值。
But I am doing something wrong and I am getting "Uncaught Error: Malformed UTF-8 data" when decrypting the URL's.
但我做错了,在解密 URL 时,我收到“未捕获的错误:格式错误的 UTF-8 数据”。
encrypt.js:
加密.js:
var encrypted = CryptoJS.AES.encrypt(item[key], pass);
json[j] += encrypted.ciphertext.toString(CryptoJS.enc.Base64);
decrypt.js:
解密.js:
var decrypted = CryptoJS.AES.decrypt(item[key], pass);
html += '<a href="' + decrypted.toString(CryptoJS.enc.Utf8) + '" target="_blank" class="socialico ' + key + '">' + icons[key] + '</a>';
I followed thisexample... Help, pretty please?
我跟着这个例子...帮助,漂亮吗?
回答by Jeff M
That error message usually means the data wasn't decrypted correctly, and the resulting plaintext bytes don't form valid UTF-8 characters.
该错误消息通常意味着数据未正确解密,并且生成的纯文本字节不能形成有效的 UTF-8 字符。
A couple things to check:
需要检查的几件事:
- First, make sure you're using the same password for both encryption and decryption. You may want to keep a hash of the correct password so that you can verify if the user gave the correct password before you use it for decryption.
- Second, make sure that the value
item[key]
is a string before encrypting. CryptoJS can't encrypt JSON objects. You'll have to serialize it first.
- 首先,确保您使用相同的密码进行加密和解密。您可能希望保留正确密码的哈希值,以便您可以在使用密码进行解密之前验证用户是否提供了正确的密码。
- 其次,
item[key]
在加密之前确保该值是一个字符串。CryptoJS 无法加密 JSON 对象。您必须先对其进行序列化。