JS: Decryption not possible after saving to database (SJCL)
I am experimenting with a scripting library at Stanford (SJCL) and want to encrypt and later decrypt a string.
The following code works fine:
var pw = "password";
var message = "message";
var encrypted = sjcl.encrypt(pw, message);
alert(encrypted);
var decrypted = sjcl.decrypt(pw, encrypted)
alert(decrypted);
The first warning shows encrypted data and the second warning shows a "message". However, I need to store the var encrypted in the SQL database, so I send it via ajax to the server, which stores it in a table.
I later request an encrypted message (again via ajax) and store it in an encrypted variable. After that I want to decrypt it:
var decrypted = sjcl.decrypt(pw, encrypted);
alert(decrypted);
But I don't get a warning that contains the string "messages", the console only displays "uncaught exception: CORRUPT: ccm: tag does not match".
I didn't change the ciphertext, the only difference between the two examples is that I got the variable encrypted from the server.
Any ideas what is wrong?
EDIT:
The ajax code to save it to the DB:
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");
}
}
}
And the ajax code to get the data:
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;;
}
}
}
I also compared the encrypted string immediately after encryption with the string on the server and the one on the client side (for decryption): all are the same.
source to share
The problem is almost in the way you construct your query parameters. You need to encode each parameter value using encodeURIComponent
as the data can contain characters such as +
to be converted to space except when encoded correctly.
Your repository url with encodeURIComponent
:
var url = "action.php?action=r&n="+encodeURIComponent(name)+"&pw="+encodeURIComponent(pw_hashed)+"&encrypted="+encodeURIComponent(encrypted);
And your search url:
var url = "action.php?action=l&n="+encodeURIComponent(name)+"&pw="+encodeURIComponent(pw_hashed);
source to share