Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. SubtleCrypto
  4. wrapKey()

SubtleCrypto: wrapKey() method

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨January 2020⁩.

Secure context: This feature is available only insecure contexts (HTTPS), in some or allsupporting browsers.

Note: This feature is available inWeb Workers.

ThewrapKey() method of theSubtleCrypto interface "wraps" a key.This means that it exports the key in an external, portable format, then encrypts the exported key.Wrapping a key helps protect it in untrusted environments, such as inside an otherwise unprotected data store or in transmission over an unprotected network.

As withSubtleCrypto.exportKey(), you specify anexport format for the key.To export a key, it must haveCryptoKey.extractable set totrue.

But becausewrapKey() also encrypts the key to be exported, you also need to pass in the key that must be used to encrypt it.This is sometimes called the "wrapping key".

The inverse ofwrapKey() isSubtleCrypto.unwrapKey(): whilewrapKey is composed of export + encrypt,unwrapKey is composed of import + decrypt.

Syntax

js
wrapKey(format, key, wrappingKey, wrapAlgo)

Parameters

format

A string describing the data format in which the key will be exported before it is encrypted. It can be one of the following:

raw

Raw format.

pkcs8

PKCS #8 format.

spki

SubjectPublicKeyInfo format.

jwk

JSON Web Key format.

key

TheCryptoKey to wrap.

wrappingkey

TheCryptoKey used to encrypt the exported key. The key must have thewrapKey usage set.

wrapAlgo

An object specifying thealgorithmto be used to encrypt the exported key, and any required extra parameters:

Return value

APromise that fulfills withanArrayBuffercontaining the encrypted exported key.

Exceptions

The promise is rejected when one of the following exceptions is encountered:

InvalidAccessErrorDOMException

Raised when the wrapping key is not a key for the requested wrap algorithm.

NotSupportedDOMException

Raised when trying to use an algorithm that is either unknown or isn't suitable forencryption or wrapping.

TypeError

Raised when trying to use an invalid format.

Supported algorithms

Allalgorithms that are usable for encryption are also usable for key wrapping, as long as the key has the "wrapKey" usage set.For key wrapping you have the additional option ofAES-KW.

AES-KW

AES-KW is a way to use the AES cipher for key wrapping.

One advantage of using AES-KW over another AES mode such as AES-GCM is that AES-KW does not require an initialization vector.To use AES-KW, the input must be a multiple of 64 bits.

AES-KW is specified inRFC 3394.

Examples

Note:You cantry the working examples out on GitHub.

Raw wrap

This example wraps an AES key.It uses "raw" as the export format and AES-KW, with a password-derived key, to encrypt it.See the complete code on GitHub.

