W3C

Web Cryptography API

W3C Last Call Working Draft 25 March 2014

This version:
http://www.w3.org/TR/2014/WD-WebCryptoAPI-20140325/
Latest published version:
http://www.w3.org/TR/WebCryptoAPI/
Latest Editor’s Draft:
http://dvcs.w3.org/hg/webcrypto-api/raw-file/tip/spec/Overview.html
Previous Version(s):
http://www.w3.org/TR/2013/WD-WebCryptoAPI-20130625/
Editors:
Ryan Sleevi, Google, Inc. <sleevi@google.com>
Mark Watson, Netflix <watsonm@netflix.com>
Participate:

Send feedback to public-webcrypto-comments@w3.org (archives), or file a bug (see existing bugs).


Abstract

This specification describes a JavaScript API for performing basic cryptographic operations in web applications, such as hashing, signature generation and verification, and encryption and decryption. Additionally, it describes an API for applications to generate and/or manage the keying material necessary to perform these operations. Uses for this API range from user or service authentication, document or code signing, and the confidentiality and integrity of communications.

Editorial note

There are 19 further editorial notes in the document.

Status of this Document

Publication as a Last Call Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

This document is the 25 March 2014 Last Call Working Draft of the Web Cryptography API specification. Please send comments about this document to public-webcrypto-comments@w3.org (archived).

This document is produced by the Web Cryptography WG of the W3C.

Implementors should be aware that this specification is not stable. Implementors who are not taking part in the discussions are likely to find the specification changing out from under them in incompatible ways. Vendors interested in implementing this specification before it eventually reaches the Candidate Recommendation stage should join the mailing lists that follow and take part in the discussions.

This document was published by the Web Cryptography Working Group as a Last Call Working Draft. This document is intended to become a W3C Recommendation. If you wish to make comments regarding this document, please send them to public-webcrypto-comments@w3.org, the W3C's public email list for issues related to Web Cryptography. Archives of the public list and archives of the member's-only list are available. The Last Call period ends 20 May 2014. All comments are welcome.

In particular, the Web Cryptography Working Group invites discussion and feedback on this draft document by web developers, companies, standardization bodies or forums interested in deployment of secure services with web applications. Specifically, Web Cryptography Working Group is looking for priority feedback on:

Changes made to this document can be found in the W3C public Mercurial server.

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

Table of Contents

1. Introduction

This section is non-normative.

The Web Cryptography API defines a low-level interface to interacting with cryptographic key material that is managed or exposed by user agents. The API itself is agnostic of the underlying implementation of key storage, but provides a common set of interfaces that allow rich web applications to perform operations such as signature generation and verification, hashing and verification, encryption and decryption, without requiring access to the raw keying material.

Cryptographic transformations are exposed via the SubtleCrypto interface, which defines a common set of methods and events for dealing with initialization, processing data, and completing the operation to yield the final output. In addition to operations such as signature generation and verification, hashing and verification, and encryption and decryption, the API provides interfaces for key generation, key derivation, key import and export, and key discovery.

2. Use Cases

This section is non-normative

2.1. Multi-factor Authentication

A web application may wish to extend or replace existing username/password based authentication schemes with authentication methods based on proving that the user has access to some secret keying material. Rather than using transport-layer authentication, such as TLS client certificates, the web application may wish to provide a rich user experience by providing authentication within the application itself.

Using the Web Cryptography API, such an application could locate suitable client keys, which may have been previously generated via the user agent or pre-provisioned out-of-band by the web application. It could then perform cryptographic operations such as decrypting an authentication challenge followed by signing an authentication response.

Further, the authentication data could be further enhanced by binding the authentication to the TLS session that the client is authenticating over, by deriving a key based on properties of the underlying transport.

If a user did not already have a key associated with their account, the web application could direct the user agent to either generate a new key or to re-use an existing key of the user's choosing.

2.2. Protected Document Exchange

When exchanging documents that may contain sensitive or personal information, a web application may wish to ensure that only certain users can view the documents, even after they have been securely received, such as over TLS. One way that a web application can do so is by encrypting the documents with a secret key, and then wrapping that key with the public keys associated with authorized users.

When a user agent navigates to such a web application, the application may send the encrypted form of the document. The user agent is then instructed to unwrap the encryption key, using the user's private key, and from there, decrypt and display the document.

2.3. Cloud Storage

When storing data with remote service providers, users may wish to protect the confidentiality of their documents and data prior to uploading them. The Web Cryptography API allows an application to have a user select a private or secret key, to either derive encryption keys from the selected key or to directly encrypt documents using this key, and then to upload the transformed/encrypted data to the service provider using existing APIs.

This use case is similar to the Protected Document Exchange use case because Cloud Storage can be considered as a user exchanging protected data with himself in the future.

2.4. Document Signing

A web application may wish to accept electronic signatures on documents, in lieu of requiring physical signatures. An authorized signature may use a key that was pre-provisioned out-of-band by the web application, or it may be using a key that the client generated specifically for the web application.

The web application must be able to locate any appropriate keys for signatures, then direct the user to perform a signing operation over some data, as proof that they accept the document.

2.5. Data Integrity Protection

When caching data locally, an application may wish to ensure that this data cannot be modified in an offline attack. In such a case, the server may sign the data that it intends the client to cache, with a private key held by the server. The web application that subsequently uses this cached data may contain a public key that enables it to validate that the cache contents have not been modified by anyone else.

2.6. Secure Messaging

In addition to a number of web applications already offering chat based services, the rise of WebSockets and RTCWEB allows a great degree of flexibility in inter-user-agent messaging. While TLS/DTLS may be used to protect messages to web applications, users may wish to directly secure messages using schemes such as off-the-record (OTR) messaging.

The Web Cryptography API enables OTR, by allowing key agreement to be performed so that the two parties can negotiate shared encryption keys and message authentication code (MAC) keys, to allow encryption and decryption of messages, and to prevent tampering of messages through the MACs.

2.7. Javascript Object Signing and Encryption (JOSE)

A web application wishes to make use of the structures and format of messages defined by the IETF Javascript Object Signing and Encryption (JOSE) Working Group. The web application wishes to manipulate public keys encoded in the JSON key format (JWK), messages that have been integrity protected using digital signatures or MACs (JWS), or that have been encrypted (JWE).

3. Conformance

As well as sections marked as non-normative, all authoring guidelines, diagrams, examples, and notes in this specification are non-normative. Everything else in this specification is normative.

The keywords MUST, MUST NOT, REQUIRED, SHALL, SHALL NOT, RECOMMENDED, MAY, OPTIONAL, in this specification are to be interpreted as described in Key words for use in RFCs to Indicate Requirement Levels [RFC2119].

The following conformance classes are defined by this specification:

conforming user agent

A user agent is considered to be a conforming user agent if it satisfies all of the MUST-, REQUIRED- and SHALL-level criteria in this specification that apply to implementations. This specification uses both the terms "conforming user agent" and "user agent" to refer to this product class.

User agents MAY implement algorithms in this specification in any way desired, so long as the end result is indistinguishable from the result that would be obtained from the specification's algorithms.

User agents that use ECMAScript to implement the APIs defined in this specification MUST implement them in a manner consistent with the ECMAScript Bindings defined in the Web IDL specification [WEBIDL] as this specification uses that specification and terminology.

Unless otherwise stated, string comparisons are done in a case-sensitive manner. String literals in this specification written in monospace font like "this" do not include the enclosing quotes.

4. Scope

This section is non-normative.

4.1. Level of abstraction

The specification attempts to focus on the common functionality and features between various platform-specific or standardized cryptographic APIs, and avoid features and functionality that are specific to one or two implementations. As such this API allows key generation, management, and exchange with a level of abstraction that avoids developers needing to care about the implementation of the underlying key storage. The API is focused specifically around Key objects, as an abstraction for the underlying raw cryptographic keying material. The intent behind this is to allow an API that is generic enough to allow conforming user agents to expose keys that are stored and managed directly by the user agent, that may be stored or managed using isolated storage APIs such as per-user key stores provided by some operating systems, or within key storage devices such as secure elements, while allowing rich web applications to manipulate the keys and without requiring the web application be aware of the nature of the underlying key storage.

4.2. Cryptographic algorithms

Because the underlying cryptographic implementations will vary between conforming user agents, and may be subject to local policy, including but not limited to concerns such as government or industry regulation, security best practices, intellectual property concerns, and constrained operational environments, this specification does not dictate a mandatory set of algorithms that MUST be implemented. Instead, it defines a common set of bindings that can be used in an algorithm-independent manner, a common framework for discovering if a user agent or key handle supports the underlying algorithm, and a set of conformance requirements for the behaviours of individual algorithms, if implemented.

4.3. Operations

Although the API does not expose the notion of cryptographic providers or modules, each key is internally bound to a cryptographic provider or module, so web applications can rest assured that the right cryptographic provider or module will be used to perform cryptographic operations involving that key.

4.4. Out of scope

This API, while allowing applications to generate, retrieve, and manipulate keying material, does not specifically address the provisioning of keys in particular types of key storage, such as secure elements or smart cards. This is due to such provisioning operations often being burdened with vendor-specific details that make defining a vendor-agnostic interface an unsuitably unbounded task. Additionally, this API does not deal with or address the discovery of cryptographic modules, as such concepts are dependent upon the underlying user agent and are not concepts that are portable between common operating systems, cryptographic libraries, and implementations.

5. Security considerations

This section is non-normative.

5.1. Security considerations for implementers

User agents should take care before exposing keys that were not explicitly generated via the API in this specification or exposing keys that were generated in the context of other origins. Two applications with access to the same key handle may be able to spoof messages to each other, as both valid and hostile messages will appear to be valid for the given key. Because of this, user agents are recommended to obtain express permission from the user before re-using keys, unless there is a prearranged trust relationship.

User agents should be aware of the security considerations of each algorithm implemented and exposed to applications. For a number of algorithms, their cryptographic strength is relative to the amount of work necessary to compute the result, whether this be through the generation of significantly large prime numbers or through the repeatedly iterating through the same algorithm to reduce its susceptibility to brute force. Implementations should therefore take measures to ensure against misuse. Such measures may include requiring express user permission to compute some expensive operations, rate limiting the number of times the application may call certain APIs/algorithms, and defining implementation-specific upper limits for inputs such as key sizes or iteration counts, as appropriate for the device on which the implementation executes.

In some cases, the same underlying cryptographic key material may be re-usable for multiple algorithms. One such example is an RSA key, which may be used for both signing and encryption, or with RSA-PKCS1v1.5 and RSA-PSS. In some cases, the re-use of this key material may undermine the security properties of the key and allow applications to recover the raw material.

Editorial note
  • ISSUE-33 One proposed technical solution for user agents is to implement "key tainting", in which it records how a particular key has been used (eg: algorithms, parameters), and prevents it from being re-used in a manner that is unsafe or contrary to the security - such as preventing a PKCS1-v1.5 key from being used with RSA-PSS, or preventing an RSA-OAEP w/ MGF1-SHA1 from being used with RSA-OAEP w/ MGF1-SHA256. Questions exist about whether this should be encouraged or permitted, and the interoperability concerns it might cause.

5.2. Security considerations for authors

While this API provides important functionality for the development of secure applications, it does not attempt to provide a mitigation for existing threats to the web security model, such as script injection or hostile intermediaries. As such, application developers must take care to ensure applications are secured against common and traditional attacks, such as script injection, by making use of appropriate existing functionality such as Content Security Policy and the use of TLS.

This API includes a variety of cryptographic operations, some of which may have known security issues when used inappropriately. Application developers should take care to review the appropriate cryptographic literature before making use of certain algorithms, and should avoid attempting to develop new cryptographic protocols whenever possible.

While the API in this specification provides a means to protect keys from future access by web applications, it makes no statements as to how the actual keying material will be stored by an implementation. As such, although a key may be inaccessible to web content, it should not be presumed that it is inaccessible to end-users. For example, a conforming user agent may choose to implement key storage by storing key material in plain text on device storage. Although the user agent prevents access to the raw keying material to web applications, any user with access to device storage may be able to recover the key.

6. Privacy considerations

This section is non-normative.

Fingerprinting
Malicious applications may be able to fingerprint users or user agents by detecting or enumerating the list of algorithms that are supported. This is especially true if an implementation exposes details about users' smart cards or secure element storage, as the combination of algorithms supported by such devices may be used to fingerprint devices more accurately than just the particular user agent.
Tracking
If user agents permit keys to be re-used between origins, without performing any secondary operations such as key derivation that includes the origin, then it may be possible for two origins to collude and track a unique user by recording their ability to access a common key.
Super-cookies
With the exception of ephemeral keys, its often desirable for applications to strongly associate users with keys. These associations may be used to enhance the security of authenticating to the application, such as using a key stored in a secure element as a second factor, or may be used by users to assert some identity, such as an e-mail signing identity. As such, these keys often live longer than their counterparts such as usernames and passwords, and it may be undesirable or prohibitive for users to revoke these keys. Because of this, keys may exist longer than the lifetime of the browsing context [HTML] and beyond the lifetime of items such as cookies, thus presenting a risk that a user may be tracked even after clearing such data. This is especially true for keys that were pre-provisioned for particular origins and for which no user interaction was provided.

7. Dependencies

This specification relies on underlying specifications.

DOM

A conforming user agent MUST support at least the subset of the functionality defined in DOM4 that this specification relies upon; in particular, it MUST support Promises. [DOM4]

HTML

A conforming user agent MUST support at least the subset of the functionality defined in HTML that this specification relies upon; in particular, it MUST support event loops and event handler IDL attributes. [HTML]

Web IDL

A conforming user agent MUST be a conforming implementation of the IDL fragments in this specification, as described in the Web IDL specification. [WebIDL]

Typed Arrays

A conforming user agent MUST support the Typed Arrays specification [TypedArrays].

8. Terminology

The terms and algorithms document, event handler IDL attributes, event handler event type, origin, same origin, URL, event loops, task, task source, queue a task, and structured clone, are defined by the HTML specification [HTML].

Comparing two strings in a case-sensitive manner means comparing them exactly, code point for code point.

When this specification says to terminate the algorithm, the user agent must terminate the algorithm after finishing the step it is on. The algorithm referred to is the set of specification-defined processing steps, rather than the underlying cryptographic algorithm that may be in the midst of processing.

When this specification says to parse an ASN.1 structure, the user agent must perform the following steps:

  1. Let data be a sequence of bytes to be parsed.

  2. Let structure be the ASN.1 structure to be parsed.

  3. Let exactData be an optional boolean value. If it is not supplied, let it be initialized to true.

  4. Parse data according to the Distinguished Encoding Rules of X.690 (11/08), using structure as the ASN.1 structure to be decoded.

  5. If exactData was specified, and all of the bytes of data were not consumed during the parsing phase, then return an error named DataError.

  6. Return the parsed ASN.1 structure.

When this specification says to parse a subjectPublicKeyInfo, the user agent must parse an ASN.1 structure, with data set to the sequence of bytes to be parsed, structure as the ASN.1 structure of subjectPublicKeyInfo, as specified in RFC 5280, and exactData set to true.

When this specification says to parse a PrivateKeyInfo, the user agent must parse an ASN.1 structure with data set to the sequence of bytes to be parsed, structure as the ASN.1 structure of PrivateKeyInfo, as specified in RFC 5208, and exactData set to true.

When this specification says to parse a JWK, the user agent must run the following steps:

  1. Let data be the sequence of bytes to be parsed.

  2. Let json be the unicode string that results from interpreting data according to UTF-8.

  3. Let result be the result of translating json into an internal object using the grammar specified in Section 15.12 of ECMA 262.

  4. If result does not describe an Object type, then return an error named DataError.

  5. If the "kty" field of result is not present, or is not a string value, then return an error named DataError.

  6. Return result.

When this specification says to calculate the usage intersection of two arrays, a and b the result shall be an array containing each recognised key usage value that appears in both a and b, in the order listed in the list of recognised key usage values, where a value is said to appear in an array if an element of the array exists that is a case-sensistive string match for that value.

When this specification says to calculate the normalized value of a usages list, usages the result shall be the usage intersection of usages and an array containing all recognised key usage values.

9. RandomSource interface

IDL

[NoInterfaceObject]
interface RandomSource {
  ArrayBufferView getRandomValues(ArrayBufferView array);
};
        

9.1. Description

The RandomSource interface represents an interface to a cryptographically strong pseudo-random number generator seeded with truly random values.

Note
Implementations should generate cryptographically random values using well-established cryptographic pseudo-random number generators seeded with high-quality entropy, such as from an operating-system entropy source (e.g., "/dev/urandom"). This specification provides no lower-bound on the information theoretic entropy present in cryptographically random values, but implementations should make a best effort to provide as much entropy as practicable.
Note
This interface defines a synchronous method for obtaining cryptographically random values. While some devices and implementations may support truly random cryptographic number generators or provide interfaces that block when there is insufficient entropy, implementations are discouraged from using these sources when implementing getRandomValues, both for performance and to avoid depleting the system of entropy. Instead, these sources should be used to seed a cryptographic pseudo-random number generator that can then return suitable values efficiently.

9.2. Methods and Parameters

9.2.1. The getRandomValues method

The getRandomValues method generates cryptographically random values. It must act as follows:

  1. If array is not of an integer type (i.e., Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, or Uint32Array), throw a TypeMismatchError and terminate the algorithm.

  2. If the byteLength of array is greater than 65536, throw a QuotaExceededError and terminate the algorithm.

  3. Overwrite all elements of array with cryptographically random values of the appropriate type.

  4. Return array.

Note

Do not generate keys using the getRandomValues method. Use the generateKey method instead.

10. Algorithm dictionary

The Algorithm object is a dictionary object [WebIDL] which is used to specify an algorithm and any additional parameters required to fully specify the desired operation.

IDL

// TBD: ISSUE-28
typedef (Algorithm or DOMString) AlgorithmIdentifier;

dictionary Algorithm {
  DOMString name;
};
        

10.1. Algorithm Dictionary Members

name
The name of the registered algorithm to use.

11. KeyAlgorithm interface

The KeyAlgorithm interface represents information about the contents of a given Key object.

IDL

[NoInterfaceObject]
interface KeyAlgorithm {
  readonly attribute DOMString name
};
        

11.1. Description

This section is non-normative

The KeyAlgorithm interface is a supplemental interface used to reflect the static, public properties of a Key back to an application. These properties can be used for determination of strength (e.g.: an attribute that indicates the size of the key or the parameters of its creation) as well as for protocol negotiations (e.g.: a particular instance of an inner hash).

11.2. KeyAlgorithm interface members

name
The name of the algorithm used to generate the Key

12. Key interface

The Key object represents an opaque reference to keying material that is managed by the user agent.

IDL

typedef DOMString KeyType;

typedef DOMString KeyUsage;

interface Key {
  readonly attribute KeyType type;
  readonly attribute boolean extractable;
  readonly attribute KeyAlgorithm algorithm;
  readonly attribute KeyUsage[] usages;
};
        

12.1. Description

This section is non-normative

This specification provides a uniform interface for many different kinds of keying material managed by the user agent. This may include keys that have been generated by the user agent, derived from other keys by the user agent, imported to the user agent through user actions or using this API, pre-provisioned within software or hardware to which the user agent has access or made available to the user agent in other ways. The term key refers broadly to any keying material including actual keys for cryptographic operations and secret values obtained within key derivation or exchange operations.

The Key object is not required to directly interface with the underlying key storage mechanism, and may instead simply be a reference for the user agent to understand how to obtain the keying material when needed, eg. when performing a cryptographic operation.

12.2. Key interface data types

KeyType
The type of a key. The recognized key type values are "public", "private" and "secret". Opaque keying material, including that used for symmetric algorithms, is represented by "secret", while keys used as part of asymmetric algorithms composed of public/private keypairs will be either "public" or "private".
KeyUsage
A type of operation that may be performed using a key. The recognized key usage values are "encrypt", "decrypt", "sign", "verify", "deriveKey", "deriveBits", "wrapKey" and "unwrapKey".

12.3. Key interface members

type
The type of the underlying key.
extractable
Whether or not the raw keying material may be exported by the application.
algorithm
The KeyAlgorithm used to generate the key.
usages
An Array of KeyUsages that indicate what cryptographic operations may be used with this key.

12.4. Structured clone algorithm

When a user agent is required to obtain a structured clone of a Key object, it must run the following steps.

  1. Let input and memory be the corresponding inputs defined by the internal structured cloning algorithm, where input represents a Key object to be cloned.
  2. Let output be a newly constructed Key object.
  3. Let the following attributes of output be equal to the value obtained by invoking the internal structured clone algorithm recursively, using the corresponding attribute on input as the new "input" argument and memory as the new "memory" argument:
  4. Let output refer to the same underlying cryptographic material and cryptographic material key storage of input.
Note
Implementation Note: When performing the structured clone algorithm for a Key object, it is important that the underlying cryptographic key material not be exposed to a JavaScript implementation. Such a situation may arise if an implementation fails to implement the structured clone algorithm correctly, such as by allowing a Key object to be serialized as part of a structured clone implementation, but then deserializing it as a DOMString, rather than as a Key object.

13. Crypto interface

IDL

interface Crypto {
  readonly attribute SubtleCrypto subtle;
};

Crypto implements RandomSource;

partial interface Window {
  readonly attribute Crypto crypto;
};
        

14. SubtleCrypto interface

IDL

typedef DOMString KeyFormat;

typedef (ArrayBuffer or ArrayBufferView) CryptoOperationData;

interface SubtleCrypto {
  Promise<any> encrypt(AlgorithmIdentifier algorithm,
                       Key key,
                       CryptoOperationData data);
  Promise<any> decrypt(AlgorithmIdentifier algorithm,
                       Key key,
                       CryptoOperationData data);
  Promise<any> sign(AlgorithmIdentifier algorithm,
                    Key key,
                    CryptoOperationData data);
  Promise<any> verify(AlgorithmIdentifier algorithm,
                      Key key,
                      CryptoOperationData signature,
                      CryptoOperationData data);
  Promise<any> digest(AlgorithmIdentifier algorithm,
                      CryptoOperationData data);

  Promise<any> generateKey(AlgorithmIdentifier algorithm,
                          boolean extractable,
                          KeyUsage[] keyUsages );
  Promise<any> deriveKey(AlgorithmIdentifier algorithm,
                         Key baseKey,
                         AlgorithmIdentifier derivedKeyType,
                         boolean extractable,
                         KeyUsage[] keyUsages );
  Promise<any> deriveBits(AlgorithmIdentifier algorithm,
                          Key baseKey,
                          unsigned long length);
  
  // TBD: ISSUE-35
  Promise<any> importKey(KeyFormat format,
                         CryptoOperationData keyData,
                         AlgorithmIdentifier? algorithm,
                         boolean extractable,
                         KeyUsage[] keyUsages );
  Promise<any> exportKey(KeyFormat format, Key key);

  // Note: wrapKey and unwrapKey remain "Features at Risk"
  Promise<any> wrapKey(KeyFormat format,
                       Key key,
                       Key wrappingKey,
                       AlgorithmIdentifier wrapAlgorithm);
  Promise<any> unwrapKey(KeyFormat format,
                         CryptoOperationData wrappedKey,
                         Key unwrappingKey,
                         AlgorithmIdentifier unwrapAlgorithm,
                         AlgorithmIdentifier? unwrappedKeyAlgorithm,
                         boolean extractable,
                         KeyUsage[] keyUsages );
};
        
Editorial note
  • ISSUE-35: The specification for wrapKey/unwrapKey does not specify how authors that do not trust the execution environment may indicate required attributes for keys that are unwrapped. An example is unwrapping a key with a non-extractable key, marking the newly unwrapped key as non extractable, and then further indicating that all keys unwrapped with the newly unwrapped key are also non-extractable.

14.1. Description

This section is non-normative.

The SubtleCrypto interface provides a set of methods for dealing with low-level cryptographic primitives and algorithms. It is named SubtleCrypto to reflect the fact that many of these algorithms have subtle usage requirements in order to provide the required algorithmic security guarantees.

For example, the direct use of an unauthenticated encryption scheme, such as AES in counter mode, gives potential attackers the ability to manipulate bits in the output by manipulating bits in the input, compromising the integrity of the message. However, AES-CTR can be used securely in combination with other cryptographic primitives, such as message authentication codes, to ensure the integrity of the protected message, but only when the message authentication code is constructed over the encrypted message and IV.

Developers making use of the SubtleCrypto interface are expected to be aware of the security concerns associated with both the design and implementation of the various algorithms provided. The raw algorithms are provided in order to allow developers maximum flexibility in implementing a variety of protocols and applications, each of which may represent the composition and security parameters in a unique manner that necessitate the use of the raw algorithms.

14.2. Data Types

KeyFormat
Specifies a serialization format for a key. The recognized key format values are:
raw
An unformatted sequence of bytes. Intended for secret keys.
pkcs8
The DER encoding of the PrivateKeyInfo structure from RFC 5208.
spki
The DER encoding of the SubjectPublicKeyInfo structure from RFC 5280.
jwk
The key is represented as JSON according to the JSON Web Key format.

14.3. Methods and Parameters

Note

All errors are reported asynchronously by calling the reject handler of the returned Promise. This includes WebIDL type mapping errors.

14.3.1. The encrypt method

The encrypt method returns a new Promise object that will encrypt data using the specified AlgorithmIdentifier with the supplied Key. It must act as follows:

  1. Let algorithm, key and data be the algorithm, key and data parameters passed to the encrypt method, respectively.

  2. Let promise be a new Promise object and resolver its associated resolver object.

  3. Return promise and asynchronously perform the remaining steps.

  4. If the following steps or referenced procedures say to return an error, execute resolver's reject(value) algorithm, with the returned error as the value argument and then terminate the algorithm.

  5. Perform type mapping as specified in [WEBIDL] for key and data.

  6. Let normalizedAlgorithm be the result of normalizing algorithm to Algorithm.

  7. If the name member of normalizedAlgorithm does not identify a registered algorithm that supports the encrypt operation, then return an error named NotSupportedError.

  8. If the usages attribute of key does not contain an entry that is "encrypt", then return an error named InvalidAccessError.

  9. Let ciphertext be the result of performing the encrypt operation specified by normalizedAlgorithm using algorithm and key and with data as plaintext.

  10. Execute resolver's resolve(value) algorithm, with ciphertext as value.

14.3.2. The decrypt method

The decrypt method returns a new Promise object that will decrypt data using the specified AlgorithmIdentifier with the supplied Key. It must act as follows:

  1. Let algorithm, key and data be the algorithm, key and data parameters passed to the decrypt method, respectively.

  2. Let promise be a new Promise object and resolver its associated resolver object.

  3. Return promise and asynchronously perform the remaining steps.

  4. If the following steps or referenced procedures say to return an error, execute resolver's reject(value) algorithm, with the returned error as the value argument and then terminate the algorithm.

  5. Perform type mapping as specified in [WEBIDL] for key and data.

  6. Let normalizedAlgorithm be the result of normalizing algorithm to Algorithm.

  7. If the name member of normalizedAlgorithm does not identify a registered algorithm that supports the decrypt operation, then return an error named NotSupportedError.

  8. If the usages attribute of key does not contain an entry that is "decrypt", then return an error named InvalidAccessError.

  9. Let plaintext be the result of performing the decrypt operation specified by normalizedAlgorithm using key and algorithm and with data as ciphertext.

  10. Execute resolver's resolve(value) algorithm, with plaintext as value.

14.3.3. The sign method

The sign method returns a new Promise object that will sign data using the specified AlgorithmIdentifier with the supplied Key. It must act as follows:

  1. Let algorithm, key and data be the algorithm, key and data parameters passed to the sign method, respectively.

  2. Let promise be a new Promise object and resolver its associated resolver object.

  3. Return promise and asynchronously perform the remaining steps.

  4. If the following steps or referenced procedures say to return an error, execute resolver's reject(value) algorithm, with the returned error as the value argument and then terminate the algorithm.

  5. Perform type mapping as specified in [WEBIDL] for key and data.

  6. Let normalizedAlgorithm be the result of normalizing algorithm to Algorithm.

  7. If the name member of normalizedAlgorithm does not identify a registered algorithm that supports the sign operation, then return an error named NotSupportedError.

  8. If the usages attribute of key does not contain an entry that is "sign", then return an error named InvalidAccessError.

  9. Let result be the result of performing the sign operation specified by normalizedAlgorithm uaing key and algorithm and with data as message.

  10. Execute resolver's resolve(value) algorithm, with result as value.

