Learn more about Russian war crimes in Ukraine.

Symmetric encryption with the Web Cryptography API

Here’s an example of symmetric encryption using the Web Cryptography API. Below you see three textareas: plaintext, ciphertext and private key. This page generates a new symmetric key. You can see this key in JSON Web Key format, on the right-hand side. The plaintext on the left is encrypted with this key; the resulting ciphertext is in the middle.

You can edit all three textareas. Editing the plaintext updates the ciphertext. Editing the private key also updates the ciphertext. Editing the ciphertext updates the plaintext using the private key.

The crypto.subtle methods used are generateKey, exportKey, importKey, encrypt and decrypt. I first generate the private key like this:

privKeyEl.value = JSON.stringify(
  await crypto.subtle.exportKey(
    "jwk",                              // JSON Web Key format
    await crypto.subtle.generateKey(
      {name:"AES-CTR", length: 256},    // AES in "counter" mode
      true,                             // Allow exporting the key
      ["encrypt", "decrypt"])));        // We'll use the key for encryption and decryption

I import the key again with the reverse process:

function importKey() {
  return crypto.subtle.importKey(
    "jwk",
    JSON.parse(privKeyEl.value),
    {name:"AES-CTR", length: 256},
    true,
    ["encrypt", "decrypt"]
  );
}

To encrypt the plaintext:

function buf2hex(buf) {
  return Array.prototype.map.call(new Uint8Array(buf), x=>(('00'+x.toString(16)).slice(-2))).join('');
}
async function encrypt() {
  const privKey = await importKey();
  ciphertextEl.value = buf2hex(
    await crypto.subtle.encrypt(
      {name: "AES-CTR", counter: new Uint8Array(16), length: 16*8},
      privKey,
      new TextEncoder("utf-8").encode(plaintextEl.value)));
}

To decrypt the ciphertext:

function hex2buf(hex) {
  const bytes = [];
  for (let i = 0; i < hex.length; i+=2) {
    bytes.push(Number.parseInt(hex.slice(i,i+2), 16));
  }
  return new Uint8Array(bytes);
}
async function decrypt() {
  const privKey = await importKey();
  plaintextEl.value = new TextDecoder("utf-8").decode(
    await crypto.subtle.decrypt(
      {name: "AES-CTR", counter: new Uint8Array(16), length: 16*8},
      privKey,
      hex2buf(ciphertextEl.value)));
};

Notice that, for each plaintext character, you get two hex characters. The plaintext and ciphertext are the same size in bytes. The characters are encoded byte-by-byte. By editing pieces of the ciphertext, the corresponding plaintext character changes. If you edit the private key, the ciphertext completely changes.

The encryption is AES in “counter” mode, counting up from 0 for each encryption block. This is perhaps not the “recommended” mode of operation. I’ll do a future post about modes of operation in block ciphers.

What can computers do? What are the limits of mathematics? And just how busy can a busy beaver be? This year, I’m writing Busy Beavers, a unique interactive book on computability theory. You and I will take a practical and modern approach to answering these questions — or at least learning why some questions are unanswerable!

It’s only $19, and you can get 50% off if you find the discount code ... Not quite. Hackers use the console!

After months of secret toil, I and Andrew Carr released Everyday Data Science, a unique interactive online course! You’ll make the perfect glass of lemonade using Thompson sampling. You’ll lose weight with differential equations. And you might just qualify for the Olympics with a bit of statistics!

It’s $29, but you can get 50% off if you find the discount code ... Not quite. Hackers use the console!

More by Jim

Tagged #programming, #crypto, #javascript. All content copyright James Fisher 2017. This post is not associated with my employer. Found an error? Edit this page.