js
let salt;/*Get some key material to use as input to the deriveKey method.The key material is a password supplied by the user.*/function getKeyMaterial() {  const password = window.prompt("Enter your password");  const enc = new TextEncoder();  return window.crypto.subtle.importKey(    "raw",    enc.encode(password),    { name: "PBKDF2" },    false,    ["deriveBits", "deriveKey"],  );}/*Given some key material and some random saltderive an AES-KW key using PBKDF2.*/function getKey(keyMaterial, salt) {  return window.crypto.subtle.deriveKey(    {      name: "PBKDF2",      salt,      iterations: 100000,      hash: "SHA-256",    },    keyMaterial,    { name: "AES-KW", length: 256 },    true,    ["wrapKey", "unwrapKey"],  );}/*Wrap the given key.*/async function wrapCryptoKey(keyToWrap) {  // get the key encryption key  const keyMaterial = await getKeyMaterial();  salt = window.crypto.getRandomValues(new Uint8Array(16));  const wrappingKey = await getKey(keyMaterial, salt);  return window.crypto.subtle.wrapKey("raw", keyToWrap, wrappingKey, "AES-KW");}/*Generate an encrypt/decrypt secret key,then wrap it.*/window.crypto.subtle  .generateKey(    {      name: "AES-GCM",      length: 256,    },    true,    ["encrypt", "decrypt"],  )  .then((secretKey) => wrapCryptoKey(secretKey))  .then((wrappedKey) => console.log(wrappedKey));

PKCS #8 wrap

This example wraps an RSA private signing key. It uses "pkcs8" as the export format andAES-GCM, with a password-derived key, to encrypt it.See the complete code on GitHub.

js
let salt;let iv;/*Get some key material to use as input to the deriveKey method.The key material is a password supplied by the user.*/function getKeyMaterial() {  const password = window.prompt("Enter your password");  const enc = new TextEncoder();  return window.crypto.subtle.importKey(    "raw",    enc.encode(password),    { name: "PBKDF2" },    false,    ["deriveBits", "deriveKey"],  );}/*Given some key material and some random saltderive an AES-GCM key using PBKDF2.*/function getKey(keyMaterial, salt) {  return window.crypto.subtle.deriveKey(    {      name: "PBKDF2",      salt,      iterations: 100000,      hash: "SHA-256",    },    keyMaterial,    { name: "AES-GCM", length: 256 },    true,    ["wrapKey", "unwrapKey"],  );}/*Wrap the given key.*/async function wrapCryptoKey(keyToWrap) {  // get the key encryption key  const keyMaterial = await getKeyMaterial();  salt = window.crypto.getRandomValues(new Uint8Array(16));  const wrappingKey = await getKey(keyMaterial, salt);  iv = window.crypto.getRandomValues(new Uint8Array(12));  return window.crypto.subtle.wrapKey("pkcs8", keyToWrap, wrappingKey, {    name: "AES-GCM",    iv,  });}/*Generate a sign/verify key pair,then wrap the private key.*/window.crypto.subtle  .generateKey(    {      name: "RSA-PSS",      // Consider using a 4096-bit key for systems that require long-term security      modulusLength: 2048,      publicExponent: new Uint8Array([1, 0, 1]),      hash: "SHA-256",    },    true,    ["sign", "verify"],  )  .then((keyPair) => wrapCryptoKey(keyPair.privateKey))  .then((wrappedKey) => {    console.log(wrappedKey);  });

SubjectPublicKeyInfo wrap

This example wraps an RSA public encryption key. It uses "spki" as the export format and AES-CBC, with a password-derived key, to encrypt it.See the complete code on GitHub.

js
let salt;let iv;/*Get some key material to use as input to the deriveKey method.The key material is a password supplied by the user.*/function getKeyMaterial() {  const password = window.prompt("Enter your password");  const enc = new TextEncoder();  return window.crypto.subtle.importKey(    "raw",    enc.encode(password),    { name: "PBKDF2" },    false,    ["deriveBits", "deriveKey"],  );}/*Given some key material and some random saltderive an AES-CBC key using PBKDF2.*/function getKey(keyMaterial, salt) {  return window.crypto.subtle.deriveKey(    {      name: "PBKDF2",      salt,      iterations: 100000,      hash: "SHA-256",    },    keyMaterial,    { name: "AES-CBC", length: 256 },    true,    ["wrapKey", "unwrapKey"],  );}/*Wrap the given key.*/async function wrapCryptoKey(keyToWrap) {  // get the key encryption key  const keyMaterial = await getKeyMaterial();  salt = window.crypto.getRandomValues(new Uint8Array(16));  const wrappingKey = await getKey(keyMaterial, salt);  iv = window.crypto.getRandomValues(new Uint8Array(16));  return window.crypto.subtle.wrapKey("spki", keyToWrap, wrappingKey, {    name: "AES-CBC",    iv,  });}/*Generate an encrypt/decrypt key pair,then wrap it.*/window.crypto.subtle  .generateKey(    {      name: "RSA-OAEP",      // Consider using a 4096-bit key for systems that require long-term security      modulusLength: 2048,      publicExponent: new Uint8Array([1, 0, 1]),      hash: "SHA-256",    },    true,    ["encrypt", "decrypt"],  )  .then((keyPair) => wrapCryptoKey(keyPair.publicKey))  .then((wrappedKey) => console.log(wrappedKey));

JSON Web Key wrap

This example wraps an ECDSA private signing key. It uses "jwk" as the export format and AES-GCM, with a password-derived key, to encrypt it.See the complete code on GitHub.

js
let salt;let iv;/*Get some key material to use as input to the deriveKey method.The key material is a password supplied by the user.*/function getKeyMaterial() {  const password = window.prompt("Enter your password");  const enc = new TextEncoder();  return window.crypto.subtle.importKey(    "raw",    enc.encode(password),    { name: "PBKDF2" },    false,    ["deriveBits", "deriveKey"],  );}/*Given some key material and some random saltderive an AES-GCM key using PBKDF2.*/function getKey(keyMaterial, salt) {  return window.crypto.subtle.deriveKey(    {      name: "PBKDF2",      salt,      iterations: 100000,      hash: "SHA-256",    },    keyMaterial,    { name: "AES-GCM", length: 256 },    true,    ["wrapKey", "unwrapKey"],  );}/*Wrap the given key.*/async function wrapCryptoKey(keyToWrap) {  // get the key encryption key  const keyMaterial = await getKeyMaterial();  salt = window.crypto.getRandomValues(new Uint8Array(16));  const wrappingKey = await getKey(keyMaterial, salt);  iv = window.crypto.getRandomValues(new Uint8Array(12));  return window.crypto.subtle.wrapKey("jwk", keyToWrap, wrappingKey, {    name: "AES-GCM",    iv,  });}/*Generate a sign/verify key pair,then wrap the private key*/window.crypto.subtle  .generateKey(    {      name: "ECDSA",      namedCurve: "P-384",    },    true,    ["sign", "verify"],  )  .then((keyPair) => wrapCryptoKey(keyPair.privateKey))  .then((wrappedKey) => console.log(wrappedKey));

Specifications

Specification
Web Cryptography Level 2
# SubtleCrypto-method-wrapKey

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp