Scenario
我有以下代码:
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes.js"></script>
<div id="decrypted">Please wait...</div>
Insert new note:<input type="text" id="new_note"><input type="button" id="enc_button" value="Save">
<script>
var password = "testpassword";
var encrypted_text = localStorage.getItem("encrypted");
var rawData = atob(encrypted_text);
var iv = rawData.substring(0,16);
var crypttext = rawData.substring(16);
var plaintextArray = CryptoJS.AES.decrypt(
{ ciphertext: CryptoJS.enc.Latin1.parse(crypttext) },
CryptoJS.enc.Hex.parse(password),
{ iv: CryptoJS.enc.Latin1.parse(iv) }
);
var decrypted = CryptoJS.enc.Latin1.stringify(plaintextArray);
document.getElementById("decrypted").innerHTML = decrypted;
document.getElementById("enc_button").onclick = function(){
var text = document.getElementById("new_note").value;
var encrypted = CryptoJS.AES.encrypt(text, password);
localStorage.setItem("encrypted",encrypted);
}
</script>
我的代码应该做什么
使用 CryptoJS 使用 AES 加密字符串;解密本地存储中保存的加密文本并将结果显示在 div 中
什么不起作用
虽然字符串似乎已加密,但变量decrypt
是空的。 Chrome 控制台中不会触发任何错误。
我的问题
如何成功加密和解密我的文本?
CryptoJS 有两种略有不同的加密/解密类型。
当你使用
var encrypted = CryptoJS.AES.encrypt(text, password);
那么您使用的是基于密码的加密,这与纯密钥/基于 IV 的加密不同。这意味着密码和随机生成的盐通过一次 MD5 调用运行,以生成用于实际加密的密钥和 IV。这是一种与 OpenSSL 兼容的加密方式。这encrypted
对象存储用于生成密钥和 IV 的随机盐。
当你强行encrypted
转换为字符串(如将其添加到 localStorage),然后将其转换为包含 salt 的 OpenSSL 兼容字符串编码。为了再次解密它,你不需要自己搞乱密钥、IV 或盐,因为 CryptoJS 会自动为你做这些:
var decrypted = CryptoJS.AES.decrypt(encrypted, password);
请记住decrypted
is a WordArray
对象,当您强制将其转换为字符串时,默认情况下它会将内容编码为十六进制。如果您不希望这样,那么您需要自己指定编码,例如 UTF-8。
当由于某种原因(例如错误的密钥、错误的密文或错误的编码)解密失败时,通常会返回空白值。 CryptoJS 不会抛出自定义错误消息,但会尝试继续,因为您应该知道自己在做什么。
完整代码:
var password = "testpassword";
document.getElementById("enc_button").onclick = function(){
var text = document.getElementById("new_note").value;
var encrypted = CryptoJS.AES.encrypt(text, password);
encrypted = encrypted.toString();
var decrypted = CryptoJS.AES.decrypt(encrypted, password);
decrypted = decrypted.toString(CryptoJS.enc.Utf8)
document.getElementById("decrypted").innerHTML = decrypted;
}
<script src="https://cdn.rawgit.com/CryptoStore/crypto-js/3.1.2/build/rollups/aes.js"></script>
<div id="decrypted">Please wait...</div>
Insert new note:<input type="text" id="new_note"><input type="button" id="enc_button" value="Encrypt & Decrypt">
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)