14.3.4. The verify method

The verify method returns a new Promise object that will verify data using the specified AlgorithmIdentifier with the supplied Key. It must act as follows:

  1. Let algorithm, key, signature and data be the algorithm, key, signature and data parameters passed to the verify method, respectively.

  2. Let promise be a new Promise object and resolver its associated resolver object.

  3. Return promise and asynchronously perform the remaining steps.

  4. If the following steps or referenced procedures say to return an error, execute resolver's reject(value) algorithm, with the returned error as the value argument and then terminate the algorithm.

  5. Perform type mapping as specified in [WEBIDL] for key, data and signature.

  6. Let normalizedAlgorithm be the result of normalizing algorithm to Algorithm.

  7. If the name member of normalizedAlgorithm does not identify a registered algorithm that supports the verify operation, then return an error named NotSupportedError.

  8. If the usages attribute of key does not contain an entry that is "verify", then return an error named InvalidAccessError.

  9. Let result be the result of performing the verify operation specified by normalizedAlgorithm using key, algorithm and signature and with data as message.

  10. Execute resolver's resolve(value) algorithm, with result as value.

14.3.5. The digest method

The digest method returns a new Promise object that will digest data using the specified AlgorithmIdentifier. It must act as follows:

  1. Let algorithm and data be the algorithm and data parameters passed to the digest method, respectively.

  2. Let promise be a new Promise object and resolver its associated resolver object.

  3. Return promise and asynchronously perform the remaining steps.

  4. If the following steps or referenced procedures say to return an error, execute resolver's reject(value) algorithm, with the returned error as the value argument and then terminate the algorithm.

  5. Perform type mapping as specified in [WEBIDL] for data.

  6. Let normalizedAlgorithm be the result of normalizing algorithm to Algorithm.

  7. If the name member of normalizedAlgorithm does not identify a registered algorithm that supports the digest operation, then return an error named NotSupportedError.

  8. Let result be the result of performing the digest operation specified by normalizedAlgorithm using algorithm, with data as message.

  9. Execute resolver's resolve(value) algorithm, with result as value.

14.3.6. The generateKey method

When invoked, generateKey MUST perform the following steps:

  1. Let algorithm, extractable and usages be the algorithm, extractable and keyUsages parameters passed to the generateKey method, respectively.

  2. Let promise be a new Promise object and resolver its associated resolver object.

  3. Return promise and asynchronously perform the remaining steps.

  4. If the following steps or referenced procedures say to return an error, execute resolver's reject(value) algorithm, with the returned error as the value argument and then terminate the algorithm.

  5. Perform type mapping as specified in [WEBIDL] for extractable and usages.

  6. Let normalizedAlgorithm be the result of normalizing algorithm to Algorithm.

  7. If the name member of normalizedAlgorithm does not identify a registered algorithm that supports the generate key operation, then return an error named NotSupportedError.

  8. If usages includes a value that is not a recognized key usage value, then return an error named InvalidAccessError.

  9. Let result be the result of executing the generate key operation specified by normalizedAlgorithm using algorithm, extractable and usages.

  10. Execute resolver's resolve(value) algorithm, with result as the value argument.

14.3.7. The deriveKey method

When invoked, deriveKey MUST perform the following steps:

  1. Let algorithm, baseKey, derivedKeyType, extractable and usages be the algorithm, baseKey, derivedKeyType, extractable and keyUsages parameters passed to the deriveKey method, respectively.

  2. Let promise be a new Promise object and resolver its associated resolver object.

  3. Return promise and asynchronously perform the remaining steps.

  4. If the following steps or referenced procedures say to return an error, execute resolver's reject(value) algorithm, with the returned error as the value argument and then terminate the algorithm.

  5. Perform type mapping as specified in [WEBIDL] for baseKey, extractable and usages.

  6. Let normalizedAlgorithm be the result of normalizing algorithm to Algorithm.

  7. If the name member of normalizedAlgorithm does not identify a registered algorithm that supports the derive bits operation, then return an error named NotSupportedError.

  8. Let normalizedDerivedKeyAlgorithm be the result of normalizing derivedKeyType to Algorithm.

  9. If the name member of normalizedDerivedKeyAlgorithm does not identify a registered algorithm that supports the get key length and import key operations, then return an error named NotSupportedError.

  10. If the usages attribute of baseKey does not contain an entry that is "deriveKey", then return an error named InvalidAccessError.

  11. If usages includes a value that is not a recognized key usage value, then return an error named SyntaxError.

  12. Let length be the result of executing the get key length algorithm specified by normalizedDerivedKeyAlgorithm using derivedKeyType.

  13. Let secret be the result of executing the derive bits operation specified by normalizedAlgorithm using key, algorithm and length.

  14. Let result be the result of executing the import key operation specified by normalizedDerivedKeyAlgorithm using "raw" as format, secret as keyData, derivedKeyType as algorithm and using extractable and usages.

  15. Execute resolver's resolve(value) algorithm, with result as the value argument.

14.3.8. The deriveBits method

When invoked, deriveBits MUST perform the following steps:

  1. Let algorithm, baseKey and length, be the algorithm, baseKey and length parameters passed to the deriveBits method, respectively.

  2. Let promise be a new Promise object and resolver its associated resolver object.

  3. Return promise and asynchronously perform the remaining steps.

  4. If the following steps or referenced procedures say to return an error, execute resolver's reject(value) algorithm, with the returned error as the value argument and then terminate the algorithm.

  5. Perform type mapping as specified in [WEBIDL] for baseKey and length.

  6. Let normalizedAlgorithm be the result of normalizing algorithm to Algorithm.

  7. If the name member of normalizedAlgorithm does not identify a registered algorithm that supports the derive bits operation, then return an error named NotSupportedError.

  8. If the usages attribute of baseKey does not contain an entry that is "deriveBits", then return an error named InvalidAccessError.

  9. Let result be a new ArrayBuffer containing the result of executing the derive bits operation specified by normalizedAlgorithm using baseKey, algorithm and length.

  10. Execute resolver's resolve(value) algorithm, with result as the value argument.

14.3.9. The importKey method

When invoked, the importKey method MUST perform the following steps:

  1. Let format, keyData, algorithm, extractable and usages, be the format, keyData, algorithm, extractable and keyUsages parameters passed to the importKey method, respectively.

  2. Let promise be a new Promise object and resolver its associated resolver object.

  3. Return promise and asynchronously perform the remaining steps.

  4. If the following steps or referenced procedures say to return an error, execute resolver's reject(value) algorithm, with the returned error as the value argument and then terminate the algorithm.

  5. Perform type mapping as specified in [WEBIDL] for format, keyData, extractable and usages.

  6. Let normalizedAlgorithm be the result of normalizing algorithm to Algorithm.

  7. If the name member of normalizedAlgorithm does not identify a registered algorithm that supports the import key operation, then return an error named NotSupportedError.

  8. If format is not a recognized key format value, then return an error named SyntaxError.

  9. If usages includes a value that is not a recognized key usage value, then return an error named SyntaxError.

  10. Let result be the Key object that results from performing the import key operation specified by normalizedAlgorithm using keyData, algorithm, format, extractable and usages.

  11. Execute resolver's resolve(value) algorithm, with result as the value argument.

Editorial note
Bug 24963 - There is an open question as to whether/how to support importing keys when format is jwk. As currently specified, it is a JSON-encoded Javascript object, converted to a UTF-8 byte sequence, with the raw bytes provided via CryptoOperationData. A separate proposal exists to handle this via IDL, permitting importing JavaScript objects directly when importing with jwk.

14.3.10. The exportKey method

When invoked, the exportKey method MUST perform the following steps:

  1. Let format and key be the format and key parameters passed to the importKey method, respectively.

  2. Let promise be a new Promise object and resolver its associated resolver object.

  3. Return promise and asynchronously perform the remaining steps.

  4. If the following steps or referenced procedures say to return an error, execute resolver's reject(value) algorithm, with the returned error as the value argument and then terminate the algorithm.

  5. Perform type mapping as specified in [WEBIDL] for format and key.

  6. If format is not a recognized key format value, then return an error named SyntaxError.

  7. If the name member of normalizedAlgorithm does not identify a registered algorithm that supports the export key operation, then return an error named NotSupportedError.

  8. If the extractable attribute of key is false, then return an error named InvalidAccessError.

  9. Let result be the result of performing the export key operation specified by the algorithm attribute of key using key and format.

  10. Execute resolver's resolve(value) algorithm, with result as the value argument.

Editorial note
Bug 24963 - There is an open question as to whether/how to support exporting keys when format is jwk. As currently specified, the result is a JSON-encoded Javascript object, converted to a UTF-8 byte sequence, with the raw bytes provided via an ArrayBuffer. A separate proposal exists to return an actual Javascript object when exporting with jwk.

14.3.11. The wrapKey method

When invoked, the wrapKey method MUST perform the following steps:

  1. Let format, key, wrappingKey and algorithm be the format, key, wrappingKey and wrapAlgorithm parameters passed to the wrapKey method, respectively.

  2. Let promise be a new Promise object and resolver its associated resolver object.

  3. Return promise and asynchronously perform the remaining steps.

  4. If the following steps or referenced procedures say to return an error, execute resolver's reject(value) algorithm, with the returned error as the value argument and then terminate the algorithm.

  5. Perform type mapping as specified in [WEBIDL] for format, key and wrappingKey.

  6. Let normalizedAlgorithm be the result of normalizing algorithm to Algorithm.

  7. If the name member of normalizedAlgorithm does not identify a registered algorithm that supports the encrypt or wrap key operation, then return an error named NotSupportedError.

  8. If format is not algorithm a recognized key format value, then return an error named SyntaxError.

  9. If the usages attribute of wrappingKey does not contain an entry that is "wrapKey", then return an error named InvalidAccessError.

  10. If the algorithm identified by the algorithm attibute of key does not support the export key operation, then return an error named NotSupportedError.

  11. If the extractable attribute of key is false, then return an error named InvalidAccessError.

  12. Let bytes be the result of performing the export key operation specified the algorithm attribute of key using key and format.

    Note

    This note is non-normative.

    The key wrapping operations for some algorithms place constraints on the payload size. For example AES-KW requires the payload to be a multiple of 8 bytes in length and RSA-OAEP places a restriction on the length. For key formats that offer flexibility in serialization of a given key (for example JWK), implementations may choose to adapt the serialization to the constraints of the wrapping algorithm.

  13. If normalizedAlgorithm supports the wrap key operation:

    Let result be the result of performing the wrap key operation specified by normalizedAlgorithm using algorithm, wrappingKey as key and bytes as plaintext.

    Otherwise, if normalizedAlgorithm supports the encrypt operation:

    Let result be the result of performing the encrypt operation specified by normalizedAlgorithm using algorithm, wrappingKey as key and bytes as plaintext.

    Otherwise:
    Return an error named NotSupportedError.
  14. Execute resolver's resolve(value) algorithm, with result as the value argument.

14.3.12. The unwrapKey method

When invoked, the unwrapKey method MUST perform the following steps:

  1. Let format, wrappedKey, unwrappingKey, algorithm, unwrappedKeyAlgorithm, extractable and usages, be the format, wrappedKey, unwrappingKey, unwrapAlgorithm, unwrappedKeyAlgorithm, extractable and keyUsages parameters passed to the unwrapKey method, respectively.

  2. Let promise be a new Promise object and resolver its associated resolver object.

  3. Return promise and asynchronously perform the remaining steps.

  4. If the following steps or referenced procedures say to return an error, execute resolver's reject(value) algorithm, with the returned error as the value argument and then terminate the algorithm.

  5. Perform type mapping as specified in [WEBIDL] for format, wrappedKey, unwrappingKey, extractable and usages.

  6. Let normalizedAlgorithm be the result of normalizing algorithm to Algorithm.

  7. If the name member of normalizedAlgorithm does not identify a registered algorithm that supports the unwrap key or decrypt operation, then return an error named NotSupportedError.

  8. Let normalizedKeyAlgorithm be the result of normalizing unwrappedKeyAlgorithm to Algorithm.

  9. If the name member of normalizedKeyAlgorithm does not identify a registered algorithm that supports the importKey operation, then return an error named NotSupportedError.

  10. If the usages attribute of unwrappingKey does not contain an entry that is "unwrapKey", then return an error named InvalidAccessError.

  11. If format is not a recognized key format value, then return an error named SyntaxError.

  12. If usages includes a value that is not a recognized key usage value, then return an error named SyntaxError.

  13. If normalizedUnwrapAlgorithm supports an unwrap key operation:
    Let bytes be the result of performing the unwrap key operation specified by normalizedAlgorithm using algorithm, unwrappingKey as key and wrappedKey as ciphertext.
    Otherwise, if normalizedAlgorithm supports a decrypt operation:
    Let bytes be the result of performing the decrypt operation specified by normalizedAlgorithm using algorithm, unwrappingKey as key and wrappedKey as ciphertext.
    Otherwise:
    Return an error named NotSupportedError.
  14. Let result be the result of performing the import key operation specified by normalizedKeyAlgorithm using unwrappedKeyAlgorithm as algorithm, format, usages and extractable and with bytes as keyData.

  15. Execute resolver's resolve(value) algorithm, with result as the value argument.

14.4. Exceptions

The methods of the SubtleCrypto interface return errors by calling the reject handler of the returned promise with a DOMException. The following DOMException types from [DOM4] are used with messages as shown in the following table:

Type Message (optional)
NotSupportedError The algorithm is not supported
SyntaxError A required parameter was missing our out-of-range
InvalidStateError The requested operation is not value for the current state of the provided key.
InvalidAccessError The requested operation is not valid for the provided key

The following new DOMException types are defined by this specification:

Type Message (optional)
UnknownError The operation failed for an unknown transient reason (e.g. out of memory)
DataError Data provided to an operation does not meet requirements
OperationError The operation failed for an operation-specific reason

When this specification says to return an error named error, where error is one of the above error names, the user agent must return a DOMException with name error and message as defined in the above two tables.

15. WorkerCrypto interface

IDL

interface WorkerCrypto {
  readonly attribute SubtleCrypto subtle;
};

WorkerCrypto implements RandomSource;

partial interface WorkerGlobalScope {
  readonly attribute WorkerCrypto crypto;
};
        

15.1. Description

The WorkerCrypto interface provides cryptographic functionality for background scripts, as specified by Web Workers [ Web Workers].

16. BigInteger

IDL

typedef Uint8Array BigInteger;
        

The BigInteger typedef is a Uint8Array that holds an arbitrary magnitude unsigned integer in big-endian order. Values read from the API SHALL have minimal typed array length (that is, at most 7 leading zero bits, except the value 0 which shall have length 8 bits). The API SHALL accept values with any number of leading zero bits, including the empty array, which represents zero.

Note
Implementation Note: Since the integer is unsigned, the highest order bit is NOT a sign bit. Implementors should take care when mapping to big integer implementations that expected signed integers.

17. KeyPair

IDL

interface KeyPair {
  readonly attribute Key publicKey;
  readonly attribute Key privateKey;
};
        

The KeyPair interface represents an asymmetric key pair that is comprised of both public and private keys.

18. Algorithms

Editorial note

Note: All algorithms listed should be considered as "features at risk", barring implementors adopting them. Their inclusion in the Last Call Working Draft reflects requests for their inclusion by members of the community, and are included as an exercise to ensure the robustness of the API defined in this specification.

As such, the list of algorithms, and the recommendations, may be significantly altered in future revisions.

18.1. Registered algorithms

Algorithm name encrypt decrypt sign verify digest generateKey deriveKey deriveBits importKey exportKey wrapKey unwrapKey
RSAES-PKCS1-v1_5
RSASSA-PKCS1-v1_5
RSA-PSS
RSA-OAEP
ECDSA
ECDH
AES-CTR
AES-CBC
AES-CMAC
AES-GCM
AES-CFB
AES-KW
HMAC
DH
SHA-1
SHA-256
SHA-384
SHA-512
CONCAT
HKDF-CTR
PBKDF2

18.3. Defining an algorithm

Each algorithm that is to be exposed via the Web Cryptography API SHOULD be registered via the Web Cryptography working group, and MUST include all of the following details. Algorithms that are not registered via these means, but are exposed via this API, MUST be processed as if the sections had been defined.

18.3.1. Recognized algorithm name

Each registered algorithm MUST have a canonical name for which applications can refer to the algorithm. The canonical name MUST contain only ASCII characters and MUST NOT equal any other canonical name or algorithm alias when every character in both names are converted to lower case.

18.3.2. Supported operations

Each registered algorithm MUST define the operations that it supports.

18.3.3. Algorithm-specific parameters

Each registered algorithm MUST define the expected parameters, if any, that should be exposed via the Algorithm dictionary for every supported operation.

18.3.4. Algorithm results

Each registered algorithm MUST define the contents of the result of performing the underlying cryptographic operation for every supported operation.

18.3.5. Algorithm aliases

Each registered algorithm MAY define one or more aliases that may define a fully normalized Algorithm object.

Each algorithm alias MUST follow the same naming rules as the recognized algorithm name.

18.4. RSAES-PKCS1-v1_5

18.4.1. Description

The "RSAES-PKCS1-v1_5" algorithm identifier is used to perform encryption and decryption ordering to the RSAES-PKCS1-v1_5 algorithm specified in [RFC3447].

18.4.2. Registration

The recognized algorithm name for this algorithm is "RSAES-PKCS1-v1_5".

Operation Parameters Result
encrypt None ArrayBuffer
decrypt None ArrayBuffer
generateKey RsaKeyGenParams KeyPair
importKey None Key
exportKey None ArrayBuffer

18.4.3. RsaKeyGenParams dictionary

IDL

dictionary RsaKeyGenParams : Algorithm {
  // The length, in bits, of the RSA modulus
  [EnforceRange] unsigned long modulusLength;
  // The RSA public exponent
  BigInteger publicExponent;
};
            

18.4.4. RsaKeyAlgorithm interface

IDL

interface RsaKeyAlgorithm : KeyAlgorithm {
  // The length, in bits, of the RSA modulus
  readonly attribute unsigned long modulusLength;
  // The RSA public exponent
  readonly attribute BigInteger publicExponent;
};
            

18.4.5. Operations

Encrypt
  1. If the type attribute of key is not "public", then return an error named InvalidAccessError.

  2. Perform the encrytion operation defined in Section 7.2 of [RFC3447] with the key represented by key as the recipient's RSA public key and the contents of plaintext as M.

  3. If performing the operation results in an error, then return an error named OperationError.

  4. Let ciphertext be a new ArrayBuffer containing the value C that results from performing the operation.

Decrypt
  1. If the type attribute of key is not "private", then return an error named InvalidAccessError

  2. Perform the decryption operation defined in Section 7.2 of [RFC3447] with the key represented by key as the recipient's RSA private key and the contents of ciphertext as C.

  3. If performing the operation results in an error, then return an error named OperationError.

  4. Let plaintext be a new ArrayBuffer containing the value M that results from performing the operation.

Generate Key
  1. Let normalizedAlgorithm be the result of normalizing algorithm to RsaKeyGenParams.

  2. If any of the members of RsaKeyGenParams are not present in normalizedAlgorithm, then return an error named SyntaxError.

  3. If usages contains an entry which is not "encrypt", "decrypt", "wrapKey" or "unwrapKey", then return an error named DataError.

  4. Generate an RSA key pair, as defined in [RFC3447], with RSA modulus length equal to the modulusLength member of normalizedAlgorithm and RSA public exponent equal to the publicExponent member of normalizedAlgorithm.

  5. If generation of the key pair fails, then return an error named OperationError.

  6. Let algorithm be a new RsaKeyAlgorithm object.

  7. Set the name attribute of algorithm to "RSAES-PKCS1-v1_5".

  8. Set the modulusLength attribute of algorithm to equal the modulusLength attribute of normalizedAlgorithm.

  9. Set the publicExponent attribute of algorithm to equal the publicExponent attribute of normalizedAlgorithm.

  10. Let publicKey be a new Key object representing the public key of the generated key pair.

  11. Set the type attribute of publicKey to "public"

  12. Set the algorithm attribute of publicKey to be algorithm.

  13. Set the extractable attribute of publicKey to true.

  14. Set the usages attribute of publicKey to be the usage intersection of usages and [ "encrypt", "wrapKey" ].

  15. Let privateKey be a new Key object representing the private key of the generated key pair.

  16. Set the type attribute of privateKey to "private"

  17. Set the algorithm attribute of privateKey to be algorithm.

  18. Set the extractable attribute of privateKey to extractable.

  19. Set the usages attribute of privateKey to be the usage intersection of usages and [ "decrypt", "unwrapKey" ].

  20. Let result be a new KeyPair object.

  21. Set the publicKey attribute of result to be publicKey.

  22. Set the privateKey attribute of result to be privateKey.

  23. Return result.

Import Key
  1. Let keyData be the key data to be imported.

  2. If format is "spki":
    1. Let spki be the result of running the parse a subjectPublicKeyInfo algorithm over keyData.

    2. If an error occurred while parsing, then return an error named DataError.

    3. If the algorithm object identifier field of the algorithm AlgorithmIdentifier field of spki is not equivalent to the rsaEncryption OID defined in Section 2.3.1 of RFC 3279, then return an error named DataError.

    4. Let publicKey be the result of performing the parse an ASN.1 structure algorithm, with data as the subjectPublicKeyInfo field of spki, structure as the RSAPublicKey structure specified in Section A.1.1 of RFC 3447, and exactData set to true.

    5. If an error occurred while parsing, then return an error named DataError.

    6. Let key be a new Key object that represents the RSA public key identified by publicKey.

    7. Set the type attribute of key to "public"

    If format is "pkcs8":
    1. Let privateKeyInfo be the result of running the parse a privateKeyInfo algorithm over keyData.

    2. If an error occurred while parsing, then return an error named DataError.

    3. If the algorithm object identifier field of the privateKeyAlgorithm PrivateKeyAlgorithmIdentifier field of privateKeyInfo is not equivalent to the rsaEncryption OID defined in Section 2.3.1 of RFC 3279, then return an error named DataError.

    4. Let rsaPrivateKey be the result of performing the parse an ASN.1 structure algorithm, with data as the privateKey field of privateKeyInfo, structure as the RSAPrivateKey structure specified in Section A.1.2 of RFC 3447, and exactData set to true.

    5. If an error occurred while parsing, then return an error named DataError.

    6. Let key be a new Key object that represents the RSA private key identified by rsaPrivateKey.

    7. Set the type attribute of key to "private"

    If format is "jwk":
    1. Let jwk be the result of running the parse a jwk algorithm over keyData.

    2. If the "kty" field of jwk is not "RSA", then return an error named DataError.

    3. If the "use" field of jwk is present, and is not "enc", then return an error named DataError.

    4. If the "key_ops" field of jwk is present, and is invalid according to the requirements of JSON Web Key or does not contain all of the specified usages values, then return an error named DataError.

    5. If the "alg" field of jwk is present, and is not "RSA1_5", then return an error named DataError.

    6. If the "d" field of jwk is present:
      1. If jwk does not meet the requirements of Section 6.3.2 of JSON Web Algorithms, then return an error named DataError.

      2. Let key be a new Key object that represents the RSA private key identified by interpreting jwk according to Section 6.3.2 of JSON Web Algorithms.

      3. Set the type attribute of key to "private"

      Otherwise:
      1. If jwk does not meet the requirements of Section 6.3.1 of JSON Web Algorithms, then return an error named DataError.

      2. Let key be a new Key object that represents the RSA public key identified by interpreting jwk according to Section 6.3.1 of JSON Web Algorithms.

      3. Set the type attribute of key to "public"

    Otherwise:
    Return an error named NotSupportedError.
  3. Let algorithm be a new RsaKeyAlgorithm.

  4. Set the name attribute of algorithm to "RSAES-PKCS1-v1_5"

  5. Set the modulusLength attribute of algorithm to the length, in bits, of the RSA public modulus.

  6. Set the publicExponent attribute of algorithm to the BigInteger representation of the RSA public exponent.

  7. Set the algorithm attribute of key to algorithm

  8. Return key.

Export Key
  1. Let key be the key to be exported.

  2. If format is "spki"
    1. If the type attribute of key is not "public", then return an error named InvalidAccessError.

    2. Let result be the result of encoding a subjectPublicKeyInfo with the following properties:

      • Set the algorithm field to an AlgorithmIdentifier ASN.1 type with the following properties:

        • Set the algorithm field to the OID 1.2.840.113549.1.1

        • Set the params field to the ASN.1 type NULL.

      • Set the subjectPublicKey field to the result of DER-encoding an RSAPublicKey ASN.1 type, as defined in RFC 3447, Appendix A.1.1, that represents the RSA public key identified by key

    If format is "pkcs8":
    1. If the type attribute of key is not "private", then return an error named InvalidAccessError.

    2. Let result be the result of encoding a privateKeyInfo with the following properties:

      • Set the version field to 0.

      • Set the privateKeyAlgorithm field to a PrivateKeyAlgorithmIdentifier ASN.1 type with the following properties:

        • Set the algorithm field to the OID 1.2.840.113549.1.1

        • Set the params field to the ASN.1 type NULL.

      • Set the privateKey field to the result of DER-encoding an RSAPrivateKey ASN.1 type, as defined in RFC 3447, Appendix A.1.2, that represents the RSA private key identified by key

        Editorial note
        RFC 5208 specifies that the encoding of this field should be BER encoded in Section 5 (as a "for example"). However, to avoid requiring WebCrypto implementations support BER-encoding and BER-decoding, only DER encodings are produced or accepted.
    If format is "jwk":
    • Let jwk be a new internal object.

    • Set the kty property of jwk to the string "RSA".

    • Set the alg property of jwk to the string "RSA1_5".

    • Set the properties n and e of jwk according to the corresponding definitions in JSON Web Algorithms, Section 6.3.1.

    • If the type attribute of key is "private":
      1. Set the properties named d, p, q, dp, dq, and qi of jwk according to the corresponding definitions in JSON Web Algorithms, Section 6.3.2.

      2. If the underlying RSA private key represented by key is represented by more than two primes, set the member named oth of jwk according to the corresponding definition in JSON Web Algorithms, Section 6.3.2.7

    • Set the key_ops property of jwk to the usages attribute of key.

    • Set the ext property of jwk to the extractable attribute of key.

    • Let stringifiedJwk be the result of encoding jwk according to the grammar specified in Section 15.12 of ECMA262.

    • Let result be the UTF-8 encoding of stringifiedJwk.

    Otherwise

    Return an error named NotSupportedError.

  3. Let data be a new ArrayBuffer containing result.

  4. Return data.

18.5. RSASSA-PKCS1-v1_5

18.5.1. Description

The "RSASSA-PKCS1-v1_5" algorithm identifier is used to perform signing and verification using the RSASSA-PKCS1-v1_5 algorithm specified in [RFC3447].

18.5.2. Registration

The recognized algorithm name for this algorithm is "RSASSA-PKCS1-v1_5".

Operation Parameters Result
sign None ArrayBuffer
verify None boolean
generateKey RsaHashedKeyGenParams KeyPair
importKey RsaHashedImportParams Key
exportKey None ArrayBuffer

18.5.3. RsaHashedKeyGenParams dictionary

IDL

dictionary RsaHashedKeyGenParams : RsaKeyGenParams {
  // The hash algorithm to use 
  AlgorithmIdentifier hash;
};
            

18.5.4. RsaHashedKeyAlgorithm interface

IDL

[NoInterfaceObject]
interface RsaHashedKeyAlgorithm : RsaKeyAlgorithm {
  // The hash algorithm that is used with this key
  readonly attribute KeyAlgorithm hash;
};
            

