Skip to main content
Version: 3.13.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
    • : A string describing the data format of the key to import. It can be one of the following:
  • keyData
    • : An ArrayBuffer, a TypedArray, a DataView, or a JSONWebKey object containing the key in the given format.
  • algorithm
  • 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 one key import/export format: JSON Web Key.

Raw

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

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

JSON Web Key

You can use JSON Web Key format to import or export RSA or Elliptic Curve public or private keys, as well as AES and HMAC secret keys.

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"
};