Instantly share code, notes, and snippets.

Embed
What would you like to do?
Uses the SubtleCrypto interface of the Web Cryptography API to encrypt and decrypt text using AES-GCM (AES Galois counter mode).
/**
* Encrypts plaintext using AES-GCM with supplied password, for decryption with aesGcmDecrypt().
* (c) Chris Veness MIT Licence
*
* @param {String} plaintext - Plaintext to be encrypted.
* @param {String} password - Password to use to encrypt plaintext.
* @returns {String} Encrypted ciphertext.
*
* @example
* const ciphertext = await aesGcmEncrypt('my secret text', 'pw');
* aesGcmEncrypt('my secret text', 'pw').then(function(ciphertext) { console.log(ciphertext); });
*/
async function aesGcmEncrypt(plaintext, password) {
const pwUtf8 = new TextEncoder().encode(password); // encode password as UTF-8
const pwHash = await crypto.subtle.digest('SHA-256', pwUtf8); // hash the password
const iv = crypto.getRandomValues(new Uint8Array(12)); // get 96-bit random iv
const alg = { name: 'AES-GCM', iv: iv }; // specify algorithm to use
const key = await crypto.subtle.importKey('raw', pwHash, alg, false, ['encrypt']); // generate key from pw
const ptUint8 = new TextEncoder().encode(plaintext); // encode plaintext as UTF-8
const ctBuffer = await crypto.subtle.encrypt(alg, key, ptUint8); // encrypt plaintext using key
const ctArray = Array.from(new Uint8Array(ctBuffer)); // ciphertext as byte array
const ctStr = ctArray.map(byte => String.fromCharCode(byte)).join(''); // ciphertext as string
const ctBase64 = btoa(ctStr); // encode ciphertext as base64
const ivHex = Array.from(iv).map(b => ('00' + b.toString(16)).slice(-2)).join(''); // iv as hex string
return ivHex+ctBase64; // return iv+ciphertext
}
/**
* Decrypts ciphertext encrypted with aesGcmEncrypt() using supplied password.
* (c) Chris Veness MIT Licence
*
* @param {String} ciphertext - Ciphertext to be decrypted.
* @param {String} password - Password to use to decrypt ciphertext.
* @returns {String} Decrypted plaintext.
*
* @example
* const plaintext = await aesGcmDecrypt(ciphertext, 'pw');
* aesGcmDecrypt(ciphertext, 'pw').then(function(plaintext) { console.log(plaintext); });
*/
async function aesGcmDecrypt(ciphertext, password) {
const pwUtf8 = new TextEncoder().encode(password); // encode password as UTF-8
const pwHash = await crypto.subtle.digest('SHA-256', pwUtf8); // hash the password
const iv = ciphertext.slice(0,24).match(/.{2}/g).map(byte => parseInt(byte, 16)); // get iv from ciphertext
const alg = { name: 'AES-GCM', iv: new Uint8Array(iv) }; // specify algorithm to use
const key = await crypto.subtle.importKey('raw', pwHash, alg, false, ['decrypt']); // use pw to generate key
const ctStr = atob(ciphertext.slice(24)); // decode base64 ciphertext
const ctUint8 = new Uint8Array(ctStr.match(/[\s\S]/g).map(ch => ch.charCodeAt(0))); // ciphertext as Uint8Array
// note: why doesn't ctUint8 = new TextEncoder().encode(ctStr) work?
const plainBuffer = await crypto.subtle.decrypt(alg, key, ctUint8); // decrypt ciphertext using key
const plaintext = new TextDecoder().decode(plainBuffer); // decode password from UTF-8
return plaintext; // return the plaintext
}
@chrisveness

This comment has been minimized.

Owner

chrisveness commented Feb 17, 2017

Cryptography is indeed subtle. If I have made any errors, let me know and I will attempt to correct.

Thx to Tim Taubert @ Mozilla.

@chrisveness

This comment has been minimized.

Owner

chrisveness commented Feb 28, 2017

With the benefit of node-webcrypto-ossl and text-encoding polyfills, these routines will run on Node.js, and will inter-operate between the browser and the server.

Simply add the following at the top of the file:

const TextEncoder = require('text-encoding').TextEncoder;
const TextDecoder = require('text-encoding').TextDecoder;
const WebCrypto = require("node-webcrypto-ossl");
const crypto = new WebCrypto();
module.exports = { aesGcmEncrypt, aesGcmDecrypt };

Then to use it,

const aesGcmEncrypt = require ('./crypto-aes-gcm.js').aesGcmEncrypt;
const aesGcmDecrypt = require ('./crypto-aes-gcm.js').aesGcmDecrypt;

const ciphertext = await aesGcmEncrypt('my secret text', 'pw');
const plaintext = await aesGcmDecrypt(ciphertext, 'pw');
@majodi

This comment has been minimized.

majodi commented Nov 23, 2017

