我正在试验 Stanford Javascript Crypto Library (SJCL)并想要加密并稍后解密一个字符串。
下面的代码工作正常:
var pw = "password";
var message = "message";
var encrypted = sjcl.encrypt(pw, message);
alert(encrypted);
var decrypted = sjcl.decrypt(pw, encrypted)
alert(decrypted);
第一个警报显示加密数据,第二个警报显示“消息”。但是我需要将 var 加密存储在 SQL 数据库中,所以我通过 ajax 将它发送到服务器,服务器将它存储在一个表中。
我稍后请求加密消息(再次通过 ajax)并将其存储在变量 encrypted 中。之后我想解密它:
var decrypted = sjcl.decrypt(pw, encrypted);
alert(decrypted);
但我没有收到包含字符串“messages”的警报,控制台仅显示“未捕获的异常:CORRUPT:ccm:标签不匹配”。
我没有更改加密文本,两个示例之间的唯一区别是我从服务器获取了加密的变量。
知道哪里出了问题吗?
编辑:
将其存储在数据库中的 ajax 代码:
var url = "action.php?action=r&n="+name+"&pw="+pw_hashed+"&encrypted="+encrypted;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
if(xmlhttp.responseText == "success")
{
alert("success");
}
}
}
以及接收数据的ajax代码:
var url = "action.php?action=l&n="+name+"&pw="+pw_hashed;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
if(xmlhttp.responseText == "success")
{
var encrypted = xmlhttp.responseText;;
}
}
}
我还比较了加密后的加密字符串与服务器端的字符串和客户端(用于解密)的字符串:都是一样的。
最佳答案
问题几乎肯定出在您如何构建查询参数上。您需要使用 encodeURIComponent
对每个参数值进行编码,因为数据可能包含诸如 +
之类的字符,除非正确编码,否则这些字符将被转换为空格。
使用 encodeURIComponent
的存储 URL:
var url = "action.php?action=r&n="+encodeURIComponent(name)+"&pw="+encodeURIComponent(pw_hashed)+"&encrypted="+encodeURIComponent(encrypted);
以及您的检索 URL:
var url = "action.php?action=l&n="+encodeURIComponent(name)+"&pw="+encodeURIComponent(pw_hashed);
关于javascript - JS : Decryption not possible after storing in database (SJCL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30425767/