RSA-OAEP

August 24, 2019 ยท View on GitHub

W3 specification

Operations

OperationParametersResult
generateKeyRsaHashedKeyGenParamsCryptoKeyPair
importKeyRsaHashedImportParamsCryptoKey
exportKeyNoneJsonWebKey or BufferSource
encryptRsaOaepParamsArrayBuffer
decryptRsaOaepParamsArrayBuffer
wrapKeyRsaOaepParamsArrayBuffer
unwrapKeyRsaOaepParamsCryptoKey

Generate key

const keys = await crypto.subtle.generateKey(
  {
    name: "RSA-OAEP",
    hash: "SHA-256",     // SHA-1, SHA-256, SHA-384, or SHA-512
    publicExponent: new Uint8Array([1, 0, 1]), // 0x03 or 0x010001
    modulusLength: 2048, // 1024, 2048, or 4096
  },
  false,
  ["encrypt", "decrypt", "wrapKey", "unwrapKey"],
);

Import key

const publicKey = await crypto.subtle.importKey(
  "jwk",
  {
    alg: "RSA-OAEP-256",
    ext: true,
    key_ops: ["encrypt"],
    kty: "RSA",
    e: "AQAB",
    n: "vqpvdxuyZ6rKYnWTj_ZzDBFZAAAlpe5hpoiYHqa2j5kK7v8U5EaPY2bLib9m4B40j-n3FV9xUCGiplWdqMJJKT-4PjGO5E3S4N9kjFhu57noYT7z7302J0sJXeoFbXxlgE-4G55Oxlm52ID2_RJesP5nzcGTriQwoRbrJP5OEt0",
  },
  {
    name: "RSA-OAEP",
    hash: "SHA-256",
  },
  false,
  ["encrypt"],
);

Export key

const jwk = await crypto.subtle.exportKey(
  "jwk",
  publicKey);

Encrypt

const label = crypto.getRandomValues(new Uint8Array(5));

const encData = await crypto.subtle.encrypt(
  {
    name: "RSA-OAEP",
    label, // Optional. BufferSource
  },
  publicKey,  // RSA public key
  data,       // BufferSource
);

Decrypt

const data = await crypto.subtle.encrypt(
  {
    name: "RSA-OAEP",
    label, // Optional. BufferSource
  },
  privateKey, // RSA private key
  encData,    // BufferSource
);

Wrap key

const wrappedKey = await crypto.subtle.wrapKey(
  "raw",     // raw, pkcs8, spki, or jwk
  aesKey,    // Crypto key
  publicKey, // RSA public key
  {
    name: "RSA-OAEP",
    label, // Optional. BufferSource
  },
);

Unwrap key

const unwrappedKey = await crypto.subtle.unwrapKey(
  "raw",      // raw, pkcs8, spki, or jwk
  wrappedKey, // BufferSource
  privateKey, // RSA private key
  {
    name: "RSA-OAEP",
    label, // Optional. BufferSource
  },
  {
    name: "AES-CBC",
    label: 128,
  }
  false,      // extractable
  ["encrypt", "decrypt"],
);