match(/./g) is leaving out whitespace chars, making the Decrypt fail when ctStr contains a return or linefeed for instance. For now I am using a for-loop with charCodeAt() but maybe there's a more efficient way.

@sohrabsaran

This comment has been minimized.

sohrabsaran commented Nov 26, 2017

Hi @chrisveness ,
I'm a newbie to GitHubGist...
Haven't yet tried out the above pieces of code, but it looks pretty useful.
What is the license for the code that you've shared above (even though it's a couple of lines of wrapper code around webcrypto)?
For some reason I'm unable to find clear information on this.
I'm planning to use this on an open source project, but still want to be clear on the licensing aspects.

Also by the way, I'm assuming that there is no known symmetric-key encryption system significantly more secure than AES-256-GCM.
Please confirm my understanding?
Also, can you recommend any similar gists for asymmetric key encryption?

Thanks,
Sohrab

@sohrabsaran

This comment has been minimized.

sohrabsaran commented Nov 27, 2017

Hi @majodi,
Can you please share your fix for decrypt?

Thanks,
Sohrab

@gnadelwartz

This comment has been minimized.

gnadelwartz commented Dec 2, 2017

i want to say a big thanks to you. this is the first time I found simple, useable and readable crypto libs made for casual users.
no need to bother with module api's, initialisation etc simply call encrypt/decrypt!

@gnadelwartz

This comment has been minimized.

gnadelwartz commented Dec 2, 2017

hm, not so easy then expected. even your code use await internally it returns a promise, not a string. So i can't simply do an

result = aesGcmEncrypt('text', 'pw');
enSaveValue(result);

gives me in Firefox:
"EnSaveValue URL: https://dealz.rrr.de/enstyler/save.php?ID=-378385905&value=[object Promise]"