18.5.5. RsaHashedImportParams dictionary

IDL

dictionary RsaHashedImportParams {
  // The hash algorithm to use
  AlgorithmIdentifier hash;
};
            
Editorial note

Should this be folded into RsaHashedKeyGenParams and rely on the optional nature of the dictionary fields?

18.5.6. Operations

Sign
  1. If the type attribute of key is not "private", then return an error named InvalidAccessError.

  2. Perform the signature generation operation defined in Section 8.2 of [RFC3447] with the key represented by key as the signer's private key and the contents of message as M and using the hash function specified in the hash attribute of the algorithm attribute of key as the Hash option for the EMSA-PKCS1-v1_5 encoding method.

  3. If performing the operation results in an error, then return an error named OperationError.

  4. Let signature be the value S that results from performing the operation.

Verify
  1. If the type attribute of key is not "public", then return an error named InvalidAccessError.

  2. Perform the signature verification operation defined in Section 8.2 of [RFC3447] with the key represented by key as the signer's RSA public key and the contents of message as M and signature as S and using the hash function specified in the hash attribute of the algorithm attribute of key as the Hash option for the EMSA-PKCS1-v1_5 encoding method.

  3. If performing the operation results in an error, then return an error named OperationError.

  4. Let result be a boolean with value true if the result of the operations was "valid signature" and a boolean with value false otherwise.

Generate Key
  1. Let normalizedAlgorithm be the result of normalizing algorithm to RsaHashedKeyGenParams.

  2. If any of the members of RsaHashedKeyGenParams are not present in normalizedAlgorithm, then return an error named SyntaxError.

  3. If usages contains an entry which is not "sign" or "verify", then return an error named DataError.

  4. Generate an RSA key pair, as defined in [RFC3447], with RSA modulus length equal to the modulusLength attribute of normalizedAlgorithm and RSA public exponent equal to the publicExponent attribute of normalizedAlgorithm.

  5. If generation of the key pair fails, then return an error named OperationError.

  6. Let algorithm be a new RsaHashedKeyAlgorithm object.

  7. Set the name attribute of algorithm to "RSASSA-PKCS1-v1_5".

  8. Set the modulusLength attribute of algorithm to equal the modulusLength attribute of normalizedAlgorithm.

  9. Set the publicExponent attribute of algorithm to equal the publicExponent attribute of normalizedAlgorithm.

  10. Set the hash attribute of algorithm to equal the hash member of normalizedAlgorithm.

  11. Let publicKey be a new Key object representing the public key of the generated key pair.

  12. Set the type attribute of publicKey to "public"

  13. Set the algorithm attribute of publicKey to be algorithm.

  14. Set the extractable attribute of publicKey to true.

  15. Set the usages attribute of publicKey to be the usage intersection of usages and [ "verify" ].

  16. Let privateKey be a new Key object representing the private key of the generated key pair.

  17. Set the type attribute of privateKey to "private"

  18. Set the algorithm attribute of privateKey to be algorithm.

  19. Set the extractable attribute of privateKey to extractable.

  20. Set the usages attribute of privateKey to be the usage intersection of usages and [ "sign" ].

  21. Let result be a new KeyPair object.

  22. Set the publicKey attribute of result to be publicKey.

  23. Set the privateKey attribute of result to be privateKey.

  24. Return result.

Editorial note

TODO: Specify the mapping between key.algorithm.hash and the appropriate Hash functions (and back to OID).

Import Key
  1. Let keyData be the key data to be imported.

  2. Let normalizedAlgorithm be the result of normalizing algorithm to RsaHashedImportParams.

  3. If any of the members of RsaHashedImportParams are not present in normalizedAlgorithm then return an error named SyntaxError.

  4. If format is "spki":
    1. Let spki be the result of running the parse a subjectPublicKeyInfo algorithm over keyData.

    2. If an error occurred while parsing, then return an error named DataError.

    3. Let hash be a string whose initial value is undefined.

    4. Let alg be the algorithm object identifier field of the algorithm AlgorithmIdentifier field of spki.

    5. If alg is equivalent to the rsaEncryption OID defined in Section 2.3.1 of RFC 3279:

      Let hash be undefined.

      If alg is equivalent to the sha1WithRSAEncryption OID defined in Section A.2.4 of RFC 3279:

      Let hash be the string SHA-1.

      If alg is equivalent to the sha256WithRSAEncryption OID defined in Section A.2.4 of RFC 3279:

      Let hash be the string SHA-256.

      If alg is equivalent to the sha384WithRSAEncryption OID defined in Section A.2.4 of RFC 3279:

      Let hash be the string SHA-384.

      If alg is equivalent to the sha512WithRSAEncryption OID defined in Section A.2.4 of RFC 3279:

      Let hash be the string SHA-512.

      Otherwise:

      Return an error named DataError.

    6. If hash is defined, and is not equal to the name member of the hash member of normalizedAlgorithm, return an error named DataError.

    7. Set hash to the name member of the hash member of normalizedAlgorithm.

    8. Let publicKey be the result of performing the parse an ASN.1 structure algorithm, with data as the subjectPublicKeyInfo field of spki, structure as the RSAPublicKey structure specified in Section A.1.1 of RFC 3447, and exactData set to true.

    9. If an error occurred while parsing, then return an error named DataError.

    10. Let key be a new Key object that represents the RSA public key identified by publicKey.

    11. Set the type attribute of key to "public"

    If format is "pkcs8":
    1. Let privateKeyInfo be the result of running the parse a privateKeyInfo algorithm over keyData.

    2. If an error occurred while parsing, then return an error named DataError.

    3. Let hash be a string whose initial value is undefined.

    4. Let alg be the algorithm object identifier field of the privateKeyAlgorithm PrivateKeyAlgorithmIdentifier field of privateKeyInfo.

    5. If alg is equivalent to the rsaEncryption OID defined in Section 2.3.1 of RFC 3279:

      Let hash be undefined.

      If alg is equivalent to the sha1WithRSAEncryption OID defined in Section A.2.4 of RFC 3279:

      Let hash be the string SHA-1.

      If alg is equivalent to the sha256WithRSAEncryption OID defined in Section A.2.4 of RFC 3279:

      Let hash be the string SHA-256.

      If alg is equivalent to the sha384WithRSAEncryption OID defined in Section A.2.4 of RFC 3279:

      Let hash be the string SHA-384.

      If alg is equivalent to the sha512WithRSAEncryption OID defined in Section A.2.4 of RFC 3279:

      Let hash be the string SHA-512.

      Otherwise:

      Return an error named DataError.

    6. If hash is defined, and is not equal to the name member of the hash member of normalizedAlgorithm, return an error named DataError.

    7. Set hash to the name member of the hash member of normalizedAlgorithm.

    8. Let rsaPrivateKey be the result of performing the parse an ASN.1 structure algorithm, with data as the privateKey field of privateKeyInfo, structure as the RSAPrivateKey structure specified in Section A.1.2 of RFC 3447, and exactData set to true.

    9. If an error occurred while parsing, then return an error named DataError.

    10. Let key be a new Key object that represents the RSA private key identified by rsaPrivateKey.

    11. Set the type attribute of key to "private"

    If format is "jwk":
    1. Let jwk be the result of running the parse a jwk algorithm over keyData.

    2. If the "kty" field of jwk is not a case-sensitive string match to "RSA", then return an error named DataError.

    3. If the "use" field of jwk is present, and is not a case-sensitive string match to "enc", then return an error named DataError.

    4. If the "key_ops" field of jwk is present, and is invalid according to the requirements of JSON Web Key or does not contain all of the specified usages values, then return an error named DataError.

    5. Let hash be a be a string whose initial value is undefined.

    6. If the "alg" field of jwk is not present:

      Let hash be undefined.

      If the "alg" field is equal to the string "RS1":

      Let hash be the string SHA-1.

      If the "alg" field is equal to the string "RS256":

      Let hash be the string SHA-256.

      If the "alg" field is equal to the string "RS384":

      Let hash be the string SHA-384.

      If the "alg" field is equal to the string "RS512":

      Let hash be the string SHA-512.

      Otherwise:

      Return an error named DataError.

    7. If the "d" field of jwk is present:
      1. If jwk does not meet the requirements of Section 6.3.2 of JSON Web Algorithms, then return an error named DataError.

      2. Let key be a new Key object that represents the RSA private key identified by interpreting jwk according to Section 6.3.2 of JSON Web Algorithms.

      3. Set the type attribute of key to "private"

      Otherwise:
      1. If jwk does not meet the requirements of Section 6.3.1 of JSON Web Algorithms, then return an error named DataError.

      2. Let key be a new Key object that represents the RSA public key identified by interpreting jwk according to Section 6.3.1 of JSON Web Algorithms.

      3. Set the type attribute of key to "public"

    Otherwise:
    Return an error named NotSupportedError.
  5. Let algorithm be a new RsaHashedKeyAlgorithm.

  6. Set the name attribute of algorithm to "RSASSA-PKCS1-v1_5"

  7. Set the modulusLength attribute of algorithm to the length, in bits, of the RSA public modulus.

  8. Set the publicExponent attribute of algorithm to the BigInteger representation of the RSA public exponent.

  9. Set the hash attribute of algorithm to a new KeyAlgorithm whose name attribute is hash.

  10. Set the algorithm attribute of key to algorithm

  11. Return key.

Export Key
  1. Let key be the key to be exported.

  2. If format is "spki"
    1. If the type attribute of key is not "public", then return an error named InvalidAccessError.

    2. Let result be the result of encoding a subjectPublicKeyInfo with the following properties:

      • Set the algorithm field to an AlgorithmIdentifier ASN.1 type with the following properties:

        • Set the algorithm field to the OID 1.2.840.113549.1.1

        • Set the params field to the ASN.1 type NULL.

      • Set the subjectPublicKey field to the result of DER-encoding an RSAPublicKey ASN.1 type, as defined in RFC 3447, Appendix A.1.1, that represents the RSA public key identified by key

    If format is "pkcs8":
    1. If the type attribute of key is not "private", then return an error named InvalidAccessError.

    2. Let result be the result of encoding a privateKeyInfo with the following properties:

      • Set the version field to 0.

      • Set the privateKeyAlgorithm field to a PrivateKeyAlgorithmIdentifier ASN.1 type with the following properties:

        • Set the algorithm field to the OID 1.2.840.113549.1.1

        • Set the params field to the ASN.1 type NULL.

      • Set the privateKey field to the result of DER-encoding an RSAPrivateKey ASN.1 type, as defined in RFC 3447, Appendix A.1.2, that represents the RSA private key identified by key

        Editorial note
        RFC 5208 specifies that the encoding of this field should be BER encoded in Section 5 (as a "for example"). However, to avoid requiring WebCrypto implementations support BER-encoding and BER-decoding, only DER encodings are produced or accepted.
    If format is "jwk":
    • Let jwk be a new internal object.

    • Set the kty field of jwk to the string "RSA".

    • Let hash be the name attribute of the hash attribute of key.

    • If hash is SHA-1:

      Set the alg field of jwk to the string RS1.

      If hash is SHA-256:

      Set the alg field of jwk to the string RS256.

      If hash is SHA-384:

      Set the alg field of jwk to the string RS384.

      If hash is SHA-512:

      Set the alg field of jwk to the string RS512.

      Otherwise:

      Return an error named NotSupportedError.

    • Set the alg field of jwk to the string "RSA1_5".

    • Set the fields n and e of jwk according to the corresponding definitions in JSON Web Algorithms, Section 6.3.1.

    • If the type attribute of key is "private":
      1. Set the fields named d, p, q, dp, dq, and qi of jwk according to the corresponding definitions in JSON Web Algorithms, Section 6.3.2.

      2. If the underlying RSA private key represented by key is represented by more than two primes, set the field named oth of jwk according to the corresponding definition in JSON Web Algorithms, Section 6.3.2.7

    • Set the key_ops field of jwk to the usages attribute of key.

    • Set the ext field of jwk to the extractable attribute of key.

    • Let stringifiedJwk be the result of encoding jwk according to the grammar specified in Section 15.12 of ECMA262.

    • Let result be the UTF-8 encoding of stringifiedJwk.

    Otherwise

    Return an error named NotSupportedError.

  3. Let data be a new ArrayBuffer containing result.

  4. Return data.

18.6. RSA-PSS

18.6.1. Description

The "RSA-PSS" algorithm identifier is used to perform signing and verification using the RSASSA-PSS algorithm specified in [RFC3447], using the mask generation formula MGF1.

18.6.2. Registration

The recognized algorithm name for this algorithm is "RSA-PSS".

Operation Parameters Result
sign RsaPssParams ArrayBuffer
verify RsaPssParams boolean
generateKey RsaHashedKeyGenParams KeyPair
importKey RsaHashedImportParams Key
exportKey None ArrayBuffer

18.6.3. RsaPssParams dictionary

IDL

dictionary RsaPssParams : Algorithm {
  // The desired length of the random salt
  [EnforceRange] unsigned long saltLength;
};
            

18.6.4. Operations

Sign
  1. If the type attribute of key is not "private", then return an error named InvalidAccessError.

  2. Let normalizedAlgorithm be the result of normalizing algorithm to RsaPssParams.

  3. If any of the members of RsaPssParams are not present in normalizedAlgorithm, then return an error named SyntaxError.

  4. Perform the signature generation operation defined in Section 8.1 of [RFC3447] with the key represented by key as the signer's private key, K, and the contents of message as the message to be signed, M, and using the hash function specified by the hash attribute of the algorithm attribute of key as the Hash option, MGF1 (defined in Section B.2.1 of [RFC3447]) as the MGF option and the saltLength member of normalizedAlgorithm as the salt length option for the EMM-PSS-ENCODE operation.

  5. If performing the operation results in an error, then return an error named OperationError.

  6. Let signature be a new ArrayBuffer containing the signature, S, that results from performing the operation.

Verify
  1. If the type attribute of key is not "public", then return an error named InvalidAccessError.

  2. Let normalizedAlgorithm be the result of normalizing algorithm to RsaPssParams.

  3. If any of the members of RsaPssParams are not present in normalizedAlgorithm, then return an error named SyntaxError.

  4. Perform the signature verification operation defined in Section 8.1 of [RFC3447] with the key represented by key as the signer's RSA public key and the contents of message as M and the contents of signature as S and using the hash function specified by the hash attribute of the algorithm attribute of key as the Hash option, MGF1 (defined in Section B.2.1 of [RFC3447]) as the MGF option and the saltLength member of normalizedAlgorithm as the salt length option for the EMSA-PSS-VERIFY operation.

  5. If performing the operation results in an error, then return an error named OperationError.

  6. Let result be a boolean with value true if the result of the operation was "valid signature" and a boolean with value false otherwise.

Generate Key
  1. Let normalizedAlgorithm be the result of normalizing algorithm to RsaHashedKeyGenParams.

  2. If any of the members of RsaHashedKeyGenParams are not present in normalizedAlgorithm, then return an error named SyntaxError.

  3. If usages contains an entry which is not "sign" or "verify", then return an error named SyntaxError.

  4. Generate an RSA key pair, as defined in [RFC3447], with RSA modulus length equal to the modulusLength member of normalizedAlgorithm and RSA public exponent equal to the publicExponent member of normalizedAlgorithm.

  5. If performing the operation results in an error, then return an error named OperationError.

  6. Let algorithm be a new RsaHashedKeyAlgorithm object.

  7. Set the name attribute of algorithm to "RSA-PSS".

  8. Set the modulusLength attribute of algorithm to equal the modulusLength member of normalizedAlgorithm.

  9. Set the publicExponent attribute of algorithm to equal the publicExponent member of normalizedAlgorithm.

  10. Set the hash attribute of algorithm to equal the hash member of normalizedAlgorithm.

  11. Let publicKey be a new Key object representing the public key of the generated key pair.

  12. Set the type attribute of publicKey to "public"

  13. Set the algorithm attribute of publicKey to be algorithm.

  14. Set the extractable attribute of publicKey to true.

  15. Set the usages attribute of publicKey to be the usage intersection of usages and [ "verify" ].

  16. Let privateKey be a new Key object representing the private key of the generated key pair.

  17. Set the type attribute of privateKey to "private"

  18. Set the algorithm attribute of privateKey to be algorithm.

  19. Set the extractable attribute of privateKey to extractable.

  20. Set the usages attribute of privateKey to be the usage intersection of usages and [ "sign" ].

  21. Let result be a new KeyPair object.

  22. Set the publicKey attribute of result to be publicKey.

  23. Set the privateKey attribute of result to be privateKey.

  24. Return result.

Import Key
  1. Let keyData be the key data to be imported.

  2. Let normalizedAlgorithm be the result of normalizing algorithm to RsaHashedImportParams.

  3. If any of the members of RsaHashedImportParams are not present in normalizedAlgorithm then return an error named SyntaxError.

  4. If format is "spki":
    1. Let spki be the result of running the parse a subjectPublicKeyInfo algorithm over keyData.

    2. If an error occurred while parsing, then return an error named DataError.

    3. Let hash be a string whose initial value is undefined.

    4. Let alg be the algorithm object identifier field of the algorithm AlgorithmIdentifier field of spki.

    5. If alg is equivalent to the rsaEncryption OID defined in RFC 3447:

      Let hash be undefined.

      If alg is equivalent to the id-RSASSA-PSS OID defined in RFC 3447:
      1. Let params be the ASN.1 structure contained within the parameters field of the algorithm AlgorithmIdentifier field of spki.

      2. If params is not defined, or is not an instance of the RSASSA-PSS-params ASN.1 type defined in RFC3447, return an error named DataError.

      3. Let hashAlg be the AlgorithmIdentifier ASN.1 type within the hashAlgorithm field of params.

      4. If the algorithm object identifier field of hashAlg is equivalent to the id-sha1 OID defined in RFC 3447:

        Set hash to the string SHA-1.

        If the algorithm object identifier field of hashAlg is equivalent to the id-sha256 OID defined in RFC 3447:

        Set hash to the string SHA-256.

        If the algorithm object identifier field of hashAlg is equivalent to the id-sha384 OID defined in RFC 3447:

        Set hash to the string SHA-384.

        If the algorithm object identifier field of hashAlg is equivalent to the id-sha512 OID defined in RFC 3447:

        Set hash to the string SHA-512.

        Otherwise:

        Return an error named NotSupportedError.

      5. If the algorithm object identifier field of the maskGenAlgorithm field of params is not equivalent to the OID id-mgf1 defined in RFC 3447, return an error named NotSupportedError.

      6. If the parameters field of the maskGenAlgorithm field of params is not an instance of the HashAlgorithm ASN.1 type that is identical in content to the hashAlglorithm field of params, return an error named NotSupportedError.

      Otherwise:

      Return an error named DataError.

    6. If hash is defined, and is not equal to the name member of the hash member of normalizedAlgorithm, return an error named DataError.

    7. Set hash to the name member of the hash member of normalizedAlgorithm.

    8. Let publicKey be the result of performing the parse an ASN.1 structure algorithm, with data as the subjectPublicKeyInfo field of spki, structure as the RSAPublicKey structure specified in Section A.1.1 of RFC 3447, and exactData set to true.

    9. If an error occurred while parsing, then return an error named DataError.

    10. Let key be a new Key object that represents the RSA public key identified by publicKey.

    11. Set the type attribute of key to "public"

    If format is "pkcs8":
    1. Let privateKeyInfo be the result of running the parse a privateKeyInfo algorithm over keyData.

    2. If an error occurred while parsing, then return an error named DataError.

    3. Let hash be a string whose initial value is undefined.

    4. Let alg be the algorithm object identifier field of the privateKeyAlgorithm PrivateKeyAlgorithmIdentifier field of privateKeyInfo.

    5. If alg is equivalent to the rsaEncryption OID defined in RFC 3447:

      Let hash be undefined.

      If alg is equivalent to the id-RSASSA-PSS OID defined in RFC 3447:
      1. Let params be the ASN.1 structure contained within the parameters field of the privateKeyAlgorithm PrivateKeyAlgorithmIdentifier field of privateKeyInfo.

      2. If params is not defined, or is not an instance of the RSASSA-PSS-params ASN.1 type defined in RFC3447, return an error named NotSupportedError.

      3. Let hashAlg be the AlgorithmIdentifier ASN.1 type within the hashAlgorithm field of params.

      4. If the algorithm object identifier field of hashAlg is equivalent to the id-sha1 OID defined in RFC 3447:

        Set hash to the string SHA-1.

        If the algorithm object identifier field of hashAlg is equivalent to the id-sha256 OID defined in RFC 3447:

        Set hash to the string SHA-256.

        If the algorithm object identifier field of hashAlg is equivalent to the id-sha384 OID defined in RFC 3447:

        Set hash to the string SHA-384.

        If the algorithm object identifier field of hashAlg is equivalent to the id-sha512 OID defined in RFC 3447:

        Set hash to the string SHA-512.

        Otherwise:

        Return an error named NotSupportedError.

      5. If the algorithm object identifier field of the maskGenAlgorithm field of params is not equivalent to the OID id-mgf1 defined in RFC 3447, return an error named NotSupportedError.

      6. If the parameters field of the maskGenAlgorithm field of params is not an instance of the HashAlgorithm ASN.1 type that is identical in content to the hashAlglorithm field of params, return an error named NotSupportedError.

      Otherwise:

      Return an error named DataError.

    6. If hash is defined, and is not equal to the name member of the hash member of normalizedAlgorithm, return an error named DataError.

    7. Set hash to the name member of the hash member of normalizedAlgorithm.

    8. Let rsaPrivateKey be the result of performing the parse an ASN.1 structure algorithm, with data as the privateKey field of privateKeyInfo, structure as the RSAPrivateKey structure specified in Section A.1.2 of RFC 3447, and exactData set to true.

    9. If an error occurred while parsing, then return an error named DataError.

    10. Let key be a new Key object that represents the RSA private key identified by rsaPrivateKey.

    11. Set the type attribute of key to "private"

    If format is "jwk":
    1. Let jwk be the result of running the parse a jwk algorithm over keyData.

    2. If the "kty" field of jwk is not a case-sensitive string match to "RSA", then return an error named DataError.

    3. If the "use" field of jwk is present, and is not a case-sensitive string match to "enc", then return an error named DataError.

    4. If the "key_ops" field of jwk is present, and is invalid according to the requirements of JSON Web Key or does not contain all of the specified usages values, then return an error named DataError.

    5. Let hash be a be a string whose initial value is undefined.

    6. If the "alg" field of jwk is not present:

      Let hash be undefined.

      If the "alg" field is equal to the string "PS1":

      Let hash be the string SHA-1.

      If the "alg" field is equal to the string "PS256":

      Let hash be the string SHA-256.

      If the "alg" field is equal to the string "PS384":

      Let hash be the string SHA-384.

      If the "alg" field is equal to the string "PS512":

      Let hash be the string SHA-512.

      Otherwise:

      Return an error named DataError.

    7. If the "d" field of jwk is present:
      1. If jwk does not meet the requirements of Section 6.3.2 of JSON Web Algorithms, then return an error named DataError.

      2. Let key be a new Key object that represents the RSA private key identified by interpreting jwk according to Section 6.3.2 of JSON Web Algorithms.

      3. Set the type attribute of key to "private"

      Otherwise:
      1. If jwk does not meet the requirements of Section 6.3.1 of JSON Web Algorithms, then return an error named DataError.

      2. Let key be a new Key object that represents the RSA public key identified by interpreting jwk according to Section 6.3.1 of JSON Web Algorithms.

      3. Set the type attribute of key to "public"

    Otherwise:
    Return an error named NotSupportedError.
  5. Let algorithm be a new RsaHashedKeyAlgorithm.

  6. Set the name attribute of algorithm to "RSA-PSS"

  7. Set the modulusLength attribute of algorithm to the length, in bits, of the RSA public modulus.

  8. Set the publicExponent attribute of algorithm to the BigInteger representation of the RSA public exponent.

  9. Set the hash attribute of algorithm to a new KeyAlgorithm whose name attribute is hash.

  10. Set the algorithm attribute of key to algorithm

  11. Return key.

Export Key
  1. Let key be the key to be exported.

  2. If format is "spki"
    1. If the type attribute of key is not "public", then return an error named InvalidAccessError.

    2. Let result be the result of encoding a subjectPublicKeyInfo with the following properties:

      • Set the algorithm field to an AlgorithmIdentifier ASN.1 type with the following properties:

        • Set the algorithm field to the OID id-RSASSA-PSS defined in RFC 3447.

        • Set the params field to an instance of the RSASSA-PSS-params ASN.1 type with the following properties:

          • Set the hashAlgorithm field to an instance of the HashAlgorithm ASN.1 type with the following properties:

            If the name attribute of the hash attribute of the algorithm attribute of key is SHA-1:

            Set the algorithm object identifier to the OID id-sha1 defined in RFC 3447.

            If the name attribute of the hash attribute of the algorithm attribute of key is SHA-256:

            Set the algorithm object identifier to the OID id-sha256 defined in RFC 3447.

            If the name attribute of the hash attribute of the algorithm attribute of key is SHA-384:

            Set the algorithm object identifier to the OID id-sha384 defined in RFC 3447.

            If the name attribute of the hash attribute of the algorithm attribute of key is SHA-512:

            Set the algorithm object identifier to the OID id-sha512 defined in RFC 3447.

          • Set the maskGenAlgorithm field to an instance of the MaskGenAlgorithm ASN.1 type with the following properties:

            • Set the algorithm field to the OID id-mgf1 defined in RFC 3447.

            • Set the params field to an instance of the HashAlgorithm ASN.1 type that is identical to the hashAlgorithm field.

          • Set the saltLength field to the length in octets of the digest algorithm identified by the name attribute of the hash attribute of the algorithm attribute of key.

      • Set the subjectPublicKey field to the result of DER-encoding an RSAPublicKey ASN.1 type, as defined in RFC 3447, Appendix A.1.1, that represents the RSA public key identified by key

    If format is "pkcs8":
    1. If the type attribute of key is not "private", then return an error named InvalidAccessError.

    2. Let result be the result of encoding a privateKeyInfo with the following properties:

      • Set the version field to 0.

      • Set the privateKeyAlgorithm field to an PrivateKeyAlgorithmIdentifier ASN.1 type with the following properties:

        • Set the algorithm field to the OID id-RSASSA-PSS defined in RFC 3447.

        • Set the params field to an instance of the RSASSA-PSS-params ASN.1 type with the following properties:

          • Set the hashAlgorithm field to an instance of the HashAlgorithm ASN.1 type with the following properties:

            If the name attribute of the hash attribute of the algorithm attribute of key is SHA-1:

            Set the algorithm object identifier to the OID id-sha1 defined in RFC 3447.

            If the name attribute of the hash attribute of the algorithm attribute of key is SHA-256:

            Set the algorithm object identifier to the OID id-sha256 defined in RFC 3447.

            If the name attribute of the hash attribute of the algorithm attribute of key is SHA-384:

            Set the algorithm object identifier to the OID id-sha384 defined in RFC 3447.

            If the name attribute of the hash attribute of the algorithm attribute of key is SHA-512:

            Set the algorithm object identifier to the OID id-sha512 defined in RFC 3447.

          • Set the maskGenAlgorithm field to an instance of the MaskGenAlgorithm ASN.1 type with the following properties:

            • Set the algorithm field to the OID id-mgf1 defined in RFC 3447.

            • Set the params field to an instance of the HashAlgorithm ASN.1 type that is identical to the hashAlgorithm field.

          • Set the saltLength field to the length in octets of the digest algorithm identified by the name attribute of the hash attribute of the algorithm attribute of key.

      • Set the privateKey field to the result of DER-encoding an RSAPrivateKey ASN.1 type, as defined in RFC 3447, Appendix A.1.2, that represents the RSA private key identified by key

        Editorial note
        RFC 5208 specifies that the encoding of this field should be BER encoded in Section 5 (as a "for example"). However, to avoid requiring WebCrypto implementations support BER-encoding and BER-decoding, only DER encodings are produced or accepted.
    If format is "jwk":
    • Let jwk be a new internal object.

    • Set the kty field of jwk to the string "RSA".

    • Let hash be the name attribute of the hash attribute of the algorithm attribute of key.

    • If hash is SHA-1:

      Set the alg field of jwk to the string PS1.

      If hash is SHA-256:

      Set the alg field of jwk to the string PS256.

      If hash is SHA-384:

      Set the alg field of jwk to the string PS384.

      If hash is SHA-512:

      Set the alg field of jwk to the string PS512.

      Otherwise:

      Return an error named NotSupportedError.

    • Set the fields n and e of jwk according to the corresponding definitions in JSON Web Algorithms, Section 6.3.1.

    • If the type attribute of key is "private":
      1. Set the fields named d, p, q, dp, dq, and qi of jwk according to the corresponding definitions in JSON Web Algorithms, Section 6.3.2.

      2. If the underlying RSA private key represented by key is represented by more than two primes, set the field named oth of jwk according to the corresponding definition in JSON Web Algorithms, Section 6.3.2.7

    • Set the key_ops field of jwk to the usages attribute of key.

    • Set the ext field of jwk to the extractable attribute of key.

    • Let stringifiedJwk be the result of encoding jwk according to the grammar specified in Section 15.12 of ECMA262.

    • Let result be the UTF-8 encoding of stringifiedJwk.

    Otherwise

    Return an error named NotSupportedError.

  3. Let data be a new ArrayBuffer containing result.

  4. Return data.

