Skip to main content
Version: 4.3.0

importKey()

The importKey() method of the SubtleCrypto interface imports a key: that is, it takes as input a key in an external, portable format and gives you a CryptoKey object that you can use.

The function accepts several import formats: see Supported formats for details.

Syntax​

importKey(format, keyData, algorithm, extractable, keyUsages)

Parameters​

  • format
  • keyData
    • : An ArrayBuffer, a TypedArray, a DataView, or a JSONWebKey object containing the key in the given format.
  • algorithm
    • : An object defining the type of key to import and providing extra algorithm-specific parameters.
      • For RSASSA-PKCS1-v1_5: Pass an RsaHashedImportParams object.
      • For HMAC: Pass an HmacImportParams object.
      • For ECDSA: Pass an EcKeyImportParams object.
      • For AES-CBC: Pass the string "AES-CBC" or an object of the form { "name": "AES-CBC" }. The key must be 128, 192 or 256 bits long, and can be used with encrypt() and decrypt().
      • For PBKDF2: Pass the string "PBKDF2" or an object of the form { "name": "PBKDF2" }. The key data is the password; only the raw format is supported, extractable must be false, and the key can be used with deriveBits().
  • extractable
    • : A boolean value indicating whether it will be possible to export the key.
  • keyUsages
    • : An Array indicating what can be done with the key. Possible array values are:
      • encrypt: The key may be used to encrypt messages.
      • decrypt: The key may be used to decrypt messages.
      • sign: The key may be used to sign messages.
      • verify: The key may be used to verify signatures.
      • deriveKey: The key may be used in deriving a new key.
      • deriveBits: The key may be used in deriving bits.
      • wrapKey: The key may be used to wrap a key.
      • unwrapKey: The key may be used to unwrap a key.

Return value​

A Promise that fulfills with the imported key as a CryptoKey object.

Exceptions​

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

  • SyntaxError
    • : Raised when keyUsages is empty but the unwrapped key is of type secret or private.
  • TypeError
    • : Raised when trying to use an invalid format or if the keyData is not suited for that format.

Supported formats​

This API currently supports four key import formats: raw, PKCS #8, SubjectPublicKeyInfo, and JSON Web Key.

Raw​

You can use this format to import AES, HMAC or PBKDF2 secret keys, or Elliptic Curve public keys.

In this format the key is supplied as an ArrayBuffer containing the raw bytes for the key.

PKCS #8​

You can use this format to import RSA or Elliptic Curve private keys.

The PKCS #8 format is defined in RFC 5208, using the ASN.1 notation.

importKey() expects to receive this object as an ArrayBuffer containing the DER-encoded form of the PrivateKeyInfo. A PEM file that starts with -----BEGIN PRIVATE KEY----- contains this data, encoded in base64. To get the DER data, remove the header and footer lines, and decode the base64 text. See the example in SubjectPublicKeyInfo.

SubjectPublicKeyInfo​

You can use this format to import RSA or Elliptic Curve public keys.

SubjectPublicKeyInfo is defined in RFC 5280, Section 4.1, using the ASN.1 notation.

importKey() expects to receive this object as an ArrayBuffer containing the DER-encoded form of the SubjectPublicKeyInfo. A PEM file that starts with -----BEGIN PUBLIC KEY----- contains this data, encoded in base64. To get the DER data, remove the header and footer lines, and decode the base64 text:

function pemToArrayBuffer(pem) {
const base64 = pem
.replace(/-----(BEGIN|END) [A-Z ]+-----/g, '')
.replace(/\s+/g, '');
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes.buffer;
}

const publicKey = await crypto.subtle.importKey(
'spki',
pemToArrayBuffer(pem),
{ name: 'ECDSA', namedCurve: 'P-256' },
false,
['verify'],
);

JSON Web Key​

You can use JSON Web Key format to import RSA or Elliptic Curve public or private keys, as well as AES and HMAC secret keys. PBKDF2 keys cannot be imported in this format.

JSON Web Key format is defined in RFC 7517. It describes a way to represent public, private, and secret keys as JSON objects.

A JSON Web Key looks something like this (this is an EC private key):

{
"crv": "P-384",
"d": "wouCtU7Nw4E8_7n5C1-xBjB4xqSb_liZhYMsy8MGgxUny6Q8NCoH9xSiviwLFfK_",
"ext": true,
"key_ops": ["sign"],
"kty": "EC",
"x": "SzrRXmyI8VWFJg1dPUNbFcc9jZvjZEfH7ulKI1UkXAltd7RGWrcfFxqyGPcwu6AQ",
"y": "hHUag3OvDzEr0uUQND4PXHQTXP5IDGdYhJhL-WLKjnGjQAw0rNGy5V29-aV-yseW"
};