Open source

exportKey

The exportKey() method takes a CryptoKey object as input and exports it in an external, portable format.

Note that for a key to be exportable, it must have been created with the extractable flag set to true.

Usage

exportKey(format, key)

Parameters

NameTypeDescription
formatstringDefines the data format in which the key should be exported. Depending on the algorithm and key type, the data format could vary. Currently supported formats are raw, jwk, spki, and pkcs8.
keyCryptoKeyThe key to export.

Supported algorithms

AES-CBCAES-CTRAES-GCMAES-KWECDHECDSAHMACPBKDF2RSA-OAEPRSASSA-PKCS1-v1_5RSA-PSSEd25519X25519
✅ AesCbcParams✅ AesCtrParams✅ AesGcmParams❌✅ EcdhKeyDeriveParams✅ EcdsaParams✅ HmacKeyGenParams✅ Pbkdf2Params✅ RsaHashedImportParams✅ RsaHashedImportParams✅ RsaHashedImportParams✅✅

Supported formats

Ed25519 and X25519 public keys can be exported as raw, spki, or jwk; private keys can be exported as pkcs8 or jwk. Export requires an extractable key. A JWK export includes kty: 'OKP', crv, x, key_ops, and ext; private keys also include d.

  • ECDH and ECDSA algorithms have support for pkcs8, spki, raw and jwk formats.
  • RSA-OAEP, RSASSA-PKCS1-v1_5 and RSA-PSS algorithms have support for pkcs8, spki and jwk formats.
  • AES-* and HMAC algorithms have currently support for raw and jwk formats.
  • PBKDF2 algorithm has support for raw format only.
  • Ed25519 and X25519 public keys support raw, spki, and jwk; their private keys support pkcs8 and jwk. The raw format is for public keys only.

Return Value

A Promise that resolves to a new ArrayBuffer or an JsonWebKey object/dictionary containing the key.

Throws

TypeDescription
InvalidAccessErrorRaised when trying to export a non-extractable key.
NotSupportedErrorRaised when trying to export in an unknown format.
TypeErrorRaised when trying to use an invalid format.

Example

JavaScript
export default async function () {
  /**
   * Generate a symmetric key using the AES-CBC algorithm.
   */
  const generatedKey = await crypto.subtle.generateKey(
    {
      name: 'AES-CBC',
      length: '256',
    },
    true,
    ['encrypt', 'decrypt']
  );

  /**
   * Export the key in raw format.
   */
  const exportedKey = await crypto.subtle.exportKey('raw', generatedKey);

  /**
   * Reimport the key in raw format to verify its integrity.
   */
  const importedKey = await crypto.subtle.importKey('raw', exportedKey, 'AES-CBC', true, [
    'encrypt',
    'decrypt',
  ]);

  console.log(JSON.stringify(importedKey));
}