18.7. RSA-OAEP

18.7.1. Description

The "RSA-OAEP" algorithm identifier is used to perform encryption and decryption ordering to the RSAES-OAEP algorithm specified in [RFC3447], using the mask generation function MGF1.

18.7.2. Registration

The recognized algorithm name for this algorithm is "RSA-OAEP".

Operation Parameters Result
encrypt RsaOaepParams ArrayBuffer
decrypt RsaOaepParams ArrayBuffer
generateKey RsaHashedKeyGenParams KeyPair
importKey RsaHashedImportParams Key
exportKey None ArrayBuffer

18.7.3. RsaOaepParams dictionary

IDL

dictionary RsaOaepParams : Algorithm {
  // The optional label/application data to associate with the message
  CryptoOperationData? label;
};
            

18.7.4. Operations

Encrypt
  1. If the type attribute of key is not "public", then return an error named InvalidAccessError.

  2. Let normalizedAlgorithm be the result of normalizing algorithm to RsaOaepParams.

  3. If any of the members of RsaOaepParams are not present in normalizedAlgorithm, then return an error named SyntaxError.

  4. Perform the encrytion operation defined in Section 7.1 of [RFC3447] with the key represented by key as the recipient's RSA public key, the contents of plaintext as the message to be encrypted, M and the label member of normalizedAlgorithm as the label, L, and with the hash function specified by the hash attribute of the algorithm attribute of key as the Hash option and MGF1 (defined in Section B.2.1 of [RFC3447]) as the MGF option.

  5. If performing the operation results in an error, then return an error named OperationError.

  6. Let ciphertext be a new ArrayBuffer containing the value C that results from performing the operation.

Decrypt
  1. If the type attribute of key is not "private", then return an error named InvalidAccessError.

  2. Let normalizedAlgorithm be the result of normalizing algorithm to RsaOaepParams.

  3. If any of the members of RsaOaepParams are not present in normalizedAlgorithm, then return an error named SyntaxError.

  4. Perform the decryption operation defined in Section 7.1 of [RFC3447] with the key represented by key as the recipient's RSA private key, the contents of ciphertext as the cipertext to be decrypted, C, and the label member of normalizedAlgorithm as the label, L, and with the hash function specified by the hash attribute of the algorithm attribute of key as the Hash option and MGF1 (defined in Section B.2.1 of [RFC3447]) as the MGF option.

  5. If performing the operation results in an error, then return an error named OperationError.

  6. Let plaintext be a new ArrayBuffer containing the value M that results from performing the operation.

Generate Key
  1. Let normalizedAlgorithm be the result of normalizing algorithm to RsaHashedKeyGenParams.

  2. If any of the members of RsaHashedKeyGenParams are not present in normalizedAlgorithm, then return an error named SyntaxError.

  3. If usages contains an entry which is not "encrypt", "decrypt, wrapKey or unwrapKey, then return an error named InvalidAccessError.

  4. Generate an RSA key pair, as defined in [RFC3447], with RSA modulus length equal to the modulusLength member of normalizedAlgorithm and RSA public exponent equal to the publicExponent member of normalizedAlgorithm.

  5. If performing the operation results in an error, then return an error named OperationError.

  6. Let algorithm be a new RsaHashedKeyAlgorithm object.

  7. Set the name attribute of algorithm to "RSA-OAEP".

  8. Set the modulusLength attribute of algorithm to equal the modulusLength member of normalizedAlgorithm.

  9. Set the publicExponent attribute of algorithm to equal the publicExponent member of normalizedAlgorithm.

  10. Set the hash attribute of algorithm to equal the hash member of normalizedAlgorithm.

  11. Let publicKey be a new Key object representing the public key of the generated key pair.

  12. Set the type attribute of publicKey to "public"

  13. Set the algorithm attribute of publicKey to be algorithm.

  14. Set the extractable attribute of publicKey to true.

  15. Set the usages attribute of publicKey to be the usage intersection of usages and [ "encrypt", "wrapKey" ].

  16. Let privateKey be a new Key object representing the private key of the generated key pair.

  17. Set the type attribute of privateKey to "private"

  18. Set the algorithm attribute of privateKey to be algorithm.

  19. Set the extractable attribute of privateKey to extractable.

  20. Set the usages attribute of privateKey to be the usage intersection of usages and [ "decrypt", "unwrapKey" ].

  21. Let result be a new KeyPair object.

  22. Set the publicKey attribute of result to be publicKey.

  23. Set the privateKey attribute of result to be privateKey.

  24. Return result.

Import Key
  1. Let keyData be the key data to be imported.

  2. Let normalizedAlgorithm be the result of normalizing algorithm to RsaHashedImportParams.

  3. If any of the members of RsaHashedImportParams are not present in normalizedAlgorithm then return an error named SyntaxError.

  4. If format is "spki":
    1. Let spki be the result of running the parse a subjectPublicKeyInfo algorithm over keyData.

    2. If an error occurred while parsing, then return an error named DataError.

    3. Let hash be a string whose initial value is undefined.

    4. Let alg be the algorithm object identifier field of the algorithm AlgorithmIdentifier field of spki.

    5. If alg is equivalent to the rsaEncryption OID defined in RFC 3447:

      Let hash be undefined.

      If alg is equivalent to the id-RSAES-OAEP OID defined in RFC 3447:
      1. Let params be the ASN.1 structure contained within the parameters field of the algorithm AlgorithmIdentifier field of spki.

      2. If params is not defined, or is not an instance of the RSAES-OAEP-params ASN.1 type defined in RFC3447, return an error named DataError.

      3. Let hashAlg be the AlgorithmIdentifier ASN.1 type within the hashAlgorithm field of params.

      4. If the algorithm object identifier field of hashAlg is equivalent to the id-sha1 OID defined in RFC 3447:

        Set hash to the string SHA-1.

        If the algorithm object identifier field of hashAlg is equivalent to the id-sha256 OID defined in RFC 3447:

        Set hash to the string SHA-256.

        If the algorithm object identifier field of hashAlg is equivalent to the id-sha384 OID defined in RFC 3447:

        Set hash to the string SHA-384.

        If the algorithm object identifier field of hashAlg is equivalent to the id-sha512 OID defined in RFC 3447:

        Set hash to the string SHA-512.

        Otherwise:

        Return an error named NotSupportedError.

      5. If the algorithm object identifier field of the maskGenAlgorithm field of params is not equivalent to the OID id-mgf1 defined in RFC 3447, return an error named NotSupportedError.

      6. If the parameters field of the maskGenAlgorithm field of params is not an instance of the HashAlgorithm ASN.1 type that is identical in content to the hashAlglorithm field of params, return an error named NotSupportedError.

      Otherwise:

      Return an error named DataError.

    6. If hash is defined, and is not equal to the name member of the hash member of normalizedAlgorithm, return an error named DataError.

    7. Set hash to the name member of the hash member of normalizedAlgorithm.

    8. Let publicKey be the result of performing the parse an ASN.1 structure algorithm, with data as the subjectPublicKeyInfo field of spki, structure as the RSAPublicKey structure specified in Section A.1.1 of RFC 3447, and exactData set to true.

    9. If an error occurred while parsing, then return an error named DataError.

    10. Let key be a new Key object that represents the RSA public key identified by publicKey.

    11. Set the type attribute of key to "public"

    If format is "pkcs8":
    1. Let privateKeyInfo be the result of running the parse a privateKeyInfo algorithm over keyData.

    2. If an error occurred while parsing, then return an error named DataError.

    3. Let hash be a string whose initial value is undefined.

    4. Let alg be the algorithm object identifier field of the privateKeyAlgorithm PrivateKeyAlgorithmIdentifier field of privateKeyInfo.

    5. If alg is equivalent to the rsaEncryption OID defined in RFC 3447:

      Let hash be undefined.

      If alg is equivalent to the id-RSAES-OAEP OID defined in RFC 3447:
      1. Let params be the ASN.1 structure contained within the parameters field of the privateKeyAlgorithm PrivateKeyAlgorithmIdentifier field of privateKeyInfo.

      2. If params is not defined, or is not an instance of the RSAES-OAEP-params ASN.1 type defined in RFC3447, return an error named NotSupportedError.

      3. Let hashAlg be the AlgorithmIdentifier ASN.1 type within the hashAlgorithm field of params.

      4. If the algorithm object identifier field of hashAlg is equivalent to the id-sha1 OID defined in RFC 3447:

        Set hash to the string SHA-1.

        If the algorithm object identifier field of hashAlg is equivalent to the id-sha256 OID defined in RFC 3447:

        Set hash to the string SHA-256.

        If the algorithm object identifier field of hashAlg is equivalent to the id-sha384 OID defined in RFC 3447:

        Set hash to the string SHA-384.

        If the algorithm object identifier field of hashAlg is equivalent to the id-sha512 OID defined in RFC 3447:

        Set hash to the string SHA-512.

        Otherwise:

        Return an error named NotSupportedError.

      5. If the algorithm object identifier field of the maskGenAlgorithm field of params is not equivalent to the OID id-mgf1 defined in RFC 3447, return an error named NotSupportedError.

      6. If the parameters field of the maskGenAlgorithm field of params is not an instance of the HashAlgorithm ASN.1 type that is identical in content to the hashAlglorithm field of params, return an error named NotSupportedError.

      Otherwise:

      Return an error named DataError.

    6. If hash is defined, and is not equal to the name member of the hash member of normalizedAlgorithm, return an error named DataError.

    7. Set hash to the name member of the hash member of normalizedAlgorithm.

    8. Let rsaPrivateKey be the result of performing the parse an ASN.1 structure algorithm, with data as the privateKey field of privateKeyInfo, structure as the RSAPrivateKey structure specified in Section A.1.2 of RFC 3447, and exactData set to true.

    9. If an error occurred while parsing, then return an error named DataError.

    10. Let key be a new Key object that represents the RSA private key identified by rsaPrivateKey.

    11. Set the type attribute of key to "private"

    If format is "jwk":
    1. Let jwk be the result of running the parse a jwk algorithm over keyData.

    2. If the "kty" field of jwk is not a case-sensitive string match to "RSA", then return an error named DataError.

    3. If the "use" field of jwk is present, and is not a case-sensitive string match to "enc", then return an error named DataError.

    4. If the "key_ops" field of jwk is present, and is invalid according to the requirements of JSON Web Key or does not contain all of the specified usages values, then return an error named DataError.

    5. If the alg field of jwk is present, and is not RSA-OAEP, return an error named DataError.

    6. Set hash to the name member of the hash member of normalizedAlgorithm.

    7. If the "d" field of jwk is present:
      1. If jwk does not meet the requirements of Section 6.3.2 of JSON Web Algorithms, then return an error named DataError.

      2. Let key be a new Key object that represents the RSA private key identified by interpreting jwk according to Section 6.3.2 of JSON Web Algorithms.

      3. Set the type attribute of key to "private"

      Otherwise:
      1. If jwk does not meet the requirements of Section 6.3.1 of JSON Web Algorithms, then return an error named DataError.

      2. Let key be a new Key object that represents the RSA public key identified by interpreting jwk according to Section 6.3.1 of JSON Web Algorithms.

      3. Set the type attribute of key to "public"

    Otherwise:
    Return an error named NotSupportedError.
  5. Let algorithm be a new RsaHashedKeyAlgorithm.

  6. Set the name attribute of algorithm to "RSA-OAEP"

  7. Set the modulusLength attribute of algorithm to the length, in bits, of the RSA public modulus.

  8. Set the publicExponent attribute of algorithm to the BigInteger representation of the RSA public exponent.

  9. Set the hash attribute of algorithm to a new KeyAlgorithm whose name attribute is hash.

  10. Set the algorithm attribute of key to algorithm

  11. Return key.

Export Key
  1. Let key be the key to be exported.

  2. If format is "spki"
    1. If the type attribute of key is not "public", then return an error named InvalidAccessError.

    2. Let result be the result of encoding a subjectPublicKeyInfo with the following properties:

      • Set the algorithm field to an AlgorithmIdentifier ASN.1 type with the following properties:

        • Set the algorithm field to the OID id-RSAES-OAEP defined in RFC 3447.

        • Set the params field to an instance of the RSAES-OAEP-params ASN.1 type with the following properties:

          • Set the hashAlgorithm field to an instance of the HashAlgorithm ASN.1 type with the following properties:

            If the name attribute of the hash attribute of the algorithm attribute of key is SHA-1:

            Set the algorithm object identifier to the OID id-sha1 defined in RFC 3447.

            If the name attribute of the hash attribute of the algorithm attribute of key is SHA-256:

            Set the algorithm object identifier to the OID id-sha256 defined in RFC 3447.

            If the name attribute of the hash attribute of the algorithm attribute of key is SHA-384:

            Set the algorithm object identifier to the OID id-sha384 defined in RFC 3447.

            If the name attribute of the hash attribute of the algorithm attribute of key is SHA-512:

            Set the algorithm object identifier to the OID id-sha512 defined in RFC 3447.

          • Set the maskGenAlgorithm field to an instance of the MaskGenAlgorithm ASN.1 type with the following properties:

            • Set the algorithm field to the OID id-mgf1 defined in RFC 3447.

            • Set the params field to an instance of the HashAlgorithm ASN.1 type that is identical to the hashAlgorithm field.

      • Set the subjectPublicKey field to the result of DER-encoding an RSAPublicKey ASN.1 type, as defined in RFC 3447, Appendix A.1.1, that represents the RSA public key identified by key

    If format is "pkcs8":
    1. If the type attribute of key is not "private", then return an error named InvalidAccessError.

    2. Let result be the result of encoding a privateKeyInfo with the following properties:

      • Set the version field to 0.

      • Set the privateKeyAlgorithm field to an PrivateKeyAlgorithmIdentifier ASN.1 type with the following properties:

        • Set the algorithm field to the OID id-RSAES-OAEP defined in RFC 3447.

        • Set the params field to an instance of the RSAES-OAEP-params ASN.1 type with the following properties:

          • Set the hashAlgorithm field to an instance of the HashAlgorithm ASN.1 type with the following properties:

            If the name attribute of the hash attribute of the algorithm attribute of key is SHA-1:

            Set the algorithm object identifier to the OID id-sha1 defined in RFC 3447.

            If the name attribute of the hash attribute of the algorithm attribute of key is SHA-256:

            Set the algorithm object identifier to the OID id-sha256 defined in RFC 3447.

            If the name attribute of the hash attribute of the algorithm attribute of key is SHA-384:

            Set the algorithm object identifier to the OID id-sha384 defined in RFC 3447.

            If the name attribute of the hash attribute of the algorithm attribute of key is SHA-512:

            Set the algorithm object identifier to the OID id-sha512 defined in RFC 3447.

          • Set the maskGenAlgorithm field to an instance of the MaskGenAlgorithm ASN.1 type with the following properties:

            • Set the algorithm field to the OID id-mgf1 defined in RFC 3447.

            • Set the params field to an instance of the HashAlgorithm ASN.1 type that is identical to the hashAlgorithm field.

      • Set the privateKey field to the result of DER-encoding an RSAPrivateKey ASN.1 type, as defined in RFC 3447, Appendix A.1.2, that represents the RSA private key identified by key

        Editorial note
        RFC 5208 specifies that the encoding of this field should be BER encoded in Section 5 (as a "for example"). However, to avoid requiring WebCrypto implementations support BER-encoding and BER-decoding, only DER encodings are produced or accepted.
    If format is "jwk":
    • Let jwk be a new internal object.

    • Set the kty field of jwk to the string "RSA".

    • Set the alg field of jwk to the string RSA-OAEP.

    • Set the fields n and e of jwk according to the corresponding definitions in JSON Web Algorithms, Section 6.3.1.

    • If the type attribute of key is "private":
      1. Set the fields named d, p, q, dp, dq, and qi of jwk according to the corresponding definitions in JSON Web Algorithms, Section 6.3.2.

      2. If the underlying RSA private key represented by key is represented by more than two primes, set the field named oth of jwk according to the corresponding definition in JSON Web Algorithms, Section 6.3.2.7

    • Set the key_ops field of jwk to the usages attribute of key.

    • Set the ext field of jwk to the extractable attribute of key.

    • Let stringifiedJwk be the result of encoding jwk according to the grammar specified in Section 15.12 of ECMA262.

    • Let result be the UTF-8 encoding of stringifiedJwk.

    Otherwise

    Return an error named NotSupportedError.

  3. Let data be a new ArrayBuffer containing result.

  4. Return data.

18.8. ECDSA

18.8.1. Description

The "ECDSA" algorithm identifier is used to perform signing and verification using the ECDSA algorithm specified in [X9.62].

18.8.2. Registration

The recognized algorithm name for this algorithm is "ECDSA".

Operation Parameters Result
sign EcdsaParams ArrayBuffer
verify EcdsaParams boolean
generateKey EcKeyGenParams KeyPair
importKey None Key
exportKey None ArrayBuffer

18.8.3. EcdsaParams dictionary

IDL

dictionary EcdsaParams : Algorithm {
  // The hash algorithm to use
  AlgorithmIdentifier hash;
};
            

18.8.4. EcKeyGenParams dictionary

IDL

typedef DOMString NamedCurve;

dictionary EcKeyGenParams : Algorithm {
  // A named curve
  NamedCurve namedCurve;
};
            

The NamedCurve type represents named elliptic curves, which are a convenient way to specify the domain parameters of well-known elliptic curves. The following values are recognized:

P-256
NIST recommended curve P-256, also known as secp256r1.
P-384
NIST recommended curve P-384, also known as secp384r1.
P-521
NIST recommended curve P-521, also known as secp521r1.

18.8.5. EcKeyAlgorithm interface

IDL

[NoInterfaceObject]
interface EcKeyAlgorithm : KeyAlgorithm {
  // The named curve that the key uses
  readonly attribute NamedCurve namedCurve;
};
            

18.8.6. EcKeyImportParams dictionary

IDL

dictionary EcKeyImportParams : Algorithm {
  // A named curve
  NamedCurve namedCurve;
};
            

18.8.7. Operations

Sign
When signing, the following algorithm should be used:
  1. If the type attribute of key is not "private", then return an error named InvalidAccessError.

  2. Let normalizedAlgorithm be the result of normalizing algorithm to EcdsaParams.

  3. If any of the properties of EcdsaParams are not present in normalizedAlgorithm, then return an error named SyntaxError.

  4. Let hashAlgorithm be the hash member of normalizedAlgorithm.

  5. If hashAlgorithm does not describe a registered algorithm that supports the digest operation, then return an error named NotSupportedError.

  6. Let M be the result of performing the digest operation specified by hashAlgorithm using message.

  7. Let d be the ECDSA private key associated with key.

  8. Let params be the EC domain parameters associated with key.

  9. Perform the ECDSA signing process, as specified in X9.62, Section 7.3, with M as the message, using params as the EC domain parameters, and with d as the private key.

  10. Let r and s be the pair of integers resulting from performing the ECDSA signing process.

  11. Let result be a new ArrayBuffer.

  12. Convert r to a bitstring and append the sequence of bytes to result.

  13. Convert s to a bitstring and append the sequence of bytes to result.

  14. Return result.

Verify
When verifying, the following algorithm should be used:
  1. If the type attribute of key is not "public", then return an error named InvalidAccessError.

  2. Let normalizedAlgorithm be the result of normalizing algorithm to EcdsaParams.

  3. If any of the properties of EcdsaParams are not present in normalizedAlgorithm, then return an error named SyntaxError.

  4. Let hashAlgorithm be the hash member of normalizedAlgorithm.

  5. If hashAlgorithm does not describe a registered algorithm that supports the digest operation, then return an error named NotSupportedError.

  6. Let M be the result of performing the digest operation specified by hashAlgorithm using message.

  7. Let Q be the ECDSA public key associated with key.

  8. Let params be the EC domain parameters associated with key.

  9. Perform the ECDSA verifying process, as specified in X9.62, Section 7.4, with M as the received message, signatire as the received signature and using params as the EC domain parameters, and Q as the public key.

  10. Let result be a boolean indicating whether or not the purported signature is valid, with true indicating the signature is valid and false indicating it is invalid.

  11. Return result.

Generate Key
  1. Let normalizedAlgorithm be the result of normalizing algorithm to EcKeyGenParams.

  2. If any of the members of EcKeyGenParams are not present in normalizedAlgorithm, then return an error named SyntaxError.

  3. If usages contains a value which is not one of "sign" or "verify", then return an error named InvalidAccessError.

  4. Generate an Eliptic Curve key pair, as defined in [X9.62] with domain parameters for the curve identified by the namedCurve member of normalizedAlgorithm.

  5. If performing the key generation operation results in an error, then return an error named OperationError.

  6. Let algorithm be a new EcKeyAlgorithm object.

  7. Set the name attribute of algorithm to "ECDSA".

  8. Set the namedCurve attribute of algorithm to equal the namedCurve member of normalizedAlgorithm.

  9. Let publicKey be a new Key object representing the public key of the generated key pair.

  10. Set the type attribute of publicKey to "public"

  11. Set the algorithm attribute of publicKey to be algorithm.

  12. Set the extractable attribute of publicKey to true.

  13. Set the usages attribute of publicKey to be the empty list.

  14. Let privateKey be a new Key object representing the private key of the generated key pair.

  15. Set the type attribute of privateKey to "private"

  16. Set the algorithm attribute of privateKey to be algorithm.

  17. Set the extractable attribute of privateKey to extractable.

  18. Set the usages attribute of privateKey to be the usage intersection of usages and [ "sign", "verify" ].

  19. Let result be a new KeyPair object.

  20. Set the publicKey attribute of result to be publicKey.

  21. Set the privateKey attribute of result to be privateKey.

  22. Return result.

Import Key
  1. Let keyData be the key data to be imported.

  2. If format is "spki":
    1. Let spki be the result of running the parse a subjectPublicKeyInfo algorithm over keyData

    2. If an error occurred while parsing, then return an error named DataError.

    3. If the algorithm object identifier field of the algorithm AlgorithmIdentifier field of spki is not equal to the id-ecPublicKey object identifier defined in RFC 5480, then return an error named DataError.

    4. If the parameters field of the algorithm AlgorithmIdentifier field of spki is absent, then return an error named DataError.

    5. Let params be the parameters field of the algorithm AlgorithmIdentifier field of spki.

    6. If params is not an instance of the namedCurve ASN.1 type defined in RFC 5480, then return an error named DataError.

    7. Let key be a new Key object that represents the Elliptic Curve public key identified by performing the conversion steps defined in Section 2.2 of RFC 5480.

    8. Set the type attribute of key to "public"

    9. Let algorithm be a new EcKeyAlgorithm.

    10. Set the name attribute of algorithm to "ECDSA".

    11. If params is equivalent to the secp256r1 object identifier defined in RFC 5480:

      Set the namedCurve attribute of algorithm to "P-256".

      If params is equivalent to the secp384r1 object identifier defined in RFC 5480:

      Set the namedCurve attribute of algorithm to "P-384".

      If params is equivalent to the secp521r1 object identifier defined in RFC 5480:

      Set the namedCurve attribute of algorithm to "P-521".

      Otherwise:

      Return an error named DataError.

    12. Set the algorithm attribute of key to algorithm.

    If format is "pkcs8":
    1. Let privateKeyInfo be the result of running the parse a privateKeyInfo algorithm over keyData.

    2. If an error occurs while parsing, then return an error named DataError.

    3. If the algorithm object identifier field of the privateKeyAlgorithm PrivateKeyAlgorithm field of privateKeyInfo is not equal to the id-ecPublicKey object identifier defined in RFC 5480, then return an error named DataError.

    4. If the parameters field of the privateKeyAlgorithm PrivateKeyAlgorithmIdentifier field of privateKeyInfo is not present, then return an error named DataError.

    5. Let params be the parameters field of the privateKeyAlgorithm PrivateKeyAlgorithmIdentifier field of privateKeyInfo.

    6. If the params is not an instance of the namedCurve ASN.1 type defined in RFC 5480, then return an error named DataError.

    7. Let ecPrivateKey be the result of performing the parse an ASN.1 structure algorithm, with data as the privateKey field of privateKeyInfo, structure as the ASN.1 ECPrivateKey structure specified in Section 3 of RFC 5915, and exactData set to true.

    8. If an error occurred while parsing, then return an error named DataError.

    9. If the parameters field of ecPrivateKey is present, and is not an instance of the namedCurve ASN.1 type defined in RFC 5480, or does not contain the same object identifier as the parameters field of the privateKeyAlgorithm PrivateKeyAlgorithmIdentifier field of privateKeyInfo, then return an error named DataError.

    10. Let key be a new Key object that represents the Elliptic Curve private key identified by performing the conversion steps defined in Section 3 of RFC 5915.

    11. Set the type attribute of key to "private"

    12. Let algorithm be a new EcKeyAlgorithm.

    13. Set the name attribute of algorithm to "ECDSA".

    14. If params is equivalent to the secp256r1 object identifier defined in RFC 5480:

      Set the namedCurve attribute of algorithm to "P-256".

      If params is equivalent to the secp384r1 object identifier defined in RFC 5480:

      Set the namedCurve attribute of algorithm to "P-384".

      If params is equivalent to the secp521r1 object identifier defined in RFC 5480:

      Set the namedCurve attribute of algorithm to "P-521".

      Otherwise:

      Return an error named DataError.

    15. Set the algorithm attribute of key to algorithm.

    If format is "jwk":
    1. Let jwk be the result of running the parse a JWK algorithm over keyData.

    2. If an error occurred while parsing, then return an error named DataError.

    3. If the "kty" field of jwk is not "EC", then return an error named DataError.

    4. If the "use" field of jwk is present, and is not "sig", then return an error named DataError.

    5. If the "key_ops" field of jwk is present, and is invalid according to the requirements of JSON Web Key, or it does not contain all of the specified usages values, then return an error named DataError.

    6. If the "ext" field of jwk is present and has the value false and extractable is true, then return an error named DataError.

    7. If the "d" field is present:
      1. If jwk does not meet the requirements of Section 6.2.2 of JSON Web Algorithms, then return an error named DataError.

      2. Let key be a new Key object that represents the Elliptic Curve private key identified by interpreting jwk according to Section 6.2.2 of JSON Web Algorithms.

      3. Set the type attribute of Key to "private".

      Otherwise:
      1. If jwk does not meet the requirements of Section 6.2.1 of JSON Web Algorithms, then return an error named DataError.

      2. Let key be a new Key object that represents the Elliptic Curve public key identified by interpreting jwk according to Section 6.2.1 of JSON Web Algorithms.

      3. Set the type attribute of Key to "public".

    8. Let algorithm be a new instance of an EcKeyAlgorithm object.

    9. Set the name attribute of algorithm to "ECDSA".

    10. If the "crv" field of jwk is "P-256"

      Set the namedCurve attribute of algorithm to "P-256".

      If the "crv" field of jwk is "P-384"

      Set the namedCurve attribute of algorithm to "P-384".

      If the "crv" field of jwk is to "P-521"

      Set the namedCurve attribute of algorithm to "P-521".

      Otherwise:

      Return an error named DataError.

    11. Set the algorithm attribute of key to algorithm.

    Otherwise:

    Return an error named NotSupportedError.

  3. Return key