looks like I have to convert over everything to async :-(, because it seems not easy to getb the value a promise from for not async code ...

@sohrabsaran

This comment has been minimized.

sohrabsaran commented Dec 2, 2017

@majodi,

You can replace:

 const ctUint8 = new Uint8Array(ctStr.match(/./g).map(ch => ch.charCodeAt(0)));     // ciphertext as Uint8Array

...with:

const ctUint8 = new Uint8Array(ctStr.match(/[\s\S]/g).map(ch => ch.charCodeAt(0)));     // ciphertext as Uint8Array

See also https://stackoverflow.com/questions/1068280/javascript-regex-multiline-flag-doesnt-work

@chrisveness

This comment has been minimized.

Owner

chrisveness commented Mar 10, 2018

@majodi, thanks for picking up the case where the ciphertext includes line terminators, and @sohrabsaran for providing a nice, clean fix.

@sohrabsaran, I've added a (MIT) licence notice. As far as I'm aware, AES-256-GCM is pretty much tops. I'm afraid I can't help with asymmetric key encryption.

@gnadelwartz I've added an alternative syntax to the examples using .then() rather than await, but there is no way around using promises, the Web Cryptography API is promise-based.

@timbru31

This comment has been minimized.

timbru31 commented Apr 12, 2018

Amazing gist, thanks a ton! I'd like to add a note, that Safari 10 (and iOS <11) does not support AES-GCM, but AES-CBC. To use AES-CBC the initializationVector (iv) needs to be a crypto.getRandomValues(new Uint8Array(16)); and the const ctStr needs to be atob(ciphertext.slice(32));

@Xeoncross

This comment has been minimized.

Xeoncross commented Apr 13, 2018

Thank you for sharing. I am trying to convert this to AES-CTR but having some problems getting the decoding correct:

/**
 * Encrypts plaintext using AES-CTR with supplied password, for decryption with aesCtrDecrypt().
 *                                                                      (c) Chris Veness MIT Licence
 *
 * @param   {String} plaintext - Plaintext to be encrypted.
 * @param   {String} password - Password to use to encrypt plaintext.
 * @returns {String} Encrypted ciphertext.
 */
async function aesCtrEncrypt(plaintext, password) {
  const data = new TextEncoder().encode(plaintext);  
  const iv = crypto.getRandomValues(new Uint8Array(16));                             // get 120-bit random iv
  const alg = {name: "AES-CTR", counter: iv, length: 128};
  console.log('iv', iv);
  
  // Generate key
  // const key = await crypto.subtle.generateKey(
  //     {
  //         name: "AES-CTR",
  //         length: 256, //can be  128, 192, or 256
  //     },
  //     false, //whether the key is extractable (i.e. can be used in exportKey)
  //     ["encrypt", "decrypt"] //can "encrypt", "decrypt", "wrapKey", or "unwrapKey"
  // );
  
  // Use provided key
  const pwUtf8 = new TextEncoder().encode(password);                                 // encode password as UTF-8
  const pwHash = await crypto.subtle.digest('SHA-256', pwUtf8);                      // hash the password
  const key = await crypto.subtle.importKey('raw', pwHash, alg, false, ['encrypt']); // generate key from pw
  
  const ctBuffer = await crypto.subtle.encrypt(alg, key, data)

  const ctArray = Array.from(new Uint8Array(ctBuffer));                              // ciphertext as byte array
  const ctStr = ctArray.map(byte => String.fromCharCode(byte)).join('');             // ciphertext as string
  const ctBase64 = btoa(ctStr);                                                      // encode ciphertext as base64

  const ivHex = Array.from(iv).map(b => ('00' + b.toString(16)).slice(-2)).join(''); // iv as hex string

  return ivHex+ctBase64;                                                             // return iv+ciphertext
  
}

/**
 * Decrypts ciphertext encrypted with aesGcmEncrypt() using supplied password.
 *                                                                      (c) Chris Veness MIT Licence
 *
 * @param   {String} ciphertext - Ciphertext to be decrypted.
 * @param   {String} password - Password to use to decrypt ciphertext.
 * @returns {String} Decrypted plaintext.
 *
 * @example
 *   const plaintext = await aesGcmDecrypt(ciphertext, 'pw');
 *   aesGcmDecrypt(ciphertext, 'pw').then(function(plaintext) { console.log(plaintext); });
 */
async function aesCtrDecrypt(ciphertext, password) {
    const pwUtf8 = new TextEncoder().encode(password);                                 // encode password as UTF-8
    const pwHash = await crypto.subtle.digest('SHA-256', pwUtf8);                      // hash the password

    const iv = ciphertext.slice(0,32).match(/.{2}/g).map(byte => parseInt(byte, 16));  // get iv from ciphertext
    console.log('iv', iv);
  
    const alg = { name: 'AES-CTR', counter: new Uint8Array(iv), length: 128 };         // specify algorithm to use

    const key = await crypto.subtle.importKey('raw', pwHash, alg, false, ['decrypt']); // use pw to generate key

    console.log('ciphertext.slice(32)', ciphertext.slice(32));
  
    const ctStr = atob(ciphertext.slice(32));                                          // decode base64 ciphertext
    const ctUint8 = new Uint8Array(ctStr.match(/\s\S/g).map(ch => ch.charCodeAt(0)));  // ciphertext as Uint8Array
    // note: why doesn't ctUint8 = new TextEncoder().encode(ctStr) work?

    const plainBuffer = await crypto.subtle.decrypt(alg, key, ctUint8);                // decrypt ciphertext using key
    const plaintext = new TextDecoder().decode(plainBuffer);                           // decode password from UTF-8

    return plaintext;                                                                  // return the plaintext
}

async function run() {
  const plaintext = "This my secret message";
  console.log(plaintext);
  
  const password = crypto.getRandomValues(new Uint8Array(32));
  console.log('password', password);

  let ciphertext = await aesCtrEncrypt(plaintext, password);
  console.log("ciphertext", ciphertext);
  
  // Decrypt
  let decryptedText = await aesCtrDecrypt(ciphertext, password);
  console.log('decryptedText', decryptedText);
  
}

run();

After I fix this I'll need to add a SHA2 (512bit) HMAC to authenticate the ciphertext.

@lolotobg

This comment has been minimized.

lolotobg commented May 17, 2018

I think there is a problem with the regex here: ctStr.match(/\s\S/g), shouldn't this be ctStr.match(/[\s\S]/g) instead?
I mean we are trying to match every single character right? Not just the cases where a whitespace character is exactly followed by a non-whitespace one.

@Toxiapo

This comment has been minimized.

Toxiapo commented Jul 12, 2018

@lolotobg

The new regex pattern fixed the problem I had with the gist.

@sohrabsaran

This comment has been minimized.

sohrabsaran commented Jul 30, 2018

The code uses SHA-256 to create a hash from the password. If we look at how 7-zip etc. works, it takes the user-given password and hashes it several thousand times to increase the time it will take an attacker to use brute force to guess the user-given password. On further reading, it looks like you cannot just do the hashing just like that- you need to preserve the 'entropy' of the original user-given password. There are algorithms such as PBKDF2 and Argon. See https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/deriveKey

@chrisveness

This comment has been minimized.

Owner

chrisveness commented Oct 9, 2018

Regexp updated. Oops!

@chrisveness

This comment has been minimized.

Owner

chrisveness commented Oct 9, 2018

@sohrabsaran I don't know anything about how 7-zip etc work. I believe repeatedly hashing a password does not necessarily increase entropy; for storing passwords for e.g. interactive logins, key derivation functions such as bcrypt or scrypt are a better solution. Correct me if I am wrong, but I think using a password to obtain a key for AES encryption is an entirely different beast. But in any case, you are welcome to improve the security, I just wanted to illustrate the use of the SubtleCrypto interface of the Web Cryptography API, as it is not necessarily immediately evident how to string the different elements together, from documents I found.

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