JavaScript string encryption and decryption?

jeremiahs picture jeremiahs · Aug 16, 2013 · Viewed 376k times · Source

I'm interested in building a small app for personal use that will encrypt and decrypt information on the client side using JavaScript. The encrypted information will be stored in a database on a server, but never the decrypted version.

It doesn't have to be super duper secure, but I would like to use a currently unbroken algorithm.

Ideally I'd be able to do something like

var gibberish = encrypt(string, salt, key);

to generate the encoded string, and something like

var sensical = decrypt(gibberish, key);

to decode it later.

So far I've seen this: http://bitwiseshiftleft.github.io/sjcl/

Any other libraries I should look at?

Answer

Tomas Kirda picture Tomas Kirda · Oct 11, 2014

 var encrypted = CryptoJS.AES.encrypt("Message", "Secret Passphrase");
//U2FsdGVkX18ZUVvShFSES21qHsQEqZXMxQ9zgHy+bu0=

var decrypted = CryptoJS.AES.decrypt(encrypted, "Secret Passphrase");
//4d657373616765


document.getElementById("demo1").innerHTML = encrypted;
document.getElementById("demo2").innerHTML = decrypted;
document.getElementById("demo3").innerHTML = decrypted.toString(CryptoJS.enc.Utf8);
Full working sample actually is:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js" integrity="sha256-/H4YS+7aYb9kJ5OKhFYPUjSJdrtV6AeyJOtTkw6X72o=" crossorigin="anonymous"></script>

<br><br>
<label>encrypted</label>
<div id="demo1"></div>
<br>

<label>decrypted</label>
<div id="demo2"></div>

<br>
<label>Actual Message</label>
<div id="demo3"></div>