Export Key
  1. Let key be the Key to be exported.

  2. If format is "spki":
    1. If the type attribute of key is not "public", then return an error named InvalidAccessError.

    2. Let result be the result of >encoding a subjectPublicKeyInfo with the following properties:

      • Set the algorithm field to an AlgorithmIdentifier ASN.1 type with the following properties:

        • Set the algorithm object identifier to the OID 1.2.840.10045.2.1.

        • Set the parameters field to an instance of the namedCurve ASN.1 type as follows:

          If the namedCurve attribute of the algorithm attribute of key is "P-256":

          Let the namedCurve be the object identifier secp256r1 defined in RFC 5480

          If the namedCurve attribute of the algorithm attribute of key is "P-384":

          Let the namedCurve be the object identifier secp384r1 defined in RFC 5480

          If the namedCurve attribute of the algorithm attribute of key is "P-521":

          Let the namedCurve be the object identifier secp521r1 defined in RFC 5480

      • Set the subjectPublicKey field to the octet string that represents the Elliptic Curve public key identified by key according to the encoding rules specified in Section 2.2 of RFC 5480 and using the uncompressed form.

    If format is "pkcs8":
    1. If the type attribute of key is not "private", then return an error named InvalidAccessError.

    2. Let result be the result of encoding a privateKeyInfo with the following properties:

      • Set the version field to 0.

      • Set the privateKeyAlgorithm field to an PrivateKeyAlgorithmIdentifier ASN.1 type with the following properties:

        • Set the algorithm object identifier to the OID 1.2.840.10045.2.1.

        • Set the parameters field to an instance of the namedCurve ASN.1 type as follows:

          If the namedCurve attribute of the algorithm attribute of key is "P-256":

          Let the namedCurve be the object identifier secp256r1 defined in RFC 5480

          If the namedCurve attribute of the algorithm attribute of key is "P-384":

          Let the namedCurve be the object identifier secp384r1 defined in RFC 5480

          If the namedCurve attribute of the algorithm attribute of key is "P-521":

          Let the namedCurve be the object identifier secp521r1 defined in RFC 5480

      • Set the privateKey field to the result of DER-encoding an instance of the ECPrivateKey structure defined in Section 3 of RFC 5915 for the Elliptic Curve private key represented by key and that conforms to the following:

        • The parameters field is present, and is equivalent to the parameters field of the privateKeyAlgorithm field of this PrivateKeyInfo ASN.1 structure.

        • The publicKey field is present and represents the Elliptic Curve public key associated with the Elliptic Curve private key represented by key.

    If format is "jwk":
    1. Let jwk be a new internal object.

    2. Set the kty property of jwk to "EC".

    3. If the namedCurve attribute of the algorithm attribute of key is P-256:
      Set the crv property of jwk to "P-256"
      If the namedCurve attribute of the algorithm attribute of key is P-384:
      Set the crv property of jwk to "P-384"
      If the namedCurve attribute of the algorithm attribute of key is P-521:
      Set the crv property of jwk to "P-521"
    4. Set the x property of jwk according to the definition in Section 6.2.1.2 of JSON Web Algorithms.

    5. Set the y property of jwk according to the definition in Section 6.2.1.3 of JSON Web Algorithms.

    6. If the type attribute of key is private

      Set the d property of jwk according to the definition in Section 6.2.2.1 of JSON Web Algorithms.

    7. Set the key_ops property of jwk to the usages attribute of key.

    8. Set the ext property of jwk to the extractable attribute of key.

    9. Let stringifiedJwk be the result of encoding jwk into a string according to the grammer specified in Section 15.12 of ECMA262.

    10. Let data be the UTF-8 encoding of stringifiedJwk.

    Otherwise:

    Return an error named NotSupportedError.

  3. Let data be a new ArrayBuffer that contains result.

  4. Return data.

Editorial note

OPEN ISSUE: The import/export of JWK ignores the "alg" field, because it does not provide a 1:1 mapping between ECDSA (which choses the hash at sign/verify time, because it is safe to do so) and the JWS alg (which incorporates the hash algorithm).

18.9. ECDH

18.9.1. Description

This describes using Elliptic Curve Diffie-Hellman (ECDH) for key generation and key agreement, as specified by X9.63.

18.9.2. Registration

The recognized algorithm name for this algorithm is "ECDH".

Operation Parameters Result
generateKey EcKeyGenParams KeyPair
deriveBits EcdhKeyDeriveParams Octet string
importKey EcKeyImportParams Key
exportKey None ArrayBuffer

18.9.3. EcdhKeyDeriveParams dictionary

IDL

typedef Uint8Array ECPoint;

dictionary EcdhKeyDeriveParams : Algorithm {
  // The peer's EC public key.
  Key public;
};
            

18.9.4. Operations

Generate Key
  1. Let normalizedAlgorithm be the result of normalizing algorithm to EcKeyGenParams.

  2. If any of the members of EcKeyGenParams are not present in normalizedAlgorithm, then return an error named SyntaxError.

  3. If usages contains a value which is not one of "deriveKey" or "deriveBits", then return an error named InvalidAccessError.

  4. Generate an Elliptic Curve key pair, as defined in [X9.63] with domain parameters for the curve identified by the namedCurve member of normalizedAlgorithm.

  5. If performing the operation results in an error, then return an error named OperationError.

  6. Let algorithm be a new EcKeyAlgorithm object.

  7. Set the name member of algorithm to "ECDH".

  8. Set the namedCurve attribute of algorithm to equal the namedCurve member of normalizedAlgorithm.

  9. Let publicKey be a new Key object representing the public key of the generated key pair.

  10. Set the type attribute of publicKey to "public"

  11. Set the algorithm attribute of publicKey to be algorithm.

  12. Set the extractable attribute of publicKey to true.

  13. Set the usages attribute of publicKey to be the empty list.

  14. Let privateKey be a new Key object representing the private key of the generated key pair.

  15. Set the type attribute of privateKey to "private"

  16. Set the algorithm attribute of privateKey to be algorithm.

  17. Set the extractable attribute of privateKey to extractable.

  18. Set the usages attribute of privateKey to be the usage intersection of usages and [ "deriveKey", "deriveBits" ].

  19. Let result be a new KeyPair object.

  20. Set the publicKey attribute of result to be publicKey.

  21. Set the privateKey attribute of result to be privateKey.

  22. Return result.

Derive Bits
  1. If the type attribute of key is not "private", then return an error named InvalidAccessError.

  2. Let normalizedAlgorithm be the result of normalizing algorithm to EcdhKeyDeriveParams.

  3. If any of the members of EcdhKeyDeriveParams are not present in normalizedAlgorithm, then return an error named SyntaxError.

  4. Let publicKey be the public member of normalizedAlgorithm.

  5. If the name attribute of the algorithm attribute of publicKey is not "ECDH", then return an error named InvalidAccessError.

  6. If the type attribute of publicKey is not "public", then return an error named InvalidAccessError.

  7. If the namedCurve attribute of the algorithm attribute of publicKey is not equal to the namedCurve property of the algorithm attribute of key, then return an error named DataError.

  8. Perform the ECDH primitive specified in X9.63 Section 5.4.1 with key as the EC private key d and the EC public key represented by publicKey as the EC public key Q.

  9. If performing the operation results in an error, then return an error named OperationError.

  10. Let secret be the result of applying the field element to octet string comversion defined in Section ? of X9.63 to the output of the ECDH primitive.

  11. If length is null:
    Return secret
    Otherwise:
    If the length of secret in bits is less than length:
    Return an error named DataError.
    Otherwise:
    Return the first length bits of secret.
Import Key
  1. Let keyData be the key data to be imported.

  2. If format is "spki":
    1. Let spki be the result of running the parse a subjectPublicKeyInfo algorithm over keyData

    2. If an error occurred while parsing, then return an error named DataError.

    3. If the algorithm object identifier field of the algorithm AlgorithmIdentifier field of spki is not equal to the id-ecPublicKey or id-ecDH object identifiers defined in RFC 5480, then return an error named DataError.

    4. If the parameters field of the algorithm AlgorithmIdentifier field of spki is absent, then return an error named SyntaxError.

    5. Let params be the parameters field of the algorithm AlgorithmIdentifier field of spki.

    6. If params is not an instance of the namedCurve ASN.1 type defined in RFC 5480, then return an error named DataError.

    7. Let key be a new Key object that represents the Elliptic Curve public key identified by performing the conversion steps defined in Section 2.2 of RFC 5480.

    8. Set the type attribute of key to "public"

    9. Let algorithm be a new EcKeyAlgorithm.

    10. Set the name attribute of algorithm to "ECDH".

    11. If params is equivalent to the secp256r1 object identifier defined in RFC 5480:

      Set the namedCurve attribute of algorithm to "P-256".

      If params is equivalent to the secp384r1 object identifier defined in RFC 5480:

      Set the namedCurve attribute of algorithm to "P-384".

      If params is equivalent to the secp521r1 object identifier defined in RFC 5480:

      Set the namedCurve attribute of algorithm to "P-521".

      Otherwise:

      Return an error named DataError.

    12. Set the algorithm attribute of key to algorithm.

    If format is "pkcs8":
    1. Let privateKeyInfo be the result of running the parse a privateKeyInfo algorithm over keyData.

    2. If an error occurs while parsing, return an error named DataError.

    3. If the algorithm object identifier field of the privateKeyAlgorithm PrivateKeyAlgorithm field of privateKeyInfo is not equal to the id-ecPublicKey or id-ecDH object identifiers defined in RFC 5480, return an error named DataError.

    4. If the parameters field of the privateKeyAlgorithm PrivateKeyAlgorithmIdentifier field of privateKeyInfo is not present, return an error named DataError.

    5. Let params be the parameters field of the privateKeyAlgorithm PrivateKeyAlgorithmIdentifier field of privateKeyInfo.

    6. If the params is not an instance of the namedCurve ASN.1 type defined in RFC 5480, return an error named DataError.

    7. Let ecPrivateKey be the result of performing the parse an ASN.1 structure algorithm, with data as the privateKey field of privateKeyInfo, structure as the ASN.1 ECPrivateKey structure specified in Section 3 of RFC 5915, and exactData set to true.

    8. If an error occurred while parsing, then return an error named DataError.

    9. If the parameters field of ecPrivateKey is present, and is not an instance of the namedCurve ASN.1 type defined in RFC 5480, or does not contain the same object identifier as the parameters field of the privateKeyAlgorithm PrivateKeyAlgorithmIdentifier field of privateKeyInfo, return an error named DataError.

    10. Let key be a new Key object that represents the Elliptic Curve private key identified by performing the conversion steps defined in Section 3 of RFC 5915.

    11. Set the type attribute of key to "private".

    12. Let algorithm be a new EcKeyAlgorithm.

    13. Set the name attribute of algorithm to "ECDH".

    14. If params is equivalent to the secp256r1 object identifier defined in RFC 5480:

      Set the namedCurve attribute of algorithm to "P-256".

      If params is equivalent to the secp384r1 object identifier defined in RFC 5480:

      Set the namedCurve attribute of algorithm to "P-384".

      If params is equivalent to the secp521r1 object identifier defined in RFC 5480:

      Set the namedCurve attribute of algorithm to "P-521".

      Otherwise:

      Return an error named DataError.

    15. Set the algorithm attribute of key to algorithm.

    If format is "jwk":
    1. Let jwk be the result of running the parse a JWK algorithm over keyData.

    2. If an error occurred while parsing, then return an error named DataError.

    3. If the "kty" field of jwk is to "EC", then return an error named DataError.

    4. If the "use" field of jwk is present, then return an error named DataError.

    5. If the "key_ops" field of jwk is present, and is invalid according to the requirements of JSON Web Key, or it does not contain all of the specified usages values, then return an error named DataError.

    6. If the "ext" field of jwk is present and has the value false and extractable is true, then return an error named DataError.

    7. If the "d" field is present:
      1. If jwk does not meet the requirements of Section 6.2.2 of JSON Web Algorithms, then return an error named DataError.

      2. Let key be a new Key object that represents the Elliptic Curve private key identified by interpreting jwk according to Section 6.2.2 of JSON Web Algorithms.

      3. Set the type attribute of Key to "private".

      Otherwise:
      1. If jwk does not meet the requirements of Section 6.2.1 of JSON Web Algorithms, then return an error named DataError.

      2. Let key be a new Key object that represents the Elliptic Curve public key identified by interpreting jwk according to Section 6.2.1 of JSON Web Algorithms.

      3. Set the type attribute of Key to "public".

    8. Let algorithm be a new instance of an EcKeyAlgorithm object.

    9. Set the name attribute of algorithm to "ECDH".

    10. If the "crv" field of jwk is a "P-256"

      Set the namedCurve attribute of algorithm to "P-256".

      If the "crv" field of jwk is "P-384"

      Set the namedCurve attribute of algorithm to "P-384".

      If the "crv" field of jwk is "P-521"

      Set the namedCurve attribute of algorithm to "P-521".

      Otherwise:

      Return an error named DataError.

    11. Set the algorithm attribute of key to algorithm.

    If format is "raw":
    1. If any of the members of EcKeyImportParams are not present in normalizedAlgorithm, then return an error named SyntaxError.

    2. If the namedCurve member of normalizedAlgorithm is not a named curve, then return an error named DataError.

    3. If usages is not the empty list, then return an error named DataError.

    4. If extractable is false, then return an error named InvalidAccessError.

    5. Let Q be the elliptic curve point on the curve identified by the namedCurve member of normalizedAlgorithm identified by interpreting keyData according to X9.62 Annex A.

    6. Let algorithm be a new EcKeyAlgorithm object.

    7. Set the name attribute of algorithm to "ECDH".

    8. Set the namedCurve attribute of algorithm to equal the namedCurve member of normalizedAlgorithm.

    9. Let key be a new Key object.

    10. Set the type attribute of key to "public"

    11. Set the algorithm attribute of key to algorithm.

    12. Set the usages attribute of key to usages.

    13. Set the extractable attribute of key to extractable.

    Otherwise:

    Return an error named NotSupportedError.

  3. Return key

Export Key
  1. Let key be the Key to be exported.

  2. If format is "spki":
    1. If the type attribute of key is not "public", then return an error named InvalidAccessError.

    2. Let result be the result of encoding a subjectPublicKeyInfo with the following properties:

      • Set the algorithm field to an AlgorithmIdentifier ASN.1 type with the following properties:

        • Set the algorithm object identifier to the OID 1.3.132.112.

        • Set the parameters field to an instance of the namedCurve ASN.1 type as follows:

          If the namedCurve attribute of the algorithm attribute of key is "P-256":

          Let the namedCurve be the object identifier secp256r1 defined in RFC 5480

          If the namedCurve attribute of the algorithm attribute of key is "P-384":

          Let the namedCurve be the object identifier secp384r1 defined in RFC 5480

          If the namedCurve attribute of the algorithm attribute of key is "P-521":

          Let the namedCurve be the object identifier secp521r1 defined in RFC 5480

      • Set the subjectPublicKey field to the octet string that represents the Elliptic Curve public key identified by key according to the encoding rules specified in Section 2.2 of RFC 5480 and using the uncompressed form.

    If format is "pkcs8":
    1. If the type attribute of key is not "private", then return an error named InvalidAccessError.

    2. Let result be the result of encoding a privateKeyInfo with the following properties:

      • Set the version field to 0.

      • Set the privateKeyAlgorithm field to an PrivateKeyAlgorithmIdentifier ASN.1 type with the following properties:

        • Set the algorithm object identifier to the OID 1.3.132.112.

        • Set the parameters field to an instance of the namedCurve ASN.1 type as follows:

          If the namedCurve attribute of the algorithm attribute of key is "P-256":

          Let the namedCurve be the object identifier secp256r1 defined in RFC 5480

          If the namedCurve attribute of the algorithm attribute of key is "P-384":

          Let the namedCurve be the object identifier secp384r1 defined in RFC 5480

          If the namedCurve attribute of the algorithm attribute of key is "P-521":

          Let the namedCurve be the object identifier secp521r1 defined in RFC 5480

      • Set the privateKey field to the result of DER-encoding an instance of the ECPrivateKey structure defined in Section 3 of RFC 5915 for the Elliptic Curve private key represented by key and that conforms to the following:

        • The parameters field is present, and is equivalent to the parameters field of the privateKeyAlgorithm field of this PrivateKeyInfo ASN.1 structure.

        • The publicKey field is present and represents the Elliptic Curve public key associated with the Elliptic Curve private key represented by key.

    If format is "jwk":
    1. Let jwk be a new internal object.

    2. Set the kty property of jwk to "EC".

    3. If the namedCurve attribute of the algorithm attribute of key is P-256:
      Set the crv property of jwk to "P-256"
      If the namedCurve attribute of the algorithm attribute of key is P-384:
      Set the crv property of jwk to "P-384"
      If the namedCurve attribute of the algorithm attribute of key is P-521:
      Set the crv property of jwk to "P-521"
    4. Set the x property of jwk according to the definition in Section 6.2.1.2 of JSON Web Algorithms.

    5. Set the y property of jwk according to the definition in Section 6.2.1.3 of JSON Web Algorithms.

    6. If the type attribute of key is private

      Set the d property of jwk according to the definition in Section 6.2.2.1 of JSON Web Algorithms.

    7. Set the key_ops property of jwk to the usages attribute of key.

    8. Set the ext property of jwk to the extractable attribute of key.

    9. Let stringifiedJwk be the result of encoding jwk into a string according to the grammer specified in Section 15.12 of ECMA262.

    10. Let data be the UTF-8 encoding of stringifiedJwk.

    If format is "raw":
    1. If the type attribute of key is not "public", then return an error named InvalidAccessError.

    2. Let data be an octet string representing the Elliptic Curve point Q represented by key according to X9.62 Annex A.

    Otherwise:

    Return an error named NotSupportedError.

  3. Let data be a new ArrayBuffer that contains result.

  4. Return data.

18.10. AES-CTR

18.10.1. Description

This section is non-normative.

The "AES-CTR" algorithm identifier is used to perform encryption and decryption using AES in Counter mode, as described in NIST SP 800-38A [SP800-38A].

18.10.2. Registration

The recognized algorithm name for this algorithm is "AES-CTR".

Operation Parameters Result
encrypt AesCtrParams ArrayBuffer
decrypt AesCtrParams ArrayBuffer
generateKey AesKeyGenParams Key
importKey None Key
exportKey None ArrayBuffer
get key length AesDerivedKeyParams Integer

18.10.3. AesCtrParams dictionary

IDL

dictionary AesCtrParams : Algorithm {
  // The initial value of the counter block. counter MUST be 16 bytes
  // (the AES block size). The counter bits are the rightmost length
  // bits of the counter block. The rest of the counter block is for
  // the nonce. The counter bits are incremented using the standard
  // incrementing function specified in NIST SP 800-38A Appendix B.1:
  // the counter bits are interpreted as a big-endian integer and
  // incremented by one.
  CryptoOperationData counter;
  // The length, in bits, of the rightmost part of the counter block
  // that is incremented.
  [EnforceRange] octet length;
};
            
IDL

[NoInterfaceObject]
interface AesKeyAlgorithm : KeyAlgorithm {
  // The length, in bits, of the key.
  readonly attribute unsigned short length;
};
            

18.10.5. AesKeyGenParams dictionary

IDL

dictionary AesKeyGenParams : Algorithm {
  // The length, in bits, of the key.
  [EnforceRange] unsigned short length;
};
            

18.10.6. AesDerivedKeyParams dictionary

IDL

dictionary AesDerivedKeyParams : Algorithm {
  // The length, in bits, of the key.
  [EnforceRange] unsigned short length;
};
            

18.10.7. Operations

Encrypt
  1. Let normalizedAlgorithm be the result of normalizing algorithm to AesCtrParams.

  2. If any of the members of AesCtrParams are not present in normalizedAlgorithm, then return an error named SyntaxError.

  3. If the counter member of normalizedAlgorithm does not have length 16 bytes, then return an error named DataError.

  4. If the length member of normalizedAlgorithm is zero or is greater than 128, then return an error named DataError.

  5. Let ciphertext be the result of performing the CTR Encryption operation described in Section 6.5 of NIST SP 800-38A [SP800-38A] using AES as the block cipher, the contents of the counter member of normalizedAlgorithm as the initial value of the counter block, the length member of normalizedAlgorithm as the input parameter m to the standard counter block incrementing functon defined in Appendix B.1 of NIST SP 800-38A [SP800-38A] and plaintext as the input plaintext.

  6. Return ciphertext.

Decrypt
  1. Let normalizedAlgorithm be the result of normalizing algorithm to AesCtrParams.

  2. If any of the members of AesCtrParams are not present in normalizedAlgorithm, then return an error named SyntaxError.

  3. If the counter member of normalizedAlgorithm does not have length 16 bytes, then return an error named DataError.

  4. If the length member of normalizedAlgorithm is zero or is greater than 128, then return an error named DataError.

  5. Let plaintext be the result of performing the CTR Decryption operation described in Section 6.5 of NIST SP 800-38A [SP800-38A] using AES as the block cipher, the contents of the counter member of normalizedAlgorithm as the initial value of the counter block, the length member of normalizedAlgorithm as the input parameter m to the standard counter block incrementing functon defined in Appendix B.1 of NIST SP 800-38A [SP800-38A] and ciphertext as the input ciphertext.

  6. Return plaintext.

Generate Key
  1. Let normalizedAlgorithm be the result of normalizing algorithm to AesKeyGenParams.

  2. If any of the members of AesKeyGenParams are not present in normalizedAlgorithm, then return an error named SyntaxError.

  3. If the length member of normalizedAlgorithm is not equal to one of 128, 192 or 256, then return an error named DataError.

  4. If usages contains any entry which is not one of "encrypt", "decrypt", "wrapKey" or "unwrapKey", then return an error named DataError.

  5. Generate an AES key of length equal to the length member of normalizedAlgorithm.

  6. If the key generation step fails, then return an error named OperationError.

  7. Let key be a new Key object representing the generated AES key.

  8. Let algorithm be a new AesKeyAlgorithm.

  9. Set the name attribute of algorithm to "AES-CTR".

  10. Set the length attribute of algorithm to equal the length member of normalizedAlgorithm.

  11. Set the algorithm attribute of key to algorithm.

  12. Set the extractable attribute of key to be extractable.

  13. Set the usages attribute of key to be usages.

  14. Return key.

Import Key
  1. If usages contains an entry which is not one of "encrypt", "decrypt", "wrapKey" or "unwrapKey", then return an error named DataError.

  2. If format is "raw":
    1. Let data be the octet string contained in keyData.

    2. If the length in bits of data is not 128, 192 or 256 then return an error named DataError.

    If format is "jwk":
    1. Let jwk be the result of running the parse a jwk algorithm over keyData.

    2. If the "kty" field of jwk is not "oct", then return an error named DataError.

    3. If jwk does not meet the requirements of Section 6.4 of JSON Web Algorithms, then return an error named DataError.

    4. Let data be the octet string obtained by decoding the "k" field of jwk.

    5. If data has length 128 bits:
      If the "alg" field of jwk is present, and is not "A128CTR", then return an error named DataError.
      If data has length 192 bits:
      If the "alg" field of jwk is present, and is not "A192CTR", then return an error named DataError.
      If data has length 256 bits:
      If the "alg" field of jwk is present, and is not "A256CTR", then return an error named DataError.
      Otherwise:
      Return an error named DataError.
    6. If the "use" field of jwk is present, and is not "enc", then return an error named DataError.

    7. If the "key_ops" field of jwk is present, and is invalid according to the requirements of JSON Web Key or does not contain all of the specified usages values, then return an error named DataError.

    8. If the "ext" field of jwk is present and has the value false and extractable is true, then return an error named DataError.

    Otherwise:
    Return an error named NotSupportedError.
  3. Let key be a new Key object representing an AES key with value data.

  4. Let algorithm be a new AesKeyAlgorithm.

  5. Set the name attribute of algorithm to "AES-CTR".

  6. Set the length attribute of algorithm to the length, in bits, of data.

  7. Set the algorithm attribute of key to algorithm.

  8. Set the extractable attribute of key to extractable.

  9. Set the usages attribute of key to the normalized value of usages.

  10. Return key.

Export Key
  1. If format is "raw":
    Let data be the raw octets of the key represented by key.
    If format is "jwk":
    1. Let jwk be a new internal object.

    2. Set the kty property of jwk to the string "oct".

    3. Set the k property of jwk to be a string containng the raw octets of the key represented by key, encoded according to Section 6.4 of JSON Web Algorithms.

    4. If the length attribute of key is 128:
      Set the alg property of jwk to the string "A128CTR".
      If the length attribute of key is 192:
      Set the alg property of jwk to the string "A192CTR".
      If the length attribute of key is 256:
      Set the alg property of jwk to the string "A256CTR".
    5. Set the key_ops property of jwk to equal the usages attribute of key.

    6. Set the ext property of jwk to equal the extractable attribute of key.

    7. Let stringifiedJwk be the result of encoding jwk into a string according to the grammer specified in Section 15.12 of ECMA262.

    8. Let data be the UTF-8 encoding of stringifiedJwk.

  2. Let keyData be a new ArrayBuffer containing data.

  3. Return data.

Get key length
  1. Let normalizedAlgorithm be the result of normalizing algorithm to AesDerivedKeyParams.

  2. If any of the members of AesDerivedKeyParams are not present in normalizedDerivedKeyAlgorithm, then return an error named SyntaxError.

  3. If the length member of normalizedDerivedKeyAlgorithm is not 128, 192 or 256, then return an error named DataError.

  4. Return the length member of normalizedDerivedKeyAlgorithm.

18.11. AES-CBC

18.11.1. Description

This section is non-normative.

The "AES-CBC" algorithm identifier is used to perform encryption and decryption using AES in Cipher Block Chaining mode, as described in NIST SP 800-38A [SP800-38A].

When operating in CBC mode, messages that are not exact multiples of the AES block size (16 bytes) can be padded under a variety of padding schemes. In the Web Crypto API, the only padding mode that is supported is that of PKCS#7, as described by Section 10.3, step 2, of RFC 2315 [RFC2315].

18.11.2. Registration

The recognized algorithm name for this algorithm is "AES-CBC".

Operation Parameters Result
encrypt AesCbcParams ArrayBuffer
decrypt AesCbcParams ArrayBuffer
generateKey AesKeyGenParams Key
importKey None Key
exportKey None ArrayBuffer
get key length AesDerivedKeyParams Integer

18.11.3. AesCbcParams dictionary

IDL

dictionary AesCbcParams : Algorithm {
  // The initialization vector. MUST be 16 bytes.
  CryptoOperationData iv;
};
            

18.11.4. Operations

Encrypt
  1. Let normalizedAlgorithm be the result of normalizing algorithm to AesCbcParams.

  2. If any of the members of AesCbcParams are not present in normalizedAlgorithm, then return an error named SyntaxError.

  3. If the iv member of normalizedAlgorithm does not have length 16 bytes, then return an error named DataError.

  4. Let padded-plaintext be the result of adding padding octets to ciphertext according to the procedure defined in Section 10.3 of RFC 2315 [RFC2315], step 2, with a value of k of 16.

  5. Let ciphertext be the result of performing the CBC Encryption operation described in Section 6.2 of NIST SP 800-38A [SP800-38A] using AES as the block cipher, the contents of the iv member of normalizedAlgorithm as the IV input parameter and padded-plaintext as the input plaintext.

  6. Return ciphertext.

