Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Best way to encrypt data with password

I'm creating a server which can store cookies on the web that will contain application settings. The server will accept any data, but I want to encrypt all the settings before storing them in a cookie and decrypt them when reading them out. So I can store very sensitive data like Account Usernames & Passwords in the cookies and the server cannot do anything with it.

My question is now: What is the best way to encrypt such data with a password in JavaScript on the client side? What is the most secure?

I need some code that I can embed into my site and use it from there.

like image 752
Van Coding Avatar asked Apr 25 '11 20:04

Van Coding


People also ask

What is the best encryption for passwords?

PBKDF2 is recommended by NIST and has FIPS-140 validated implementations. So, it should be the preferred algorithm when these are required. PBKDF2 requires that you select an internal hashing algorithm such as an HMAC or a variety of other hashing algorithms. HMAC-SHA-256 is widely supported and is recommended by NIST.

Is JavaScript good for encryption?

Pretty secure. The advantages of using browser javascript are that the work is done clientside, so that encryption can be end to end, and that the key need never leave the local machine.


2 Answers

I'd recommend using AES encryption in your JavaScript code. See Javascript AES encryption for libraries and links. The trouble you'll have is picking a key that is only available on the client side. Perhaps you can prompt the user? Or hash together some client system information that's not sent to the server.

like image 121
WhiteFang34 Avatar answered Sep 28 '22 17:09

WhiteFang34


You could try a Vernam Cypher with the password.

Basically you use the password as the key and then XOR the string to encrypt with the password. This can be reversed as well.

Here is a wikipedia page this type of encryption http://en.wikipedia.org/wiki/XOR_cipher

Example Code

function encrypt(key, value) {
  var result="";
  for(i=0;i<value.length;++i)
  {
    result+=String.fromCharCode(key[i % key.length]^value.charCodeAt(i));
  }
  return result;
}

function decrypt()
{
 var result="";
  for(i=0;i<value.length;++i)
  {
    result+=String.fromCharCode(key[i % key.length]^value.charCodeAt(i));
  }
  return result;
}

I haven't tested this but its probably close. you will notice the encrypt and decrypt functions should be identical

like image 27
John Hartsock Avatar answered Sep 28 '22 19:09

John Hartsock