AES-CTR

January 30, 2019 ยท View on GitHub

W3 specification

Operations

OperationParametersResult
generateKeyAesKeyGenParamsCryptoKey
importKeyNoneCryptoKey
exportKeyNoneJsonWebKey or BufferSource
encryptAesCtrParamsArrayBuffer
decryptAesCtrParamsArrayBuffer
wrapKeyAesCtrParamsArrayBuffer
unwrapKeyAesCtrParamsCryptoKey

Generate key

const key = await crypto.subtle.generateKey(
  {
    name: "AES-CTR",
    length: 128, // 128, 192, or 256
  },
  false, // extractable
  ["encrypt", "decrypt", "wrapKey", "unwrapKey"], // key usages
);

Import key

const key = await crypto.subtle.importKey(
  "raw", // raw or jwk
  new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6]), // raw data
  "AES-CTR",
  false, // extractable
  ["encrypt", "decrypt"],
);

Export key

const raw = await crypto.subtle.exportKey(
  "raw", // raw or jwk
  key,
);

Encrypt

const counter = crypto.getRandomValues(new Uint8Array(16));

const encData = await crypto.subtle.encrypt(
  {
    name: "AES-CTR",
    counter,     // BufferSource
    length: 128, // 1-128
  },
  key,  // AES key
  data, // BufferSource
);

Decrypt

const data = await crypto.subtle.decrypt(
  {
    name: "AES-CTR",
    counter,     // BufferSource
    length: 128, // 1-128
  },
  key,  // AES key
  encData, // BufferSource
);

Wrap key

const counter = crypto.getRandomValues(new Uint8Array(16));

const wrappedKey = await crypto.subtle.wrapKey(
  "pkcs8",   // raw, pkcs8, spki, or jwk
  anyKey,    // Crypto key
  key,       // AES key
  {
    name: "AES-CTR",
    counter,     // BufferSource
    length: 128, // 1-128
  },
);

Unwrap key

const unwrappedKey = await crypto.subtle.unwrapKey(
  "pkcs8",    // raw, pkcs8, spki, or jwk
  wrappedKey, // BufferSource
  key,        // AES key
  {
    name: "AES-CTR",
    counter,     // BufferSource
    length: 128, // 1-128
  },
  {
    name: "RSA-PSS",
    hash: "SHA-256",
  }
  false,      // extractable
  ["sign", "verify"],
);