Decrypt
  1. Let normalizedAlgorithm be the result of normalizing algorithm to AesCbcParams.

  2. If any of the members of AesCbcParams are not present in normalizedAlgorithm, then return an error named SyntaxError.

  3. If the iv member of normalizedAlgorithm does not have length 16 bytes, then return an error named DataError.

  4. Let padded-plaintext be the result of performing the CBC Decryption operation described in Section 6.2 of NIST SP 800-38A [SP800-38A] using AES as the block cipher, the contents of the iv member of normalizedAlgorithm as the IV input parameter and ciphertext as the input ciphertext.

  5. Let p be the value of the last octet of padded-plaintext.

  6. If p is zero or greater than 16, or if any of the last p octets of padded-plaintext have a value which is not p, then return an error named DataError.

  7. Let plaintext be the result of removing p octents from the end of padded-plaintext.

  8. Return plaintext.

Generate Key
  1. Let normalizedAlgorithm be the result of normalizing algorithm to AesKeyGenParams.

  2. If any of the members of AesKeyGenParams are not present in normalizedAlgorithm, then return an error named SyntaxError.

  3. If the length member of normalizedAlgorithm is not equal to one of 128, 192 or 256, then return an error named DataError.

  4. If usages contains any entry which is not one of "encrypt", "decrypt", "wrapKey" or "unwrapKey", then return an error named DataError.

  5. Generate an AES key of length equal to the length member of normalizedAlgorithm.

  6. If the key generation step fails, then return an error named OperationError.

  7. Let key be a new Key object representing the generated AES key.

  8. Let algorithm be a new AesKeyAlgorithm.

  9. Set the name attribute of algorithm to "AES-CBC".

  10. Set the length attribute of algorithm to equal the length member of normalizedAlgorithm.

  11. Set the algorithm attribute of key to algorithm.

  12. Set the extractable attribute of key to be extractable.

  13. Set the usages attribute of key to be usages.

  14. Return key.

Import Key
  1. If usages contains an entry which is not one of "encrypt", "decrypt", "wrapKey" or "unwrapKey", then return an error named DataError.

  2. If format is "raw":
    1. Let data be the octet string contained in keyData.

    2. If the length in bits of data is not 128, 192 or 256 then return an error named DataError.

    If format is "jwk":
    1. Let jwk be the result of running the parse a jwk algorithm over keyData.

    2. If the "kty" field of jwk is not to "oct", then return an error named DataError.

    3. If jwk does not meet the requirements of Section 6.4 of JSON Web Algorithms, then return an error named DataError.

    4. Let data be the octet string obtained by decoding the "k" field of jwk.

    5. If data has length 128 bits:
      If the "alg" field of jwk is present, and is not "A128CBC", then return an error named DataError.
      If data has length 192 bits:
      If the "alg" field of jwk is present, and is not "A192CBC", then return an error named DataError.
      If data has length 256 bits:
      If the "alg" field of jwk is present, and is not "A256CBC", then return an error named DataError.
      Otherwise:
      Return an error named DataError.
    6. If the "use" field of jwk is present, and is not "enc", then return an error named DataError.

    7. If the "key_ops" field of jwk is present, and is invalid according to the requirements of JSON Web Key or does not contain all of the specified usages values, then return an error named DataError.

    8. If the "ext" field of jwk is present and has the value false and extractable is true, then return an error named DataError.

    Otherwise:
    Return an error named NotSupportedError
  3. Let key be a new Key object representing an AES key with value data.

  4. Let algorithm be a new AesKeyAlgorithm.

  5. Set the name attribute of algorithm to "AES-CBC".

  6. Set the length attribute of algorithm to the length, in bits, of data.

  7. Set the algorithm attribute of key to algorithm.

  8. Set the extractable attribute of key to extractable.

  9. Set the usages attribute of key to the normalized value of usages.

  10. Return key.

Export Key
  1. If format is "raw":
    Let data be the raw octets of the key represented by key.
    If format is "jwk":
    1. Let jwk be a new internal object.

    2. Set the kty property of jwk to the string "oct".

    3. Set the k property of jwk to be a string containng the raw octets of the key represented by key, encoded according to Section 6.4 of JSON Web Algorithms.

    4. If the length attribute of key is 128:
      Set the alg property of jwk to the string "A128CBC".
      If the length attribute of key is 192:
      Set the alg property of jwk to the string "A192CBC".
      If the length attribute of key is 256:
      Set the alg property of jwk to the string "A256CBC".
    5. Set the key_ops property of jwk to equal the usages attribute of key.

    6. Set the ext property of jwk to equal the extractable attribute of key.

    7. Let stringifiedJwk be the result of encoding jwk into a string according to the grammer specified in Section 15.12 of ECMA262.

    8. Let data be the UTF-8 encoding of stringifiedJwk.

  2. Let keyData be a new ArrayBuffer containing data.

  3. Return data.

Get key length
  1. Let normalizedAlgorithm be the result of normalizing algorithm to AesDerivedKeyParams.

  2. If any of the members of AesDerivedKeyParams are not present in normalizedDerivedKeyAlgorithm, then return an error named SyntaxError.

  3. If the length member of normalizedDerivedKeyAlgorithm is not 128, 192 or 256, then return an error named DataError.

  4. Return the length member of normalizedDerivedKeyAlgorithm.

18.12. AES-CMAC

18.12.1. Description

This section is non-normative.

The "AES-CMAC" algorithm identifier is used to perform message authentication using AES with a cipher-based MAC, as described in NIST SP 800-38B [SP800-38B].

18.12.2. Registration

The recognized algorithm name for this algorithm is "AES-CMAC".

Operation Parameters Result
sign AesCmacParams ArrayBuffer
verify AesCmacParams boolean
generateKey AesKeyGenParams Key
importKey None Key
exportKey None ArrayBuffer
get key length AesDerivedKeyParams Integer

18.12.3. AesCmacParams dictionary

IDL

dictionary AesCmacParams : Algorithm {
  // The length, in bits, of the MAC.
  [EnforceRange] unsigned short length;
};
            

18.12.4. Operations

Sign
  1. Let length equal the length member of normalizedAlgorithm, if present, and 128 otherwise.

  2. If length is zero or greater than 128, then return an error named DataError.

  3. Let mac be the result of performing the MAC Generation operation described in Section 6.2 of NIST SP 800-38B [SP800-38B] using AES as the block cipher, length as the value of the MAC length parameter, Tlen, and message as the message, M.

  4. Return mac.

Verify
  1. Let normalizedAlgorithm be the result of normalizing algorithm to AesCmacParams.

  2. Let length equal the length member of normalizedAlgorithm, if present, and 128 otherwise.

  3. If length is zero or greater than 128, then return an error named DataError.

  4. Let ouput be the result of performing the MAC Verification operation described in Section 6.3 of NIST SP 800-38B [SP800-38B] using AES as the block cipher, length as the value of the MAC length parameter, Tlen, message as the message, M and signature as the received MAC, T'.

  5. Return true if output is VALID and false otherwise.

Generate Key
  1. Let normalizedAlgorithm be the result of normalizing algorithm to AesKeyGenParams.

  2. If any of the members of AesKeyGenParams are not present in normalizedAlgorithm, then return an error named SyntaxError.

  3. If the length member of normalizedAlgorithm is not equal to one of 128, 192 or 256, then return an error named DataError.

  4. If usages contains any entry which is not "sign" or "verify", then return an error named DataError.

  5. Generate an AES key of length equal to the length member of normalizedAlgorithm.

  6. If the key generation step fails, then return an error named OperationError.

  7. Let key be a new Key object representing the generated AES key.

  8. Let algorithm be a new AesKeyAlgorithm.

  9. Set the name attribute of algorithm to "AES-CMAC".

  10. Set the length attribute of algorithm to equal the length member of normalizedAlgorithm.

  11. Set the algorithm attribute of key to algorithm.

  12. Set the extractable attribute of key to be extractable.

  13. Set the usages attribute of key to be usages.

  14. Return key.

Import Key
  1. If usages contains an entry which is not "sign" or "verify", then return an error named DataError.

  2. If format is "raw":
    1. Let data be the octet string contained in keyData.

    2. If the length in bits of data is not 128, 192 or 256 then return an error named DataError.

    If format is "jwk":
    1. Let jwk be the result of running the parse a jwk algorithm over keyData.

    2. If the "kty" field of jwk is not to "oct", then return an error named DataError.

    3. If jwk does not meet the requirements of Section 6.4 of JSON Web Algorithms, then return an error named DataError.

    4. Let data be the octet string obtained by decoding the "k" field of jwk.

    5. If data has length 128 bits:
      If the "alg" field of jwk is present, and is not "A128CMAC", then return an error named DataError.
      If data has length 192 bits:
      If the "alg" field of jwk is present, and is not "A192CMAC", then return an error named DataError.
      If data has length 256 bits:
      If the "alg" field of jwk is present, and is not "A256CMAC", then return an error named DataError.
      Otherwise:
      Return an error named DataError.
    6. If the "use" field of jwk is present, and is not "enc", then return an error named DataError.

    7. If the "key_ops" field of jwk is present, and is invalid according to the requirements of JSON Web Key or does not contain all of the specified usages values, then return an error named DataError.

    8. If the "ext" field of jwk is present and has the value false and extractable is true, then return an error named DataError.

    Otherwise:
    Return an error named NotSupportedError.
  3. Let key be a new Key object representing an AES key with value data.

  4. Let algorithm be a new AesKeyAlgorithm.

  5. Set the name attribute of algorithm to "AES-CMAC".

  6. Set the length attribute of algorithm to the length, in bits, of data.

  7. Set the algorithm attribute of key to algorithm.

  8. Set the extractable attribute of key to extractable.

  9. Set the usages attribute of key to the normalized value of usages.

  10. Return key.

Export Key
  1. If format is "raw":
    Let data be the raw octets of the key represented by key.
    If format is "jwk":
    1. Let jwk be a new internal object.

    2. Set the kty property of jwk to the string "oct".

    3. Set the k property of jwk to be a string containng the raw octets of the key represented by key, encoded according to Section 6.4 of JSON Web Algorithms.

    4. If the length attribute of key is 128:
      Set the alg property of jwk to the string "A128CMAC".
      If the length attribute of key is 192:
      Set the alg property of jwk to the string "A192CMAC".
      If the length attribute of key is 256:
      Set the alg property of jwk to the string "A256CMAC".
    5. Set the key_ops property of jwk to equal the usages attribute of key.

    6. Set the ext property of jwk to equal the extractable attribute of key.

    7. Let stringifiedJwk be the result of encoding jwk into a string according to the grammer specified in Section 15.12 of ECMA262.

    8. Let data be the UTF-8 encoding of stringifiedJwk.

  2. Return a new ArrayBuffer containing data.

Get key length
  1. Let normalizedAlgorithm be the result of normalizing algorithm to AesDerivedKeyParams.

  2. If any of the members of AesDerivedKeyParams are not present in normalizedDerivedKeyAlgorithm, then return an error named SyntaxError.

  3. If the length member of normalizedDerivedKeyAlgorithm is not 128, 192 or 256, then return an error named DataError.

  4. Return the length member of normalizedDerivedKeyAlgorithm.

18.13. AES-GCM

18.13.1. Description

This section is non-normative.

The "AES-GCM" algorithm identifier is used to perform authenticated encryption and decryption using AES in Galois/Counter Mode mode, as described in NIST SP 800-38D [SP800-38D].

18.13.2. Registration

The recognized algorithm name for this algorithm is "AES-GCM".

Operation Parameters Result
encrypt AesGcmParams ArrayBuffer
decrypt AesGcmParams ArrayBuffer
generateKey AesKeyGenParams Key
importKey None Key
exportKey None ArrayBuffer
get key length AesDerivedKeyParams Integer

18.13.3. AesGcmParams dictionary

IDL

dictionary AesGcmParams : Algorithm {
  // The initialization vector to use. May be up to 2^64-1 bytes long.
  CryptoOperationData iv;
  // The additional authentication data to include.
  CryptoOperationData? additionalData;
  // The desired length of the authentication tag. May be 0 - 128.
  [EnforceRange] octet? tagLength;
};
            

18.13.4. Operations

Encrypt
  1. Let normalizedAlgorithm be the result of normalizing algorithm to AesGcmParams.

  2. If the iv member of AesGcmParams is not present in normalizedAlgorithm, then return an error named SyntaxError.

  3. If plaintext has a length greater than 2^39 - 256 bytes, then return an error named DataError.

  4. If the iv member of normalizedAlgorithm has a length greater than 2^64 - 1 bytes, then return an error named DataError.

  5. If the additionalData member of normalizedAlgorithm is present, is not null and has a length greater than 2^64 - 1 bytes, then return an error named DataError.

  6. If the tagLength member of normalizedAlgorithm is not present or is null:
    Let tagLength be 128.
    If the tagLength member of normalizedAlgorithm is one of 32, 64, 96, 104, 112, 120 or 128:
    Let tagLength be equal to the tagLength member of normalizedAlgorithm
    Otherwise:
    Return an error named DataError.
  7. Let additionalData be the contents of the additionalData member of normalizedAlgorithm if present and not null and the empty octet string otherwise.

  8. Let C and T be the outputs that result from performing the Authenticated Encryption Function described in Section 7.1 of NIST SP 800-38D [SP800-38D] using AES as the block cipher, the contents of the iv member of normalizedAlgorithm as the IV input parameter, additionalData as the A input parameter, tagLength as the t pre-requisite and plaintext as the input plaintext.

  9. Return a new ArrayBuffer containing C | T where '|' denotes concatenation.

Decrypt
  1. Let normalizedAlgorithm be the result of normalizing algorithm to AesGcmParams.

  2. If the iv member of AesGcmParams is not present in normalizedAlgorithm, then return an error named SyntaxError.

  3. If the tagLength member of normalizedAlgorithm is not present or null:
    Let tagLength be 128.
    If the tagLength member of normalizedAlgorithm is one of 32, 64, 96, 104, 112, 120 or 128:
    Let tagLength be equal to the tagLength member of normalizedAlgorithm
    Otherwise:
    Return an error named DataError.
  4. If plaintext has a length less than tagLength bits, then return an error named DataError.

  5. If the iv member of normalizedAlgorithm has a length greater than 2^64 - 1 bytes, then return an error named DataError.

  6. If the additionalData member of normalizedAlgorithm is present, is not null and has a length greater than 2^64 - 1 bytes, then return an error named DataError.

  7. Let tag be the last tagLength bits of ciphertext.

  8. Let actualCiphertext be the result of removing the last tagLength bits from ciphertext.

  9. Let additionalData be the contents of the additionalData member of normalizedAlgorithm if present and not null and the empty octet string otherwise.

  10. Perform the Authenticated Decryption Function described in Section 7.2 of NIST SP 800-38D [SP800-38D] using AES as the block cipher, the contents of the iv member of normalizedAlgorithm as the IV input parameter, additionalData as the A input parameter, tagLength as the t pre-requisite, actualCiphertext as the input ciphertext, C and tag as the authentation tag, T.

    If the result of the algorithm is the indication of inauthenticity, "FAIL":
    Return an error named OperationError
    Otherwise:
    Let plaintext be the output P of the Authenticated Decryption Function.
  11. Return a new ArrayBuffer containing plaintext.

Generate Key
  1. Let normalizedAlgorithm be the result of normalizing algorithm to AesKeyGenParams.

  2. If any of the members of AesKeyGenParams are not present in normalizedAlgorithm, then return an error named SyntaxError.

  3. If the length member of normalizedAlgorithm is not equal to one of 128, 192 or 256, then return an error named DataError.

  4. If usages contains any entry which is not one of "encrypt", "decrypt", "wrapKey" or "unwrapKey", then return an error named DataError.

  5. Generate an AES key of length equal to the length member of normalizedAlgorithm.

  6. If the key generation step fails, then return an error named OperationError.

  7. Let key be a new Key object representing the generated AES key.

  8. Let algorithm be a new AesKeyAlgorithm.

  9. Set the name attribute of algorithm to "AES-GCM".

  10. Set the length attribute of algorithm to equal the length member of normalizedAlgorithm.

  11. Set the algorithm attribute of key to algorithm.

  12. Set the extractable attribute of key to be extractable.

  13. Set the usages attribute of key to be usages.

  14. Return key.

Import Key
  1. If usages contains an entry which is not one of "encrypt", "decrypt", "wrapKey" or "unwrapKey", then return an error named DataError.

  2. If format is "raw":
    1. Let data be the octet string contained in keyData.

    2. If the length in bits of data is not 128, 192 or 256 then return an error named DataError.

    If format is "jwk":
    1. Let jwk be the result of running the parse a jwk algorithm over keyData.

    2. If the "kty" field of jwk is not "oct", then return an error named DataError.

    3. If jwk does not meet the requirements of Section 6.4 of JSON Web Algorithms, then return an error named DataError.

    4. Let data be the octet string obtained by decoding the "k" field of jwk.

    5. If data has length 128 bits:
      If the "alg" field of jwk is present, and is not "A128GCM", then return an error named DataError.
      If data has length 192 bits:
      If the "alg" field of jwk is present, and is not "A192GCM", then return an error named DataError.
      If data has length 256 bits:
      If the "alg" field of jwk is present, and is not "A256GCM", then return an error named DataError.
      Otherwise:
      Return an error named DataError.
    6. If the "use" field of jwk is present, and is not "enc", then return an error named DataError.

    7. If the "key_ops" field of jwk is present, and is invalid according to the requirements of JSON Web Key or does not contain all of the specified usages values, then return an error named DataError.

    8. If the "ext" field of jwk is present and has the value false and extractable is true, then return an error named DataError.

    Otherwise:
    Return an error named NotSupportedError.
  3. Let key be a new Key object representing an AES key with value data.

  4. Let algorithm be a new AesKeyAlgorithm.

  5. Set the name attribute of algorithm to "AES-GCM".

  6. Set the length attribute of algorithm to the length, in bits, of data.

  7. Set the algorithm attribute of key to algorithm.

  8. Set the extractable attribute of key to extractable.

  9. Set the usages attribute of key to the normalized value of usages.

  10. Return key.

Export Key
  1. If format is "raw":
    Let data be the raw octets of the key represented by key.
    If format is "jwk":
    1. Let jwk be a new internal object.

    2. Set the kty property of jwk to the string "oct".

    3. Set the k property of jwk to be a string containng the raw octets of the key represented by key, encoded according to Section 6.4 of JSON Web Algorithms.

    4. If the length attribute of key is 128:
      Set the alg property of jwk to the string "A128GCM".
      If the length attribute of key is 192:
      Set the alg property of jwk to the string "A192GCM".
      If the length attribute of key is 256:
      Set the alg property of jwk to the string "A256GCM".
    5. Set the key_ops property of jwk to equal the usages attribute of key.

    6. Set the ext property of jwk to equal the extractable attribute of key.

    7. Let stringifiedJwk be the result of encoding jwk into a string according to the grammer specified in Section 15.12 of ECMA262.

    8. Let data be the UTF-8 encoding of stringifiedJwk.

    Otherwise:
    Return an error named DataError.
  2. Return a new ArrayBuffer containing data.

Get key length
  1. Let normalizedAlgorithm be the result of normalizing algorithm to AesDerivedKeyParams.

  2. If any of the members of AesDerivedKeyParams are not present in normalizedDerivedKeyAlgorithm, then return an error named SyntaxError.

  3. If the length member of normalizedDerivedKeyAlgorithm is not 128, 192 or 256, then return an error named DataError.

  4. Return the length member of normalizedDerivedKeyAlgorithm.

18.14. AES-CFB

18.14.1. Description

This section is non-normative.

The "AES-CFB-8" algorithm identifier is used to perform encryption and decryption using AES in Cipher Feedback mode, specifically CFB-8, as described in Section 6.3 of NIST SP 800-38A [SP800-38A].

18.14.2. Registration

The recognized algorithm name for this algorithm is "AES-CFB-8".

Operation Parameters Result
encrypt AesCfbParams ArrayBuffer
decrypt AesCfbParams ArrayBuffer
generateKey AesKeyGenParams Key
importKey None Key
exportKey None ArrayBuffer
get key length AesDerivedKeyParams Integer

18.14.3. AesCfbParams dictionary

IDL

dictionary AesCfbParams : Algorithm {
  // The initialization vector. MUST be 16 bytes.
  CryptoOperationData iv;
};
            

18.14.4. Operations

Encrypt
  1. Let normalizedAlgorithm be the result of normalizing algorithm to AesCfbParams.

  2. If any of the members of AesCfbParams are not present in normalizedAlgorithm, then return an error named SyntaxError.

  3. If the iv member of normalizedAlgorithm does not have length 16 bytes, then return an error named DataError.

  4. Let ciphertext be the result of performing the CFB Encryption operation described in Section 6.3 of NIST SP 800-38A [SP800-38A] using AES as the block cipher, the contents of the iv member of normalizedAlgorithm as the IV input parameter, the value 8 as the input parameter s and plaintext as the input plaintext.

  5. Return ciphertext.

Decrypt
  1. Let normalizedAlgorithm be the result of normalizing algorithm to AesCfbParams.

  2. If any of the members of AesCfbParams are not present in normalizedAlgorithm, then return an error named SyntaxError.

  3. If the iv member of normalizedAlgorithm does not have length 16 bytes, then return an error named DataError.

  4. Let plaintext be the result of performing the CFB Decryption operation described in Section 6.3 of NIST SP 800-38A [SP800-38A] using AES as the block cipher, the contents of the iv member of normalizedAlgorithm as the IV input parameter, the the value 8 as the input parameter s and ciphertext as the input ciphertext.

  5. Return plaintext.

Generate Key
  1. Let normalizedAlgorithm be the result of normalizing algorithm to AesKeyGenParams.

  2. If any of the members of AesKeyGenParams are not present in normalizedAlgorithm, then return an error named SyntaxError.

  3. If the length member of normalizedAlgorithm is not equal to one of 128, 192 or 256, then return an error named DataError.

  4. If usages contains any entry which is not one of "encrypt", "decrypt", "wrapKey" or "unwrapKey", then return an error named DataError.

  5. Generate an AES key of length equal to the length member of normalizedAlgorithm.

  6. If the key generation step fails, then return an error named OperationError.

  7. Let key be a new Key object representing the generated AES key.

  8. Let algorithm be a new AesKeyAlgorithm.

  9. Set the name attribute of algorithm to "AES-CFB-8".

  10. Set the length attribute of algorithm to equal the length member of normalizedAlgorithm.

  11. Set the algorithm attribute of key to algorithm.

  12. Set the extractable attribute of key to be extractable.

  13. Set the usages attribute of key to be usages.

  14. Return key.

Import Key
  1. If usages contains an entry which is not one of "encrypt", "decrypt", "wrapKey" or "unwrapKey", then return an error named DataError.

  2. If format is "raw":
    1. Let data be the octet string contained in keyData.

    2. If the length in bits of data is not 128, 192 or 256 then return an error named DataError.

    If format is "jwk":
    1. Let jwk be the result of running the parse a jwk algorithm over keyData.

    2. If the "kty" field of jwk is not "oct", then return an error named DataError.

    3. If jwk does not meet the requirements of Section 6.4 of JSON Web Algorithms, then return an error named DataError.

    4. Let data be the octet string obtained by decoding the "k" field of jwk.

    5. If data has length 128 bits:
      If the "alg" field of jwk is present, and is not "A128CFB8", then return an error named DataError.
      If data has length 192 bits:
      If the "alg" field of jwk is present, and is not "A192CFB8", then return an error named DataError.
      If data has length 256 bits:
      If the "alg" field of jwk is present, and is not "A256CFB8", then return an error named DataError.
      Otherwise:
      Return an error named DataError.
    6. If the "use" field of jwk is present, and is not "enc", then return an error named DataError.

    7. If the "key_ops" field of jwk is present, and is invalid according to the requirements of JSON Web Key or does not contain all of the specified usages values, then return an error named DataError.

    8. If the "ext" field of jwk is present and has the value false and extractable is true, then return an error named DataError.

    Otherwise:
    Return an error named NotSupportedError.
  3. Let key be a new Key object representing an AES key with value data.

  4. Let algorithm be a new AesKeyAlgorithm.

  5. Set the name attribute of algorithm to "AES-CFB-8".

  6. Set the length attribute of algorithm to the length, in bits, of data.

  7. Set the algorithm attribute of key to algorithm.

  8. Set the extractable attribute of key to extractable.

  9. Set the usages attribute of key to the normalized value of usages.

  10. Return key.

Export Key
  1. If format is "raw":
    Let data be the raw octets of the key represented by key.
    If format is "jwk":
    1. Let jwk be a new internal object.

    2. Set the kty property of jwk to the string "oct".

    3. Set the k property of jwk to be a string containng the raw octets of the key represented by key, encoded according to Section 6.4 of JSON Web Algorithms.

    4. If the length attribute of key is 128:
      Set the alg property of jwk to the string "A128CFB8".
      If the length attribute of key is 192:
      Set the alg property of jwk to the string "A192CFB8".
      If the length attribute of key is 256:
      Set the alg property of jwk to the string "A256CFB8".
    5. Set the key_ops property of jwk to equal the usages attribute of key.

    6. Set the ext property of jwk to equal the extractable attribute of key.

    7. Let stringifiedJwk be the result of encoding jwk into a string according to the grammer specified in Section 15.12 of ECMA262.

    8. Let data be the UTF-8 encoding of stringifiedJwk.

  2. Let keyData be a new ArrayBuffer containing data.

  3. Return data.

Get key length
  1. Let normalizedAlgorithm be the result of normalizing algorithm to AesDerivedKeyParams.

  2. If any of the members of AesDerivedKeyParams are not present in normalizedDerivedKeyAlgorithm, then return an error named SyntaxError.

  3. If the length property of normalizedDerivedKeyAlgorithm is not 128, 192 or 256, then return an error named DataError.

  4. Return the length property of normalizedDerivedKeyAlgorithm.

18.15. AES-KW

18.15.1. Description

This section is non-normative.

The "AES-KW" algorithm identifier is used to perform key wrapping using AES, as described in [RFC3394].

18.15.2. Registration

The recognized algorithm name for this algorithm is "AES-KW".

Operation Parameters Result
wrapKey None ArrayBuffer
unwrapKey None ArrayBuffer
generateKey AesKeyGenParams Key
importKey None Key
exportKey None ArrayBuffer
get key length AesDerivedKeyParams Integer

18.15.3. Operations

Wrap Key
  1. If plaintext is not a multiple of 64 bits in length, then return an error named DataError.

  2. Let ciphertext be the result of performing the Key Wrap operation described in Section 2.2.1 of [RFC3394] with plaintext as the plaintext to be wrapped and using the default Initial Value defined in Section 2.2.3.1 of the same document.

  3. Return ciphertext.

Unwrap Key
  1. Let plaintext be the result of performing the Key Unwrap operation described in Section 2.2.2 of [RFC3394] with ciphertext as the input ciphertext and using the default Initial Value defined in Section 2.2.3.1 of the same document.

  2. If the Key Unwrap operation returns an error, then return an error named OperationError.

  3. Return plaintext.

Generate Key
  1. Let normalizedAlgorithm be the result of normalizing algorithm to AesKeyGenParams.

  2. If any of the members of AesKeyGenParams are not present in normalizedAlgorithm, then return an error named SyntaxError.

  3. If the length property of normalizedAlgorithm is not equal to one of 128, 192 or 256, then return an error named DataError.

  4. If usages contains any entry which is not one of "wrapKey" or "unwrapKey", then return an error named DataError.

  5. If the key generation step fails, then return an error named OperationError.

  6. Let key be a new Key object representing the generated AES key.

  7. Let algorithm be a new AesKeyAlgorithm.

  8. Set the name attribute of algorithm to "AES-KW".

  9. Set the length attribute of algorithm to equal the length property of normalizedAlgorithm.

  10. Set the algorithm attribute of key to algorithm.

  11. Set the extractable attribute of key to be extractable.

  12. Set the usages attribute of key to be usages.

  13. Return key.

