Skip to content

Instantly share code, notes, and snippets.

@gurdiga
Last active May 9, 2023 13:50
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gurdiga/6723876 to your computer and use it in GitHub Desktop.
Save gurdiga/6723876 to your computer and use it in GitHub Desktop.
JS AES encryption example.

JS AES encryption example

This is a quick example of how to get symmetric encryption in JS using aes.js from the crypto-js project:

// at this point http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes.js should be loaded

var data = 'a JSON blob or something',
    password = 'my long and very secretive passphrase';

var encrypted = CryptoJS.AES.encrypt(data, password).toString();

console.log(encrypted);
// => 'U2FsdGVkX18K9Ch1JYnck/Jmq+WDgM49vPmodMcLTk+/SzKtFg+o3Olc38kzacKv'

var decrypted = CryptoJS.AES.decrypt(encrypted, password).toString(CryptoJS.enc.Utf8);

console.log(decrypted);
// => 'a JSON blob or something'

The one thing that the snippet on the original site is missing, which is the reason of existence of this gist, is the .toString() call which gives you back the actual string. The decrypted variable here is some kind of AES object.

My experiments with a 12MB string show that the code works 3x faster on Firefox than on Chrome.

@sharjeel619
Copy link

Nice and easy example. Can you please tell me if its possible to hide the key/password itself in the code. And I am not talking about obfuscation of the js code. I was wondering if there would be any technique to hide the key/password in the code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment