Skip to content

Latest commit

 

History

History
106 lines (94 loc) · 2.78 KB

AES_CBC.md

File metadata and controls

106 lines (94 loc) · 2.78 KB

AES-CBC

W3 specification

Operations

Operation Parameters Result
generateKey AesKeyGenParams CryptoKey
importKey None CryptoKey
exportKey None JsonWebKey or BufferSource
encrypt AesCbcParams ArrayBuffer
decrypt AesCbcParams ArrayBuffer
wrapKey AesCbcParams ArrayBuffer
unwrapKey AesCbcParams CryptoKey

Generate key

const key = await crypto.subtle.generateKey(
  {
    name: "AES-CBC",
    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-CBC",
  false, // extractable
  ["encrypt", "decrypt"],
);

Export key

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

Encrypt

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

const encData = await crypto.subtle.encrypt(
  {
    name: "AES-CBC",
    iv, // BufferSource
  },
  key,  // AES key
  data, // BufferSource
);

Decrypt

const data = await crypto.subtle.decrypt(
  {
    name: "AES-CBC",
    iv, // BufferSource
  },
  key,  // AES key
  encData, // BufferSource
);

Wrap key

const iv = 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-CBC",
    iv, // BufferSource
  },
);

Unwrap key

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