Import Key
  1. If usages contains an entry which is not one of "wrapKey" or "unwrapKey", then return an error named DataError.

  2. If format is "raw":
    1. Let data be the octet string contained in keyData.

    2. If the length in bits of data is not 128, 192 or 256 then return an error named DataError.

    If format is "jwk":
    1. Let jwk be the result of running the parse a jwk algorithm over keyData.

    2. If the "kty" field of jwk is not "oct", then return an error named DataError.

    3. If jwk does not meet the requirements of Section 6.4 of JSON Web Algorithms, then return an error named DataError.

    4. Let data be the octet string obtained by decoding the "k" field of jwk.

    5. If data has length 128 bits:
      If the "alg" field of jwk is present, and is not "A128KW", then return an error named DataError.
      If data has length 192 bits:
      If the "alg" field of jwk is present, and is not "A192KW", then return an error named DataError.
      If data has length 256 bits:
      If the "alg" field of jwk is present, and is not "A256KW", then return an error named DataError.
      Otherwise:
      Return an error named DataError.
    6. If the "use" field of jwk is present, and is not "enc", then return an error named DataError.

    7. If the "key_ops" field of jwk is present, and is invalid according to the requirements of JSON Web Key or does not contain all of the specified usages values, then return an error named DataError.

    8. If the "ext" field of jwk is present and has the value false and extractable is true, then return an error named DataError.

    Otherwise:
    Return an error named NotSupportedError.
  3. Let key be a new Key object representing an AES key with value data.

  4. Let algorithm be a new AesKeyAlgorithm.

  5. Set the name attribute of algorithm to "AES-KW".

  6. Set the length attribute of algorithm to the length, in bits, of data.

  7. Set the algorithm attribute of key to algorithm.

  8. Set the extractable attribute of key to extractable.

  9. Set the usages attribute of key to the normalized value of usages.

  10. Return key.

Export Key
  1. If format is "raw":
    Let data be the raw octets of the key represented by key.
    If format is "jwk":
    1. Let jwk be a new internal object.

    2. Set the kty property of jwk to the string "oct".

    3. Set the k property of jwk to be a string containng the raw octets of the key represented by key, encoded according to Section 6.4 of JSON Web Algorithms.

    4. If the length attribute of key is 128:
      Set the alg property of jwk to the string "A128KW".
      If the length attribute of key is 192:
      Set the alg property of jwk to the string "A192KW".
      If the length attribute of key is 256:
      Set the alg property of jwk to the string "A256KW".
    5. Set the key_ops property of jwk to equal the usages attribute of key.

    6. Set the ext property of jwk to equal the extractable attribute of key.

    7. Let stringifiedJwk be the result of encoding jwk into a string according to the grammer specified in Section 15.12 of ECMA262.

    8. Let data be the UTF-8 encoding of stringifiedJwk.

  2. Return a new ArrayBuffer containing data.

Get key length
  1. Let normalizedAlgorithm be the result of normalizing algorithm to AesDerivedKeyParams.

  2. If any of the members of AesDerivedKeyParams are not present in normalizedDerivedKeyAlgorithm, then return an error named SyntaxError.

  3. If the length member of normalizedDerivedKeyAlgorithm is not 128, 192 or 256, then return an error named DataError.

  4. Return the length member of normalizedDerivedKeyAlgorithm.

18.16. HMAC

18.16.1. Description

This section is non-normative.

The HMAC algorithm calculates and verifies hash-based message authentication codes according to [FIPS PUB 198-1].

18.16.2. Registration

The recognized algorithm name for this algorithm is "HMAC".

Operation Parameters Result
sign None ArrayBuffer
verify None boolean
generateKey HmacKeyGenParams Key
importKey HmacImportParams Key
exportKey None ArrayBuffer
get key length HmacDerivedKeyParams Integer

18.16.3. HmacImportParams dictionary

IDL

dictionary HmacImportParams : Algorithm {
  // The inner hash function to use.
  AlgorithmIdentifier hash;
};
            

18.16.4. HmacKeyAlgorithm interface

IDL

interface HmacKeyAlgorithm : KeyAlgorithm {
  // The inner hash function to use.
  readonly attribute KeyAlgorithm hash;
};
            

18.16.5. HmacKeyGenParams dictionary

IDL

dictionary HmacKeyGenParams : Algorithm {
  // The inner hash function to use.
  AlgorithmIdentifier hash;
  // The length (in bits) of the key to generate. If unspecified, the
  // recommended length will be used, which is the size of the associated hash function's block
  // size.
  [EnforceRange] unsigned long length;
};
            

18.16.6. HmacDerivedKeyParams dictionary

IDL

dictionary HmacDerivedKeyParams : HmacImportParams {
  // The length (in bits) of the key to generate. If unspecified, the
  // recommended length will be used, which is the size of the associated hash function's block
  // size.
  [EnforceRange] unsigned long length;
};
            

18.16.7. Operations

Sign
  1. Let mac be the result of performing the MAC Generation operation described in Section 4 of [FIPS PUB 198-1] using the key represented by key, the hash function identified by the hash attribute of the algorithm attribute of key and message as the input data text.

  2. Return mac.

Verify
  1. Let mac be the result of performing the MAC Generation operation described in Section 4 of [FIPS PUB 198-1] using the key represented by key, the hash function identified by the hash attribute of the algorithm attribute of key and message as the input data text.

  2. Return true if mac is equal to signature and false otherwise.

Generate Key
  1. Let normalizedAlgorithm be the result of normalizing algorithm to HmacKeyGenParams.

  2. If the hash member is not present in normalizedAlgorithm, then return an error named SyntaxError.

  3. If the length member of normalizedAlgorithm is not present:
    Let length be the block size in bits of the hash function identified by the hash member of normalizedAlgorithm.
    Otherwise, if the length member of normalizedAlgorithm is non-zero:
    Let length be equal to the length member of normalizedAlgorithm.
    Otherwise:
    Return an error named DataError.
  4. If usages contains any entry which is not "sign" or "verify", then return an error named DataError.

  5. Generate a key of length length bits.

  6. If the key generation step fails, then return an error named OperationError.

  7. Let key be a new Key object representing the generated key.

  8. Let algorithm be a new HmacKeyAlgorithm.

  9. Set the name attribute of algorithm to "HMAC".

  10. Let hash be a new KeyAlgorithm.

  11. Set the name attribute of hash to equal the name member of the hash member of normalizedAlgorithm.

  12. Set the hash attribute of algorithm to hash.

  13. Set the algorithm attribute of key to algorithm.

  14. Set the extractable attribute of key to be extractable.

  15. Set the usages attribute of key to be usages.

  16. Return key.

Import Key
  1. If usages contains an entry which is not "sign" or "verify", then return an error named DataError.

  2. Let hash be a new KeyAlgorithm.

  3. If format is "raw":
    1. Let data be the octet string contained in keyData.

    2. If the length in bits of data is zero then return an error named DataError.

    3. If the hash member of normalizedAlgorithm is present and has a name member:
      Set the name attribute of hash to equal the name member of the hash member of normalizedAlgorithm.
      Otherwise:
      Return an error named SyntaxError.
    If format is "jwk":
    1. Let jwk be the result of running the parse a jwk algorithm over keyData.

    2. If the "kty" field of jwk is not "oct", then return an error named DataError.

    3. If jwk does not meet the requirements of Section 6.4 of JSON Web Algorithms, then return an error named DataError.

    4. Let data be the octet string obtained by decoding the "k" field of jwk.

    5. If the hash member of normalizedAlgorithm is present and has a name member:
      1. Set the name attribute of hash to equal the name member of the hash member of normalizedAlgorithm.

      2. If the name attribute of hash is "SHA-1":
        If the "alg" field of jwk is present and is not "HS1", then return an error named DataError.
        If the name attribute of hash is "SHA-256":
        If the "alg" field of jwk is present and is not "HS256", then return an error named DataError.
        If the name attribute of hash is "SHA-384":
        If the "alg" field of jwk is present and is not "HS384", then return an error named DataError.
        If the name attribute of hash is "SHA-512":
        If the "alg" field of jwk is present and is not "HS512", then return an error named DataError.
        Otherwise:
        Return an error named DataError.
      Otherwise:
      1. If the alg field of jwk is not present, then return an error named DataError.

      2. If the "alg" field of jwk is "HS1":
        Set the name attribute of hash to "SHA-1".
        If the "alg" field of jwk is to "HS256":
        Set the name attribute of hash to "SHA-256".
        If the "alg" field of jwk is "HS384":
        Set the name attribute of hash to "SHA-384".
        If the "alg" field of jwk is "HS512":
        Set the name attribute of hash to "SHA-512".
        Otherwise:
        Return an error named DataError.
    6. If the "use" field of jwk is present, and is not "sign", then return an error named DataError.

    7. If the "key_ops" field of jwk is present, and is invalid according to the requirements of JSON Web Key or does not contain all of the specified usages values, then return an error named DataError.

    8. If the "ext" field of jwk is present and has the value false and extractable is true, then return an error named DataError.

    Otherwise:
    Return an error named NotSupportedError.
  4. Let key be a new Key object representing an HMAC key with value data.

  5. Let algorithm be a new HmacKeyAlgorithm.

  6. Set the name attribute of algorithm to "HMAC".

  7. Set the hash attribute of algorithm to hash.

  8. Set the algorithm attribute of key to algorithm.

  9. Set the extractable attribute of key to extractable.

  10. Set the usages attribute of key to the normalized value of usages.

  11. Return key.

Export Key
  1. If format is "raw":
    Let data be the raw octets of the key represented by key.
    If format is "jwk":
    1. Let jwk be a new internal object.

    2. Set the kty property of jwk to the string "oct".

    3. Set the k property of jwk to be a string containng the raw octets of the key represented by key, encoded according to Section 6.4 of JSON Web Algorithms.

    4. Let algorithm be the algorithm attribute of key.

    5. Let hash be the hash attribute of algorithm.

    6. If the name attribute of hash is "SHA-1":
      Set the alg property of jwk to the string "HS1".
      If the name attribute of hash is "SHA-256":
      Set the alg property of jwk to the string "HS256".
      If the name attribute of hash is "SHA-384":
      Set the alg property of jwk to the string "HS384".
      If the name attribute of hash is "SHA-512":
      Set the alg property of jwk to the string "HS512".
    7. Set the key_ops property of jwk to equal the usages attribute of key.

    8. Set the ext property of jwk to equal the extractable attribute of key.

    9. Let stringifiedJwk be the result of encoding jwk into a string according to the grammer specified in Section 15.12 of ECMA262.

    10. Let data be the UTF-8 encoding of stringifiedJwk.

  2. Return a new ArrayBuffer containing data.

Get key length
  1. Let normalizedAlgorithm be the result of normalizing algorithm to HmacImportParams.

  2. If the hash member is not present in normalizedDerivedKeyAlgorithm, then return an error named SyntaxError.

  3. If the length member of normalizedDerivedKeyAlgorithm is not present:
    Let length be the block size in bytes of the hash function identified by the hash member of normalizedDerivedKeyAlgorithm.
    Otherwise, if the length member of normalizedDerivedKeyAlgorithm is non-zero:
    Let length be equal to the length member of normalizedDerivedKeyAlgorithm.
    Otherwise:
    Return an error named DataError.
  4. Return length.

18.17. Diffie-Hellman

18.17.1. Description

This section is non-normative.

This describes using Diffie-Hellman for key generation and key agreement, as specified by PKCS #3.

18.17.2. Registration

The recognized algorithm name for this algorithm is "DH".

Operation Parameters Result
generateKey DhKeyGenParams KeyPair
deriveBits DhKeyDeriveParams Octet string
importKey DhImportKeyParams Key
exportKey None ArrayBuffer

18.17.3. DhKeyGenParams dictionary

IDL

dictionary DhKeyGenParams : Algorithm {
  // The prime p.
  BigInteger prime;
  // The base g.
  BigInteger generator;
};
            

18.17.4. DhKeyAlgorithm interface

IDL

[NoInterfaceObject]
interface DhKeyAlgorithm : KeyAlgorithm {
  // The prime p.
  readonly attribute BigInteger prime;
  // The base g.
  readonly attribute BigInteger generator;
};
            

18.17.5. DhKeyDeriveParams dictionary

IDL

dictionary DhKeyDeriveParams : Algorithm {
  // The peer's public value.
  Key public;
};
            

18.17.6. DhImportKeyParams dictionary

IDL

dictionary DhImportKeyParams : Algorithm {
  // The prime p.
  BigInteger prime;
  // The base g.
  BigInteger generator;
};
            

18.17.7. Operations

