how to encrypt/decrypt cookies data while writing and reading using jquery
I am using JQuery Cookies plugin for reading/writing the cookies, I have got below code in which I am storing the username, now I want that it should be encrpted in cookies and will be decrypted while reading.
if ($('#remember').attr('checked'))
{
开发者_JAVA技巧 $.cookie('username', userNo.val());
$.cookie('remember', 'true');
}
else
{
// reset cookies
$.cookie('username', null);
$.cookie('remember', null);
}
Please suggest!!
There is no way to securely encrypt the data while still having access to it from your Javascript since in order to do so, the (publicly visible) Javascript would have to contain both the decoding algorithm and any secret key used to encrypt the data!
Instead, if you want the data in the cookies to be encrypted, you can encrypt the contents on the server-side, and later decrypt the contents also on the server side. Any secret key on the server cannot be seen by the client (unless they somehow hack in, but then you've got bigger problems...).
Even if the data in the cookies is encrypted, that does not prevent the client from tampering with them; it only prevents the client from knowing what's in them. You can use an HMAC scheme to guarantee that the data has not been tampered with, but that seems like overkill here.
In this situation, you're storing the username as a means of identifying the user later; you could easily construct a random, meaningless value (a "nonce") that uniquely identifies the user and store that instead of the username. .NET's Guid.NewGuid()
is good for this -- store one copy in the database, and one in the user's cookie. Then, when the user comes back, you can look up the cookie value in the database and find the correct user (since GUIDs are unique).
精彩评论