Generate Key
  1. Let normalizedAlgorithm be the result of normalizing algorithm to DhKeyGenParams.

  2. If any of the members of DhKeyGenParams are not present in normalizedAlgorithm, then return an error named SyntaxError.

  3. If usages contains a value which is not one of "deriveKey" or "deriveBits", then return an error named DataError.

  4. Generate a Diffie-Hellman key pair, as defined in Section 7 of [PKCS #3], with prime, p, and base, g, as specified in the prime and generator properties of normalizedAlgorithm, respectively.

  5. If performing the operation results in an error, then return an error named OperationError.

  6. Let algorithm be a new DhKeyAlgorithm object.

  7. Set the name member of algorithm to "DH".

  8. Set the prime attribute of algorithm to equal the prime member of normalizedAlgorithm.

  9. Set the generator attribute of algorithm to equal the generator member of normalizedAlgorithm.

  10. Let publicKey be a new Key object representing the public key of the generated key pair.

  11. Set the type attribute of publicKey to "public"

  12. Set the algorithm attribute of publicKey to be algorithm.

  13. Set the extractable attribute of publicKey to true.

  14. Set the usages attribute of publicKey to be the empty list.

  15. Let privateKey be a new Key object representing the private key of the generated key pair.

  16. Set the type attribute of privateKey to "private"

  17. Set the algorithm attribute of privateKey to be algorithm.

  18. Set the extractable attribute of privateKey to extractable.

  19. Set the usages attribute of privateKey to be usages.

  20. Let result be a new KeyPair object.

  21. Set the publicKey attribute of result to be publicKey.

  22. Set the privateKey attribute of result to be privateKey.

  23. Return result.

Derive Bits
  1. If the type attribute of key is not "private", then return an error named InvalidAccessError.

  2. Let normalizedAlgorithm be the result of normalizing algorithm to DhKeyDeriveParams.

  3. If any of the members of DhKeyDeriveParams are not present in normalizedAlgorithm, then return an error named SyntaxError.

  4. Let publicKey be the public member of normalizedAlgorithm.

  5. If the name attribute of the algorithm attribute of publicKey is not "DH", then return an error named DataError.

  6. If the type attribute of publicKey is not "public", then return an error named DataError.

  7. If the prime attribute of the algorithm attribute of publicKey is not equal to the prime attribute of the algorithm attribute of key, then return an error named DataError.

  8. If the generator attribute of the algorithm attribute of publicKey is not equal to the generator attribute of the algorithm attribute of key, then return an error named DataError.

  9. Perform the Diffie Hellman Phase II algorithm as specified in Section 8 of [PKCS #3] with key as the DH private value x and the Diffie Hellman public value represented by the public member of normalizedAlgorithm as the other's public value PV'.

    If performing the operation results in an error:
    Return an error named OperationError.
    Otherwise:
    Let secret be the output of the DH Phase II, SK.
  10. If the length of secret in bits is less than length:
    Return an error named DataError.
    Otherwise:
    Return the first length bits of secret.
Import Key
If format is "raw":
Editorial note

Raw import of private values is presently not supported.

  1. Let normalizedAlgorithm be the result of normalizing algorithm to DhImportKeyParams.

  2. If any of the members of DhImportKeyParams are not present in normalizedAlgorithm, then return an error named SyntaxError.

  3. If extractable is false, then return an error named DataError.

  4. Let PV be the integer which results from interpreting the octets of keyData as an unsigned big integer with most significant octet first.

  5. Let key be a new Key object representing a Diffie-Hellman public key with public value PV and with prime, p and base, g equal to the prime and generator properties of normalizedAlgorithm respectively.

  6. Set the type attribute of key to "public".

  7. Let algorithm be a new DhKeyAlgorithm.

  8. Set the name attribute of algorithm to "DH".

  9. Set the prime attribute of algorithm to equal the prime member of normalizedAlgorithm.

  10. Set the generator attribute of algorithm to equal the generator member of normalizedAlgorithm.

  11. Set the algorithm attribute of key to algorithm.

  12. Set the extractable attribute of key to extractable.

  13. Set the usages attribute of key to usages.

  14. Return key.

If format is "spki":
  1. Let spki be the result of running the parse a subjectPublicKeyInfo algorithm over keyData.

  2. If an error occured while parsing, then return an error named DataError.

  3. If the algorithm object identifier field of the algorithm AlgorithmIdentifier field of spki is not equivalent to the dhKeyAgreement OID defined in Section 9 of [PKCS #3], then return an error named DataError.

  4. If the parameters field of the algorithm AlgorithmIdentifier field of spki is absent, then return an error named DataError.

  5. Let params be the parameters field of the algorithm AlgorithmIdentifier field of spki.

  6. If params is not an instance of the DHParameter ASN.1 type defined in Section 9 of PKCS #3, then return an error named DataError.

  7. Let key be a new Key object representing the Diffie-Hellman public key obtained by parsing the subjectPublicKey field of spki as an ASN.1 INTEGER.

  8. Set the type propety of key to "public".

  9. Let algorithm be a new DhKeyAlgorithm.

  10. Set the name member of algorithm to "DH".

  11. Set the prime attribute of algorithm to a new BigInteger equal to the octet string encoding of the prime field of params.

  12. Set the generator attribute of algorithm to a new BigInteger equal to the octet string encoding of the base field of params.

  13. Set the algorithm attribute of key to algorithm.

  14. Set the extractable attribute of key to extractable.

  15. Set the usages attribute of key to the normalized value of usages.

  16. Return key.

If format is "pkcs8":
  1. If usages contains a value which is not one of "deriveKey" or "deriveBits", then return an error named DataError.

  2. Let privateKeyInfo be the result of running the parse a privateKeyInfo algorithm over keyData.

  3. If an error occurred while parsing, then return an error named OperationError.

  4. If the algorithm object identifier field of the algorithm AlgorithmIdentifier field of privateKeyInfo is not equivalent to the dhKeyAgreement OID defined in Section 9 of [PKCS #3], then return an error named DataError.

  5. If the parameters field of the privateKeyAlgorithm PrivateKeyAlgorithmIdentifier field of privateKeyInfo is absent, then return an error named DataError.

  6. Let params be the parameters field of the privateKeyAlgorithm PrivateKeyAlgorithmIdentifier field of privateKeyInfo.

  7. If params is not an instance of the DHParameter ASN.1 type defined in Section 9 of PKCS #3, then return an error named DataError.

  8. Let key be a new Key object representing the Diffie-Hellman private key obtained by parsing the privateKey field of privateKeyInfo as an ASN.1 INTEGER.
  9. Set the type attribute of key to "private".

  10. Let algorithm be a new DhKeyAlgorithm.

  11. Set the name member of algorithm to "DH".

  12. Set the prime attribute of algorithm to a new BigInteger equal to the octet string encoding of the prime field of params.

  13. Set the generator attribute of algorithm to a new BigInteger equal to the octet string encoding of the base field of params.

  14. Set the algorithm attribute of key to algorithm.

  15. Set the extractable attribute of key to extractable.

  16. Set the usages attribute of key to the normalized value of usages.

  17. Return key.

Otherwise:
Return an error named NotSupportedError.
Export Key
  1. If format is "raw":
    If the type attribute of key is "public":
    Let result be the Public Value, PV, associated with key as specified in Section 7 of [PKCS #3].
    If the type attribute of key is "private":
    Let result be the octet string that represents the private value x associated with key as a big integer, most significant octet first.
    If format is "spki":
    1. If the type attribute of key is not "public", then return an error named InvalidAccessError.

    2. Let result be the result of encoding a subjectPublicKeyInfo with the following properties:

      • Set the algorithmIdentifier field to an AlgorithmIdentifier ASN.1 structure with the following properties:

        • Set the algorithm field to the dhKeyAgreement OID defined in Section 9 of PKCS #3.

        • Set the parameters field to an instance of the DHParams ASN.1 structure defined in Section 9 of PKCS #3 with the following properties:

          • Set the prime field to an ASN.1 INTEGER that is equivalent to the prime attribute of the algorithm attribute of key.

          • Set the base field to an ASN.1 INTEGER that is equivalent to the generator attribute of the algorithm attribute of key.

      • Set the subjectPublicKey to an ASN.1 INTEGER that corresponds to the Diffie-Hellman public value represented by key.

    If format is "pkcs8":
    1. If the type attribute of key is not "private", then return an error named InvalidAccessError.

    2. Let result be the result of encoding a privateKeyInfo with the following properties:

      • Set the privateKeyAlgorithm field to a PrivateKeyAlgorithmIdentifier ASN.1 structure with the following properties:

        • Set the algorithm field to the dhKeyAgreement OID defined in Section 9 of PKCS #3.

        • Set the parameters field to an instance of the DHParams ASN.1 structure defined in Section 9 of PKCS #3 with the following properties:

          • Set the prime field to an ASN.1 INTEGER that is equivalent to the prime attribute of the algorithm attribute of key.

          • Set the base field to an ASN.1 INTEGER that is equivalent to the generator attribute of the algorithm attribute of key.

      • Set the privateKey field to an ASN.1 INTEGER that corresponds to the Diffie-Hellman private value represented by key.

    Otherwise:
    Return an error named NotSupportedError.
  2. Let data be a new ArrayBuffer containing result.

  3. Return data.

18.18. SHA

18.18.1. Description

This describes the SHA-1 and SHA-2 families, as specified by [FIPS PUB 180-4].

18.18.2. Registration

The following algorithms are added as recognized algorithm names:

"SHA-1"
The SHA-1 algorithm as specified in Section 6.1
"SHA-256"
The SHA-256 algorithm as specified in Section 6.2
"SHA-384"
The SHA-384 algorithm as specified in Section 6.5
"SHA-512"
The SHA-512 algorithm as specified in Section 6.4
Operation Parameters Result
digest None ArrayBuffer

18.18.3. Operations

Digest
  1. Let normalizedAlgorithm be the result of normalizing algorithm to Algorithm.

  2. If the name member of normalizedAlgorithm is a cases-sensitve string match for "SHA-1":
    Let result be the result of performing the SHA-1 hash function defined in Section 6.1 of [FIPS PUB 180-4] using message as the input message, M.
    If the name member of normalizedAlgorithm is a cases-sensitve string match for "SHA-256":
    Let result be the result of performing the SHA-256 hash function defined in Section 6.2 of [FIPS PUB 180-4] using message as the input message, M.
    If the name member of normalizedAlgorithm is a cases-sensitve string match for "SHA-384":
    Let result be the result of performing the SHA-384 hash function defined in Section 6.5 of [FIPS PUB 180-4] using message as the input message, M.
    If the name member of normalizedAlgorithm is a cases-sensitve string match for "SHA-512":
    Let result be the result of performing the SHA-1 hash function defined in Section 6.4 of [FIPS PUB 180-4] using message as the input message, M.
  3. Return a new ArrayBuffer containing result.

18.19. Concat KDF

18.19.1. Description

The "CONCAT" algorithm identifier is used to perform key derivation using the key derivation algorithm defined in Section 5.8.1 of NIST SP 800-56A [SP800-56A].

18.19.2. Registration

The recognized algorithm name for this algorithm is "CONCAT".

Operation Parameters Result
deriveBits ConcatParams Octet string
Import key None Key
Get key length None Integer or null

18.19.3. ConcatParams dictionary

IDL

dictionary ConcatParams : Algorithm {
  // The digest method to use to derive the keying material.
  AlgorithmIdentifier hash;

  // A bit string corresponding to the AlgorithmId field of the OtherInfo parameter.
  // The AlgorithmId indicates how the derived keying material will be parsed and for which
  // algorithm(s) the derived secret keying material will be used.
  CryptoOperationData algorithmId;
  // A bit string that corresponds to the PartyUInfo field of the OtherInfo parameter.
  CryptoOperationData partyUInfo;
  // A bit string that corresponds to the PartyVInfo field of the OtherInfo parameter.
  CryptoOperationData partyVInfo;
  // An optional bit string that corresponds to the SuppPubInfo field of the OtherInfo parameter.
  CryptoOperationData? publicInfo;
  // An optional bit string that corresponds to the SuppPrivInfo field of the OtherInfo parameter.
  CryptoOperationData? privateInfo;
};
            

18.19.4. Operations

Derive Bits
  1. Let normalizedAlgorithm be the result of normalizing algorithm to ConcatParams.

  2. If any of the hash, algorithmId, partyUInfo or partyVInfo properties are not present in normalizedAlgorithm, then return an error named SyntaxError.

  3. Let secret be the result of performing the Concatenation Key Derivation Funtion defined in Section 5.8.1 of [SP800-56A] with length as keydatalen, the hash function identified by the hash member of normalizedAlgorithm as H, the algorithmId member of normalizedAlgorithm as AlgorithmID, the partyUInfo member of normalizedAlgorithm as PartyUInfo, the partyVInfo member of normalizedAlgorithm as PartyVInfo, the publicInfo member of normalizedAlgorithm, if present and not null, as publicInfo and the privateInfo member of normalizedAlgorithm, if present and not null, as privateInfo.

  4. If the operation fails, then return an error named OperationError.

  5. Return secret

Import key
If format is "raw":
  1. If usages contains a value that is not "deriveKey" or "deriveBits", then return an error named DataError.

  2. Let key be a new Key object representing the key data provided in keyData.

  3. Set the type attribute of key to "secret".

  4. Let algorithm be a new KeyAlgorithm object.

  5. Set the name attribute of algorithm to "CONCAT".

  6. Set the algorithm attribute of key to algorithm.

  7. Set the extractable attribute of key to extractable.

  8. Set the usages attribute of key to the normalized value of usages.

  9. Return key.

Otherwise:
Return an error named NotSupportedError.
Get length
  1. Return null.

18.20. HKDF-CTR

18.20.1. Description

This section is non-normative.

The "HKDF-CTR" algorithm identifier is used to perform key derivation using the extraction-then-expansion approach described in NIST SP 800-56C[SP800-56C], using HMAC in counter mode, as described in Section 5.1 of NIST SP 800-108 [SP800-108].

18.20.2. Registration

The recognized algorithm name for this algorithm is "HKDF-CTR".

Operation Parameters Result
deriveBits HkdfCtrParams ArrayBuffer
Import key None Key
Get key length None Integer or null

18.20.3. HkdfCtrParams dictionary

IDL

dictionary HkdfCtrParams : Algorithm {
  // The algorithm to use with HMAC (eg: SHA-256)
  AlgorithmIdentifier hash;
  // A bit string that corresponds to the label that identifies the purpose for the derived keying material.
  CryptoOperationData label;
  // A bit string that corresponds to the context of the key derivation, as described in Section 5 of NIST SP 800-108 [SP800-108]
  CryptoOperationData context;
};
            
Editorial note

The definition of HKDF allows the caller to supply an optional pseudorandom salt value, which is used as the key during the extract phase. If this value is not supplied, an all zero string is used instead. However, support for an explicit salt value is not widely implemented in existing APIs, nor is it required by existing usages of HKDF. Should this be an optional parameter, and if so, what should the behaviour be of a user agent that does not support explicit salt values (is it conforming or non-conforming?)

18.20.4. Operations

Derive Bits
  1. If length is null, then return an error named DataError.

  2. Let normalizedAlgorithm be the result of normalizing algorithm to HkdfCtrParams.

  3. If any of the members of HkdfCtrParams are not present in normalizedAlgorithm, then return an error named SyntaxError.

  4. If the hash member of normalizedAlgorithm does not describe a recognised algorithm that supports the digest operation, then return an error named NotSupportedError

  5. Let extractKey be a key equal to n zero bits where n is the size of the output of the hash fuction described by the hash member of normalizedAlgorithm.

  6. Let prf be the MAC Generation function described in Section 4 of [FIPS PUB 198-1] using the hash function described by the hash member of normalizedAlgorithm.

  7. Let keyDerivationKey be the result of performing prf using extractKey as the key and the secret represented by key as the message.

  8. Let result be the result of performing the KDF in counter mode operation described in Section 5.1 of NIST SP 800-108 [SP800-108] using:

    • prf as the Pseudo-Random Function, PRF,

    • keyDerivationKey as the Key derivation key, KI,

    • the contents of the label member of normalizedAlgorithm as Label,

    • the contents of the context member of normalizedAlgorithm as Context,

    • length as the value of L,

    • 32 as the value of r, and

    • the 32-bit little-endian binary encoding of length as the encoded length value [L]2.

  9. If the key derivation operation fails, then return an error named OperationError.

  10. Return result.

Import key
If format is "raw":
  1. If usages contains a value that is not "deriveKey" or "deriveBits", then return an error named DataError.

  2. Let key be a new Key object representing the key data provided in keyData.

  3. Set the type attribute of key to "secret".

  4. Let algorithm be a new KeyAlgorithm object.

  5. Set the name attribute of algorithm to "HKDF-CTR".

  6. Set the algorithm attribute of key to algorithm.

  7. Set the extractable attribute of key to extractable.

  8. Set the usages attribute of key to the normalized value of usages.

  9. Return key.

Otherwise:
Return an error named NotSupportedError.
Get length
  1. Return null.

18.21. PBKDF2

18.21.1. Description

This section is non-normative.

The "PBKDF2" algorithm identifier is used to perform key derivation using the PKCS#5 password-based key derivation function version 2.0, as defined in [RFC2898] using HMAC as the pseudo-random function.

18.21.2. Registration

The recognized algorithm name for this algorithm is "PBKDF2".

Operation Parameters Result
generateKey None Key
deriveBits Pbkdf2Params ArrayBuffer
importKey None Key
Get key length None Length or null

18.21.3. Pbkdf2Params dictionary

IDL

dictionary Pbkdf2Params : Algorithm {
  CryptoOperationData salt;
  [EnforceRange] unsigned long iterations;
  AlgorithmIdentifier hash;
};
            
Editorial note

In the above snippet, password is an optional field. The intent is that conforming user agents MAY support applications that wish to use PBKDF2 by providing password entry via an un-spoofable (by the web application) UI.

18.21.4. Operations

Derive bits
  1. Let normalizedAlgorithm be the result of normalizing algorithm to Pbkdf2Params.

  2. If any of the members of Pbkdf2Params are not present in normalizedAlgorithm, then return an error named SyntaxError.

  3. If length is null or is not a multiple of 8, then return an error named DataError.

  4. If the hash member of normalizedAlgorithm does not describe a recognised algorithm that supports the digest operation, then return an error named NotSupportedError

  5. Let prf be the MAC Generation function described in Section 4 of [FIPS PUB 198-1] using the hash function described by the hash member of normalizedAlgorithm.

  6. Let result be the result of performing the PBKDF2 operation defined in Section 5.2 of [RFC2898] using prf as the pseudo-random function, PRF, the password represented by key as the password, P, the contents of the salt attribute of normalizedAlgorithm as the salt, S, the value of the iterations attribute of normalizedAlgorithm as the iteration count, c, and length divided by 8 as the intended key length, dkLen.

  7. If the key derivation operation fails, then return an error named OperationError.

  8. Return result

Generate key
  1. If usages contains any element that is not "deriveKey", then return an error named DataError.

  2. If extractable is true, then return an error named DataError.

  3. Generate a new password by prompting the user.

  4. Let key be a new Key object representing the provided password, encoded using UTF-8.

  5. Set the type attribute of key to "secret".

  6. Let algorithm be a new KeyAlgorithm object.

  7. Set the name attribute of algorithm to "PBKDF2".

  8. Set the algorithm attribute of key to algorithm.

  9. Set the extractable attribute of key to extractable.

  10. Set the usages attribute of key to the normalized value of usages.

  11. Return key.

Import key
  1. If format is not "raw", return an error named NotSupportedError

  2. If usages contains any element that is not "deriveKey", then return an error named DataError.

  3. Let key be a new Key object representing keyData.

  4. Set the type attribute of key to "secret".

  5. Let algorithm be a new KeyAlgorithm object.

  6. Set the name attribute of algorithm to "PBKDF2".

  7. Set the algorithm attribute of key to algorithm.

  8. Set the extractable attribute of key to extractable.

  9. Set the usages attribute of key to the normalized value of usages.

  10. Return key.

Get length
  1. Return null.

19. Algorithm normalizing rules

The AlgorithmIdentifier typedef permits algorithms to be specified as either an Algorithm dictionary or a DOMString. The DOMString option permits algorithms to be specified using shorthand 'aliases'. Algorithms may define aliases and the values they correspond to. Using an alias is exactly equivalent to using the value corresponding to the alias.

Additionally, many algorithms define a subclass of the Algorithm type. As a result WebIDL type mapping to the correct subclass must be performed at the appropriate time.

When this specification says that a value algorithm be normalized to type the user agent must perform the following steps:

  1. Let mappedAlgorithm be the result of mapping algorithm to the AlgorithmIdentifier type as specified in [WEBIDL].

  2. If mappedAlgorithm is a DOMString, then:
    1. If mappedAlgorithm contains any non-ASCII characters, return an error named SyntaxError.

    2. Convert every character in mappedAlgorithm to lower case.

    3. If mappedAlgorithm is equal to a recognized algorithm alias then let objectAlgorithm be the value defined to be equivalent to this alias.

    4. Otherwise, return an error named SyntaxError.

    Otherwise:
    Let objectAlgorithm equal algorithm.
  3. Let result be the result of mapping objectAlgorithm to type as specified in [WEBIDL].

  4. If a member, memberName, of type has a type that is a union of DOMString and a type, memberType, that is either Algorithm or a subclass of Algorithm and if the memberName member of result is present and has type DOMString, then replace memberName in result with the result of normalizing the memberName member of result to memberType.

  5. Return result.

20. JavaScript Example Code

20.1. Generate a signing key pair, sign some data

ECMAScript

// Algorithm Object
var algorithmKeyGen = {
  name: "RSASSA-PKCS1-v1_5",
  // RsaHashedKeyGenParams
  modulusLength: 2048,
  publicExponent: new Uint8Array([0x01, 0x00, 0x01]),  // Equivalent to 65537
  hash: {
    name: "SHA-256",
  }
};

var algorithmSign = {
  name: "RSASSA-PKCS1-v1_5"
};

window.crypto.subtle.generateKey(algorithmKeyGen, false, ["sign"]).then(
  function(key) {
    var dataPart1 = convertPlainTextToArrayBufferView("hello,");
    var dataPart2 = convertPlainTextToArrayBufferView(" world!");
    // TODO: create example utility function that converts text -> ArrayBufferView

    return window.crypto.subtle.sign(algorithmSign, key.privateKey, [dataPart1, dataPar2]);
  },
  console.error.bind(console, "Unable to generate a key")
).then(
  console.log.bind(console, "The signature is: "),
  console.error.bind(console, "Unable to sign")
);
        

20.2. Symmetric Encryption

ECMAScript

var clearDataArrayBufferView = convertPlainTextToArrayBufferView("Plain Text Data");
// TODO: create example utility function that converts text -> ArrayBufferView

var aesAlgorithmKeyGen = {
  name: "AES-CBC",
  // AesKeyGenParams
  length: 128
};

var aesAlgorithmEncrypt = {
  name: "AES-CBC",
  // AesCbcParams
  iv: window.crypto.getRandomValues(new Uint8Array(16))
};

// Create a keygenerator to produce a one-time-use AES key to encrypt some data
window.crypto.subtle.generateKey(aesAlgorithmKeyGen, false, ["encrypt"]).then(
  function(aesKey) {
    return window.crypto.subtle.encrypt(aesAlgorithmEncrypt, aesKey, [ clearDataArrayBufferView ]);
  }
).then(console.log.bind(console, "The ciphertext is: "),
       console.error.bind(console, "Unable to encrypt"));
        

21. IANA Considerations

21.1. JSON Web Signature and Encryption Algorithms Registration

This section registers the following algorithm identifiers in the IANA JSON Web Signature and Encryption Algorithms Registry for use with JSON Web Key. Note that the 'Implementation Requirements' field in the template refers to use with JSON Web Signature and JSON Web Encryption specifically, in which case use of unauthenticated encryption is prohibited.

  • Algorithm Name: "A128CBC"
  • Algorithm Description: AES CBC using 128 bit key
  • Algorithm Usage Location(s): "JWK"
  • JOSE Implementation Requirements: Prohibited
  • Change Controller: W3C Web Cryptography Working Group
  • Specification Document(s): [[ This Document ]]
  • Algorithm Name: "A192CBC"
  • Algorithm Description: AES CBC using 192 bit key
  • Algorithm Usage Location(s): "JWK"
  • JOSE Implementation Requirements: Prohibited
  • Change Controller: W3C Web Cryptography Working Group
  • Specification Document(s): [[ This Document ]]
  • Algorithm Name: "A256CBC"
  • Algorithm Description: AES CBC using 256 bit key
  • Algorithm Usage Location(s): "JWK"
  • JOSE Implementation Requirements: Prohibited
  • Change Controller: W3C Web Cryptography Working Group
  • Specification Document(s): [[ This Document ]]
  • Algorithm Name: "A128CTR"
  • Algorithm Description: AES CTR using 128 bit key
  • Algorithm Usage Location(s): "JWK"
  • JOSE Implementation Requirements: Prohibited
  • Change Controller: W3C Web Cryptography Working Group
  • Specification Document(s): [[ This Document ]]
  • Algorithm Name: "A192CTR"
  • Algorithm Description: AES CTR using 192 bit key
  • Algorithm Usage Location(s): "JWK"
  • JOSE Implementation Requirements: Prohibited
  • Change Controller: W3C Web Cryptography Working Group
  • Specification Document(s): [[ This Document ]]
  • Algorithm Name: "A256CTR"
  • Algorithm Description: AES CTR using 256 bit key
  • Algorithm Usage Location(s): "JWK"
  • JOSE Implementation Requirements: Prohibited
  • Change Controller: W3C Web Cryptography Working Group
  • Specification Document(s): [[ This Document ]]
  • Algorithm Name: "A128CMAC"
  • Algorithm Description: AES CMAC using 128 bit key
  • Algorithm Usage Location(s): "JWK"
  • JOSE Implementation Requirements: Prohibited
  • Change Controller: W3C Web Cryptography Working Group
  • Specification Document(s): [[ This Document ]]
  • Algorithm Name: "A192CMAC"
  • Algorithm Description: AES CMAC using 192 bit key
  • Algorithm Usage Location(s): "JWK"
  • JOSE Implementation Requirements: Prohibited
  • Change Controller: W3C Web Cryptography Working Group
  • Specification Document(s): [[ This Document ]]
  • Algorithm Name: "A256CMAC"
  • Algorithm Description: AES CMAC using 256 bit key
  • Algorithm Usage Location(s): "JWK"
  • JOSE Implementation Requirements: Prohibited
  • Change Controller: W3C Web Cryptography Working Group
  • Specification Document(s): [[ This Document ]]
  • Algorithm Name: "A128CFB8"
  • Algorithm Description: AES CFB-8 using 128 bit key
  • Algorithm Usage Location(s): "JWK"
  • JOSE Implementation Requirements: Prohibited
  • Change Controller: W3C Web Cryptography Working Group
  • Specification Document(s): [[ This Document ]]
  • Algorithm Name: "A192CFB8"
  • Algorithm Description: AES CFB-8 using 192 bit key
  • Algorithm Usage Location(s): "JWK"
  • JOSE Implementation Requirements: Prohibited
  • Change Controller: W3C Web Cryptography Working Group
  • Specification Document(s): [[ This Document ]]
  • Algorithm Name: "A256CFB8"
  • Algorithm Description: AES CFB-8 using 256 bit key
  • Algorithm Usage Location(s): "JWK"
  • JOSE Implementation Requirements: Prohibited
  • Change Controller: W3C Web Cryptography Working Group
  • Specification Document(s): [[ This Document ]]
  • Algorithm Name: "HS1"
  • Algorithm Description: HMAC using SHA-1
  • Algorithm Usage Location(s): "JWK"
  • JOSE Implementation Requirements: Prohibited
  • Change Controller: W3C Web Cryptography Working Group
  • Specification Document(s): [[ This Document ]]

21.2. JSON Web Key Parameters Registry

  • Parameter Name: "ext"
  • Used with "kty" Value(s): *
  • Parameter Information Class: Public
  • Change Controller: W3C Web Cryptography Working Group
  • Specification Document(s): [[ This Document]]

22. Acknowledgements

The editors would like to thank Adam Barth, Alex Russell, Ali Asad, Arun Ranganathan, Brian Smith, Brian Warner, Channy Yun, Eric Roman, Glenn Adams, Jim Schaad, Kai Engert, Mark Watson, Michael Hutchinson, Michael Jones, Nick Van den Bleeken, Richard Barnes, Vijay Bharadwaj, Virginie Galindo, and Wan-Teh Chang for their technical feedback and assistance.

Thanks to the W3C Web Cryptography WG, and to participants on the public-webcrypto@w3.org mailing list.

The W3C would like to thank the Northrop Grumman Cybersecurity Research Consortium for supporting W3C/MIT.

The getRandomValues method in the Crypto interface was originally proposed by Adam Barth to the WHATWG.

23. References

23.1. Normative References

DOM4
DOM (Living Standard), A. Gregor, A. van Kesteren, Ms2ger. WHATWG.
Editorial note
This will be updated to W3C DOM4 once Promises are incorporated.
ECMAScript
ECMAScript 5th Edition, A. Wirfs-Brock, P. Lakshman et al.
FIPS 180-4
FIPS PUB 180-4: Secure Hash Standard, NIST.
HTML
HTML5: A vocabulary and associated APIs for HTML and XHTML (work in progress), I. Hickson. W3C.
PKCS3
PKCS #3: Diffie-Hellman Key-Agreement Standard, RSA Laboratories.
RFC2119
Key words for use in RFCs to Indicate Requirement Levels, S. Bradner. IETF.
RFC3279
Algorithms and Identifiers for the Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile, W. Polk, R. Housley, L. Bassham. IETF.
RFC3447
Public-Key Cryptography Standards (PKCS) #1: RSA Cryptography Specifications Version 2.1, J. Jonsson, B. Kaliski. IETF.
RFC5208
Public-Key Cryptography Standards (PKCS) #8: Private-Key Information Syntax Specification Version 1.2, B. Kaliski. IETF.
RFC5280
Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile, D. Cooper, S. Santesson, S. Farrell, S. Boeyen, R. Housley, W. Polk. IETF.
RFC5480
Elliptic Curve Cryptography Subject Public Key Information, S. Turner, D. Brown, K. Yiu, R. Housley, T. Polk. IETF.
RFC5756
Updates for RSAES-OAEP and RSASSA-PSS Algorithm Parameters, S. Turner, D. Brown, K. Yiu, R. Housley, T. Polk. IETF.
RFC5958
Asymmetric Key Packages, S. Turner. IETF.
Typed Arrays
Typed Arrays (work in progress), V. Vukicevic, K. Russell. Khronos Group.
WebIDL Specification
WebIDL (work in progress), C. McCormack.
X9.62
ANS X9.62–2005: Public Key Cryptography for the Financial Services Industry, The Elliptic Curve Digital Signature Algorithm (ECDSA), ANSI.
X9.63
ANS X9.63–2001: Public Key Cryptography for the Financial Services Industry, Key Agreement and Key Transport Using Elliptic Curve Cryptography, ANSI.
JSON Web Key
JSON Web Key (work in progress), M. Jones, Microsoft.
JSON Web Algorithms
JSON Web Algorithms (work in progress), M. Jones, Microsoft.
RFC3394
Advanced Encryption Standard (AES) Key Wrap Algorithm, J. Schaad, R. Housley, IETF.
FIPS PUB 198-1
The Keyed-Hash Message Authentication Code (HMAC) , July 2008, NIST.
ITU-T X.690 (11/2008)
ASN.1 encoding rules: Specification of Basic Encoding Rules (BER), Canonical Encoding Rules (CER) and Distinguished Encoding Rules (DER) , November 2008, ITU.

23.2. Informative References

CDSA
Common Security: CDSA and CSSM, Version 2 (with corrigenda), the Open Group.
CNG
Cryptography API: Next Generation, Microsoft Corporation.
CryptoAPI
Cryptography Reference, Microsoft Corporation.
DRAFT-TLS-OBC
TLS Origin-Bound Certificates, D. Balfanz, D. Smetters, M. Upadhyay, A. Barth. IETF.
FileAPI
File API, A. Ranganathan, J. Sicking. W3C.
PKCS11
PKCS #11: Cryptographic Token Interface Standard, RSA Laboratories.
RFC 2315
PKCS #7: Cryptographic Message Syntax, Version 1.5, B. Kaliski. RSA Laboratories.
RFC 2898
PKCS #5: Password-Based Cryptography Specification, Version 2.0, B. Kaliski. RSA Laboratories
RFC 4055
Additional Algorithms and Identifiers for RSA Cryptography for use in the Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile, J. Schaad, B. Kaliski, R. Housley. IETF.
RFC 5705
Keying Material Exporters for Transport Layer Security (TLS), E. Rescorla. IETF.
RFC 5869
HMAC-based Extract-and-Expand Key Derivation Function (HKDF), H. Krawczyk, P. Eronen. IETF.
RFC5915
Elliptic Curve Private Key Structure, S. Turner. D. Brown. IETF.
NIST SP 800-38A
NIST Special Publication 800-38A: Recommendation for Block Cipher Modes of Operation, Methods and Techniques, December 2001, NIST.
NIST SP 800-38B
NIST Special Publication 800-38B: Recommendation for Block Cipher Modes of Operation: The CMAC Mode for Authentication, May 2005, NIST.
NIST SP 800-38D
NIST Special Publication 800-38D: Recommendation for Block Cipher Modes of Operation: Galois/Counter Mode (GCM) and GMAC, November 2007, NIST.
NIST SP 800-56A
NIST Special Publication 800-56A: Recommendation for Pair-Wise Key Establishment Schemes Using Discrete Logarithm Cryptography (Revised), March 2007, NIST.
NIST SP 800-56C
NIST Special Publication 800-56C: Recommendation for Key Derivation through Extraction-then-Expansion, November 2011, NIST.
NIST SP 800-108
NIST Special Publication 800-108: Recommendation for Key Derivation Using Pseudorandom Functions (Revised), October 2009, NIST.
StreamsAPI
Streams API , F. Moussa. W3C.

A. Mapping between JSON Web Key / JSON Web Algorithm

The following section is non-normative. Refer to algorithm-specific sections for the normative requirements of importing and exporting JWK.

A.1. Algorithm mappings

JSON Web Key AlgorithmIdentifier
ECMAScript

{ kty: "RSA",
  alg: "RSA1_5" }
ECMAScript

{ name: "RSAES-PKCS1-V1_5" }
ECMAScript

{ kty: "RSA",
  alg: "RS256" }
ECMAScript

{ name: "RSASSA-PKCS1-v1_5",
  hash: { name: "SHA-256" }
}
ECMAScript

{ kty: "RSA",
  alg: "RS384" }
ECMAScript

{ name: "RSASSA-PKCS1-v1_5",
  hash: { name: "SHA-384" }
}
ECMAScript

{ kty: "RSA",
  alg: "RS512" }
ECMAScript

{ name: "RSASSA-PKCS1-v1_5",
  hash: { name: "SHA-512" }
}
ECMAScript

{ kty: "RSA",
  alg: "PS256" }
ECMAScript

{ name: "RSA-PSS",
  hash: { name: "SHA-256" }
}
ECMAScript

{ kty: "RSA",
  alg: "PS384" }
ECMAScript

{ name: "RSA-PSS",
  hash: { name: "SHA-384" }
}
ECMAScript

{ kty: "RSA",
  alg: "PS512" }
ECMAScript

{ name: "RSA-PSS",
  hash: { name: "SHA-512" }
}
ECMAScript

{ kty: "EC",
  alg: "ES256" }
ECMAScript

{ name: "ECDSA",
  namedCurve: "P-256"
  hash: { name: "SHA-256" }
}
ECMAScript

{ kty: "EC",
  alg: "ES384" }
ECMAScript

{ name: "ECDSA",
  namedCurve: "P-384"
  hash: { name: "SHA-384" }
}
ECMAScript

{ kty: "EC",
  alg: "ES512" }
ECMAScript

{ name: "ECDSA",
  namedCurve: "P-521"
  hash: { name: "SHA-512" }
}
ECMAScript

{ kty: "oct",
  alg: "A128CTR" }
ECMAScript

{ name: "AES-CTR",
  length: 128 }
ECMAScript

{ kty: "oct",
  alg: "A192CTR" }
ECMAScript

{ name: "AES-CTR",
  length: 192 }
ECMAScript

{ kty: "oct",
  alg: "A256CTR" }
ECMAScript

{ name: "AES-CTR",
  length: 256 }
ECMAScript

{ kty: "oct",
  alg: "A128CBC" }
ECMAScript

{ name: "AES-CBC",
  length: 128 }
ECMAScript

{ kty: "oct",
  alg: "A192CBC" }
ECMAScript

{ name: "AES-CBC",
  length: 192 }
ECMAScript

{ kty: "oct",
  alg: "A256CBC" }
ECMAScript

{ name: "AES-CBC",
  length: 256 }
ECMAScript

{ kty: "oct",
  alg: "A128KW" }
ECMAScript

{ name: "AES-KW",
  length: 128 }
ECMAScript

{ kty: "oct",
  alg: "A192KW" }
ECMAScript

{ name: "AES-KW",
  length: 192 }
ECMAScript

{ kty: "oct",
  alg: "A256KW" }
ECMAScript

{ name: "AES-KW",
  length: 256 }
ECMAScript

{ kty: "oct",
  alg: "A128GCM" }
ECMAScript

{ name: "AES-GCM",
  length: 128 }
ECMAScript

{ kty: "oct",
  alg: "A192GCM" }
ECMAScript

{ name: "AES-GCM",
  length: 192 }
ECMAScript

{ kty: "oct",
  alg: "A256GCM" }
ECMAScript

{ name: "AES-GCM",
  length: 256 }
ECMAScript

{ kty: "oct",
  alg: "A128GCMKW" }
ECMAScript

{ name: "AES-GCM",
  length: 128 }
ECMAScript

{ kty: "oct",
  alg: "A192GCMKW" }
ECMAScript

{ name: "AES-GCM",
  length: 192 }
ECMAScript

{ kty: "oct",
  alg: "A256GCMKW" }
ECMAScript

{ name: "AES-GCM",
  length: 256 }
ECMAScript

{ kty: "oct",
  alg: "A128CMAC" }
ECMAScript

{ name: "AES-CMAC",
  length: 128 }
ECMAScript

{ kty: "oct",
  alg: "A192CMAC" }
ECMAScript

{ name: "AES-CMAC",
  length: 192 }
ECMAScript

{ kty: "oct",
  alg: "A256CMAC" }
ECMAScript

{ name: "AES-CMAC",
  length: 256 }
ECMAScript

{ kty: "oct",
  alg: "A128CFB8" }
ECMAScript

{ name: "AES-CFB-8",
  length: 128 }
ECMAScript

{ kty: "oct",
  alg: "A192CFB8" }
ECMAScript

{ name: "AES-CFB-8",
  length: 192 }
ECMAScript

{ kty: "oct",
  alg: "A256CFB8" }
ECMAScript

{ name: "AES-CFB-8",
  length: 256 }
ECMAScript

{ kty: "oct",
  alg: "HS1" }
ECMAScript

{ name: "HMAC",
  hash: { name: "SHA-1" }
}
ECMAScript

{ kty: "oct",
  alg: "HS256" }
ECMAScript

{ name: "HMAC",
  hash: { name: "SHA-256" }
}
ECMAScript

{ kty: "oct",
  alg: "HS384" }
ECMAScript

{ name: "HMAC",
  hash: { name: "SHA-384" }
}
ECMAScript

{ kty: "oct",
  alg: "HS512" }
ECMAScript

{ name: "HMAC",
  hash: "SHA-512" }
Editorial note

Should the following be specified.

  • RSASSA-PKCS1-v1_5 with SHA-1

  • RSA-PSS with SHA-1

  • RSA-OAEP needs specifiers for the hash algorithms.

  • ECDSA with SHA-1

  • ECDSA where the curve (P-256, P-384, P-521) is not aligned with the hash (SHA-256, SHA-384, SHA-512)

A.2. Usage mapping

JWK use value KeyUsages
enc ["encrypt", "decrypt", "wrapKey", "unwrapKey"]
sig ["sign","verify"]

B. Mapping between Algorithm and SubjectPublicKeyInfo

The following section is non-normative. Refer to algorithm-specific sections for the normative requirements of importing and exporting SPKI.

Algorithm OID subjectPublicKey ASN.1 structure AlgorithmIdentifier Reference
rsaEncryption (1.2.840.113549.1.1.1) RSAPublicKey "RSAES-PKCS1-v1_5", "RSASSA-PKCS1-v1_5", "RSA-PSS", or "RSA-OAEP" RFC 3279, RFC 4055, RFC 5756
id-RSASSA-PSS (1.2.840.113549.1.1.10) RSAPublicKey "RSA-PSS" RFC 4055, RFC 5756
id-RSAES-OAEP (1.2.840.113549.1.1.7) RSAPublicKey "RSA-OAEP" RFC 4055, RFC 5756
id-ecPublicKey (1.2.840.10045.2.1) ECPoint "ECDH" or "ECDSA" RFC 5480
id-ecDH (1.3.132.112) ECPoint "ECDH" RFC 5480
id-dsa (1.2.840.10040.4.1) DSAPublicKey "DSA" RFC 3279
dhKeyAgreement (1.2.840.113549.1.3.1) INTEGER "DH" PKCS #3
Editorial note

The handling of "id-RSASSA-PSS" and "id-RSAES-OAEP" are tricky. RFC 5756 recommends implementations should not include parameters when PSS is used with a subjectPublicKeyInfo, and MUST NOT include parameters when OAEP is used. However, when OAEP is used as part of a key transport (as an AlgorithmIdentifier), implementations MUST include the parameters.

The natural conflict is in deciding when a key is being exported as part of a subjectPublicKeyInfo (which is what "spki" implies) and when it's being used as an algorithmIdentifier for transport.

C. Mapping between Algorithm and PKCS#8 PrivateKeyInfo

The following section is non-normative. Refer to algorithm-specific sections for the normative requirements of importing and exporting PKCS#8 PrivateKeyInfo.

privateKeyAlgorithm privateKey format AlgorithmIdentifier Reference
rsaEncryption (1.2.840.113549.1.1.1) RSAPrivateKey "RSAES-PKCS1-v1_5", "RSASSA-PKCS1-v1_5", "RSA-PSS", or "RSA-OAEP" RFC 3447, RFC 5958
id-RSASSA-PSS (1.2.840.113549.1.1.10) RSAPrivateKey "RSA-PSS" RFC 3447, RFC 4055, RFC 5958
id-RSAES-OAEP (1.2.840.113549.1.1.7) RSAPrivateKey "RSA-OAEP" RFC 3447, RFC 4055, RFC 5958
id-ecPublicKey (1.2.840.10045.2.1) ECPrivateKey "ECDH" or "ECDSA" RFC 5480, RFC 5915, RFC 5958
id-ecDH (1.3.132.112) ECPrivateKey "ECDH" RFC 5480, RFC 5915, RFC 5958
id-dsa (1.2.840.10040.4.1) INTEGER "DSA" RFC 5958
dhKeyAgreement (1.2.840.113549.1.3.1) INTEGER "DH" PKCS #3
Editorial note

There does not appear to be a normative reference for a DH key being encoded as an INTEGER. Only RFC 5958 seems to mention this.