Movatterモバイル変換


[0]ホーム

URL:


W3C

Web Cryptography Level 2

W3C First Public Working Draft

More details about this document
This version:
https://www.w3.org/TR/2025/WD-webcrypto-2-20250422/
Latest published version:
https://www.w3.org/TR/webcrypto-2/
Latest editor's draft:
https://w3c.github.io/webcrypto/
History:
https://www.w3.org/standards/history/webcrypto-2/
Commit history
Editor:
Daniel Huigens (Proton AG)
Former editors:
Mark Watson - Until
Ryan Sleevi - Until
Feedback:
GitHub w3c/webcrypto (pull requests,new issue,open issues)

Copyright © 2025World Wide Web Consortium.W3C®liability,trademark andpermissive document license rules apply.


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.

Status of This Document

This section describes the status of this document at the time of its publication. A list of currentW3C publications and the latest revision of this technical report can be found in theW3C standards and drafts index at https://www.w3.org/TR/.

This document was published by theWeb Application Security Working Group as a First Public Working Draft using theRecommendation track.

Publication as a First Public Working Draft does not imply endorsement byW3C and its Members.

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 document was produced by a group operating under theW3C Patent Policy.W3C maintains apublic 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 containsEssential Claim(s) must disclose the information in accordance withsection 6 of theW3C Patent Policy.

This document is governed by the03 November 2023W3C Process Document.

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 theSubtleCrypto interface, which defines a set of methods for performing common cryptographic operations. 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 and key import and export.

2.Use Cases

This section is non-normative.

2.1Multi-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 prefer the richer user experience provided by authenticating within the application itself.

Using the Web Cryptography API, the 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.

This exchange could be further strengthened by binding the authentication to the TLS session over which the client is authenticating, by deriving a key based on properties of the underlying transport.

If a user does 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 choice.

2.2Protected Document Exchange

A web application may wish to limit the viewership of documents that contain sensitive or personal information, even when these documents have been securely received, such as over TLS.

Using the Web Cryptography API, the application could do so by encrypting the documents with a secret key, and then wrapping that key with the public keys associated with the authorized viewers. When a user agent navigates to such a web application, the application would 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.3Cloud Storage

A web application may wish to permit users to protect the confidentiality of data and documents stored with remote service providers prior to uploading.

Using the Web Cryptography API, the application may have a user select a private or secret key, optionally derive an encryption key from the selected key, encrypt the document, and then upload the encrypted data to the service provider using existing APIs.

This use case is similar to theProtected Document Exchange use case, with viewership of the document limited to the user themself.

2.4Document Signing

A web application may wish to accept electronic signatures on documents, in lieu of requiring physical signatures.

Using the Web Cryptography API, the application may direct the user to select a key, which may have been pre-provisioned out-of-band, or generated specifically for the web application. Using this key, the application may perform a signing operation over some data, as proof that the user accepts the document.

2.5Data Integrity Protection

A web application may wish to cache data locally, while ensuring that this data cannot be modified in an offline attack.

Using the Web Cryptography API, the application may use a public key contained within the application to verify the contents of the data cache. Previously, when data was added to the cache, it would have been signed by the server with the corresponding private key. By validating the signature when restoring data from the cache, the client ensures that the cached data has not been tampered with.

2.6Secure Messaging

A web application may wish to employ message layer security using schemes such as off-the-record (OTR) messaging, even when these messages have been securely received, such as over TLS.

The Web Cryptography API enables OTR and similar message signing schemes, by allowing key agreement to be performed. 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.

2.7JavaScript Object Signing and Encryption (JOSE)

A web application may wish to interact with the structures and message formats defined by the IETF JavaScript Object Signing and Encryption (JOSE) Working Group.

Using the Web Cryptography API, the application may read and import keys encoded in the JSON key format (JWK), validate messages that have been integrity protected using digital signatures or MACs (JWS), or decrypt messages 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 key wordsMUST,REQUIRED, andSHALL in this document are to be interpreted as described inBCP 14 [RFC2119] [RFC8174] when, and only when, they appear in all capitals, as shown here.

The following conformance classes are defined by this specification:

conforming user agent

A user agent is considered to be aconforming user agent if it satisfies all of theMUST-,REQUIRED- andSHALL-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.

Conformance requirements phrased as algorithms or specific steps may be implemented in any manner, so long as the end result is equivalent. (In particular, the algorithms defined in this specification are intended to be easy to follow, and not intended to be performant.)

User agents that use ECMAScript to implement the APIs defined in this specificationMUST 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 acase-sensitive manner. String literals in this specification written in monospace font like "this" do not include the enclosing quotes.

3.1Extensibility

Vendor-specific proprietary extensions to this specification are strongly discouraged. Authors must not use such extensions, as doing so reduces interoperability and fragments the user base, allowing only users of specific user agents to access the content in question.

If vendor-specific extensions are needed, the members should be prefixed by vendor-specific strings to prevent clashes with future versions of this specification. Extensions must be defined so that the use of extensions neither contradicts nor causes the non-conformance of functionality defined in the specification.

When vendor-neutral extensions to this specification are needed, either this specification can be updated accordingly, or an extension specification can be written that overrides the requirements in this specification. When someone applying this specification to their activities decides that they will recognize the requirements of such an extension specification, it becomes anapplicable specification for the purposes of conformance requirements in this specification. Applicable specifications defined by theW3C Web Cryptography Working Group are listed in the table below.

SpecificationReference
Note
Readers are advised to consult the errata to this specification for updates to the table above.

4.Scope

This section is non-normative.

4.1Level 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 CryptoKey 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.2Cryptographic 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 thatMUST 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 behaviors of individual algorithms, if implemented.

4.3Out 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.Concepts

This section is non-normative.

5.1Underlying Cryptographic Implementation

This specification assumes, but does not require, that conforming user agents do not and will not be directly implementing cryptographic operations within the user agent itself. Historically, many user agents have deferred cryptographic operations, such as those used within TLS, to existing APIs that are available as part of the underlying operating system or to third-party modules that are managed independently of the user agent.

TheCryptoKey object represents the bridge between the JavaScript execution environment and these underlying libraries, through the use of the internal slot named[[handle]]. The handle represents an opaque type that is implementation specific, which may not be represented within a JavaScript type, nor is it ever exposed to script authors. In this way, theCryptoKey object is the conceptual equivalent to the JavaScript executing environment as the[[handle]] is to the underlying cryptographic implementation.

These APIs are traditionally built around a notion of cryptographic providers, an abstraction for a specific implementation of a set of algorithms. The operating system or library may come with a default provider, and users are frequently allowed to add additional providers, reconfigure the set of enabled algorithms, or otherwise customize how cryptographic services are provided.

While it is assumed that most user agents will be interacting with a cryptographic provider that is implemented purely in software, it is not required by this specification. As a result, the capabilities of some implementations may be limited by the capabilities of the underlying hardware, and, depending on how the user has configured the underlying cryptographic library, this may be entirely opaque to the User Agent.

5.2Key Storage

This specification does not explicitly provide any new storage mechanisms forCryptoKey objects. Instead, by definingserialization and deserialization steps forCryptoKey objects, any existing or future web storage mechanisms that support storingserializable objects can be used to storeCryptoKey objects.

In practice, it is expected that most authors will make use of the Indexed Database API [INDEXEDDB], which allows associative storage of key/value pairs, where the key is some string identifier meaningful to the application, and the value is aCryptoKey object. This allows the storage and retrieval of key material, without ever exposing that key material to the application or the JavaScript environment. Additionally, this allows authors the full flexibility to store any additional metadata with theCryptoKey itself.

6.Security considerations

This section is non-normative.

6.1Security considerations for implementers

By not providing an explicit storage mechanism, this specification assumes thatCryptoKey objects are scoped to the current execution environment and any storage mechanisms available to that environment (e.g. Indexed Database API). Application authors rely upon this for the security of their applications; two origins with the sameCryptoKey object have full access to the underlying key, and as such, messages from these applications cannot be distinguished, and messages sent to these applications can be fully recovered. Implementors should ensure that noCryptoKey objects are shared between two origins unless the author has explicitly chosen to share (e.g., such as through the use of postMessage)

A number of algorithms specified within this specification perform computationally intensive work, such as the generation of significantly large prime numbers, or through repeated iterations of a particular operation. As such, hostile applications may attempt to misuse this API and attempt to cause significant amount of work to be performed by an implementation, denying access or services to other applications that are executing. Implementations should take steps to mitigate these risks, such as limiting the amount of operations an implementation performs concurrently, requiring user consent for operations that may be known to be disruptive for the executing environment, or defining device-specific limits on attributes such as key sizes or iteration counts.

6.2Security considerations for authors

This specification includes descriptions for a variety of cryptographic operations, some of which have known weaknesses when used inappropriately. Application developers must take care and review appropriate and current cryptographic literature, to understand and mitigate such issues. In general, application developers arestrongly discouraged from inventing new cryptographic protocols; as with all applications, users of this specification will be best served through the use of existing protocols, of which this specification provides the necessary building blocks to implement.

In order to use the APIs defined in this specification to provide any meaningful cryptographic assurances, authors must be familiar with existing threats to web applications, as well as the underlying security model employed. Conceptually, issues such as script injection are the equivalent to remote code execution in other operating environments, and allowing hostile script to be injected may allow for the exfiltration of keys or data. Script injection may come from other applications, for which the judicious use of Content Security Policy may mitigate, or it may come from hostile network intermediaries, for which the use of Transport Layer Security may mitigate.

This specification does not define any specific mechanisms for the storage of cryptographic keys. By default, unless specific effort is taken by the author to persist keys, such as through the use of the Indexed Database API, keys created with this API will only be valid for the duration of the current page (e.g. until a navigation event). Authors that wish to use the same key across different pages or multiple browsing sessions must employ existing web storage technologies. Authors should be aware of the security assumptions of these technologies, such as the same-origin security model; that is, any application that shares the same scheme, host, and port have access to the same storage partition, even if other information, such as the path, may differ. Authors may explicitly choose to relax this security through the use of inter-origin sharing, such aspostMessage.

Authors should be aware that this specification places no normative requirements on implementations as to how the underlying cryptographic key material is stored. The only requirement is that key material is not exposed to script, except through the use of theexportKey andwrapKey operations. In particular, it does not guarantee that the underlying cryptographic key material will not be persisted to disk, possibly unencrypted, nor that it will be inaccessible to users or other applications running with the same privileges as the User Agent. Any application or user that has access to the device storage may be able to recover the key material, even through scripts may be prohibited.

This specification places no normative requirements on how implementations handle key material once all references to it go away. That is, conforming user agents are not required to zeroize key material, and it may still be accessible on device storage or device memory, even after all references to theCryptoKey have gone away.

Applications may share aCryptoKey object across security boundaries, such as origins, through the use of the structured clone algorithm and APIs such aspostMessage. While access to the underlying cryptographic key material may be restricted, based upon theextractable attribute, once a key is shared with a destination origin, the source origin can not later restrict or revoke access to the key. As such, authors must be careful to ensure they trust the destination origin to take the same mitigations against hostile script that the source origin employs. Further, in the event of script injection on the source origin, attackers may post the key to an origin under attacker control. Any time that the user agent visits the attacker's origin, the user agent may be directed to perform cryptographic operations using that key, such as the decryption of existing messages or the creation of new, fraudulent messages.

Authors should be aware that users may, at any time, choose to clear the storage associated with an origin, potentially destroying keys. Applications that are meant to provide long-term storage, such as on the server, should consider techniques such as key escrow to prevent such data from being inaccessible. Authors should not presume that keys will be available indefinitely.

6.3Security considerations for users

Users of applications that employ the APIs defined in this specification should be aware that these applications will have full access to all messages exchanged, regardless of the cryptography employed. That is, for messages that are encrypted, applications that use these APIs will have full access to the decrypted message as well.

7.Privacy considerations

This section is non-normative.

Fingerprinting
By exposing additional APIs that reflect capabilities of the underlying platform, this specification may allow malicious applications to determine or distinguish different user agents or devices.
Super-cookies
This specification does not provide any means for malicious applications to create identifiers that outlive existing web storage technologies. However, care must be taken when introducing future revisions to this API or additional cryptographic capabilities, such as those that are hardware backed (e.g.: smart cards or Trusted Platform Modules). Considering that such storage is designed to prevent any two users from having the same underlying key data, such APIs may represent a real risk of being used as a permanent identifier against the user's wishes.
Use ofrandomUUID as user ID
randomUUID is useful for generatinguser IDs, but does not directly give any ability to generateglobal identifiers.

8.Dependencies

This specification relies on underlying specifications.

DOM

Aconforming user agentMUST support at least the subset of the functionality defined in DOM that this specification relies upon; in particular, itMUST supportPromises andDOMException. [DOM]

HTML

Aconforming user agentMUST support at least the subset of the functionality defined in HTML that this specification relies upon; in particular, itMUST support theArrayBufferView typedef andserializable objects. [HTML]

Web IDL

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

9.Terminology

The termsArrayBuffer,ArrayBufferView, andserializable objects, are defined by the HTML specification [HTML].

The termsDOMString andBufferSource are defined in [WEBIDL].

The termbyte sequence is defined in [Infra].

Thelength in bits of abyte sequence is itslength multiplied by 8.

Abyte sequence containing a bit sequenceb is thebyte sequence obtained by first appending zero or more bits of value zero tob such that the length of the resulting bit sequence is minimal and an integer multiple of 8 and then considering each consecutive sequence of 8 bits in that string as a byte.

When this specification says toconvert a non-negative integeri to a byte sequence of lengthn, wheren * 8 is greater than the logarithm to base 2 ofi, the user agent must first calculate the binary representation ofi, most significant bit first, prefix this with sufficient zero bits to form a bit sequence of lengthn * 8, and then return thebyte sequence formed by considering each consecutive sequence of 8 bits in that bit sequence as a byte.

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

Comparing two strings in aASCII case-insensitive manner means comparing them exactly, code point for code point, except that the codepoints in the range U+0041 .. U+005A (i.e. LATIN CAPITAL LETTER A to LATIN CAPITAL LETTER Z) and the corresponding codepoints in the range U+0061 .. U+007A (i.e. LATIN SMALL LETTER A to LATIN SMALL LETTER Z) are also considered to match.

When this specification says toterminate 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 toparse an ASN.1 structure, the user agent must perform the following steps:

  1. Letdata be a sequence of bytes to be parsed.

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

  3. LetexactData be an optional boolean value. If it is not supplied, let it be initialized totrue.

  4. Parsedata according to the Distinguished Encoding Rules of [X690], usingstructure as the ASN.1 structure to be decoded.

  5. IfexactData was specified, and all of the bytes ofdata were not consumed during the parsing phase, thenthrow aDataError.

  6. Return the parsed ASN.1 structure.

When this specification says toparse a subjectPublicKeyInfo, the user agent mustparse an ASN.1 structure, withdata set to the sequence of bytes to be parsed,structure as the ASN.1 structure of subjectPublicKeyInfo, as specified in [RFC5280], andexactData set totrue.

When this specification says toparse a PrivateKeyInfo, the user agent mustparse an ASN.1 structure withdata set to the sequence of bytes to be parsed,structure as the ASN.1 structure of PrivateKeyInfo, as specified in [RFC5208], andexactData set totrue.

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

  1. Letdata be the sequence of bytes to be parsed.

  2. Letjson be the Unicode string that results from interpretingdata according to UTF-8.

  3. Convertjson to UTF-16.

  4. Letresult be the object literal that results from executing theJSON.parse internal function in the context of a new global object, withtext argument set to a JavaScript String containingjson.

  5. Letkey be the result of convertingresult to the IDL dictionary type ofJsonWebKey.

  6. If thekty field ofkey is not defined, thenthrow aDataError.

  7. Returnkey.

When this specification says to calculate theusage intersection of two sequences,a andb the result shall be a sequence containing eachrecognized key usage value that appears in botha andb, in the order listed in the list ofrecognized key usage values, where a value is said to appear in a sequence if an element of the sequence exists that is a case-sensitive string match for that value.

When this specification says to calculate the normalized value of a usages list,usages the result shall be theusage intersection ofusages and a sequence containing allrecognized key usage values.

When this specification refers to thecached ECMAScript object associated with an internal slot [[slot]] ofobject, the user agent must run the following steps:

  1. If the [[slot_cached]] internal slot ofobject is undefined:
    Set the [[slot_cached]] internal slot ofobject to the result of performing type conversion to an ECMAScript object as defined in [WebIDL] to the contents of the [[slot]] internal slot ofobject.
  2. Return the contents of the [[slot_cached]] internal slot ofobject.

10.Crypto interface

TheCrypto interface represents an interface to general purpose cryptographic functionality including a cryptographically strong pseudo-random number generator seeded with truly random values.

WebIDLpartial interface mixinWindowOrWorkerGlobalScope {  [SameObject] readonly attributeCryptocrypto;};[Exposed=(Window,Worker)]interfaceCrypto {  [SecureContext] readonly attributeSubtleCryptosubtle;ArrayBufferViewgetRandomValues(ArrayBufferViewarray);  [SecureContext]DOMStringrandomUUID();};
Note
Implementations should generate cryptographically strong 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 strong 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 strong 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.

10.1Methods and Parameters

10.1.1The getRandomValues method

ThegetRandomValues method generates cryptographically strong random values. It must act as follows:

  1. Ifarray is not anInt8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,BigInt64Array, orBigUint64Array, thenthrow aTypeMismatchError andterminate the algorithm.

  2. LetbyteLength be thebyte length ofarray.

  3. IfbyteLength is greater than 65536,throw aQuotaExceededError andterminate the algorithm.

  4. Letbytes be abyte sequence of lengthbyteLength.

  5. Fillbytes with cryptographically secure random bytes.

  6. Writebytes intoarray.

  7. Returnarray.

Note

Do not generate keys using thegetRandomValues method. Use thegenerateKey method instead.

10.1.2The randomUUID method

TherandomUUID method generates a newversion 4 UUID and returns itsnamespace specific string representation as described insection 3 of [RFC4122]. Togenerate a random UUID:

  1. Letbytes be abyte sequence of length 16.
  2. Fillbytes with cryptographically secure random bytes.
  3. Set the 4 most significant bits ofbytes[6], which represent the UUIDversion, to0100.
  4. Set the 2 most significant bits ofbytes[8], which represent the UUIDvariant, to10.
  5. Return thestring concatenation of «

    1. hexadecimal representation ofbytes[0],hexadecimal representation ofbytes[1],hexadecimal representation ofbytes[2],hexadecimal representation ofbytes[3],
    2. "-",
    3. hexadecimal representation ofbytes[4],hexadecimal representation ofbytes[5],
    4. "-",
    5. hexadecimal representation ofbytes[6],hexadecimal representation ofbytes[7],
    6. "-",
    7. hexadecimal representation ofbytes[8],hexadecimal representation ofbytes[9],
    8. "-",
    9. hexadecimal representation ofbytes[10],hexadecimal representation ofbytes[11],hexadecimal representation ofbytes[12],hexadecimal representation ofbytes[13],hexadecimal representation ofbytes[14],hexadecimal representation ofbytes[15]

    ».

For the steps described in the algorithm togenerate a random UUID, thehexadecimal representation of a bytevalue is the two-character string created by expressingvalue in hexadecimal usingASCII lower hex digits, left-padded with "0" to reach twoASCII lower hex digits.

10.2Attributes

10.2.1The subtle attribute

Thesubtle attribute provides an instance of theSubtleCrypto interface which provides low-level cryptographic primitives and algorithms.

11.Algorithm dictionary

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

WebIDLtypedef (object orDOMString)AlgorithmIdentifier;typedefAlgorithmIdentifierHashAlgorithmIdentifier;dictionaryAlgorithm {  requiredDOMStringname;};

11.1Algorithm Dictionary Members

name
The name of theregistered algorithm to use.

12.KeyAlgorithm dictionary

TheKeyAlgorithm dictionary represents information about the contents of a givenCryptoKey object.

WebIDLdictionaryKeyAlgorithm {  requiredDOMStringname;};

12.1Description

This section is non-normative.

TheKeyAlgorithm dictionary is provided to aid in documenting how fixed, public properties of aCryptoKey are reflected back to an application. The actual dictionary type is never exposed to applications.

12.2KeyAlgorithm dictionary members

name
The name of the algorithm used to generate theCryptoKey

13.CryptoKey interface

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

WebIDLenumKeyType {"public","private","secret" };enumKeyUsage {"encrypt","decrypt","sign","verify","deriveKey","deriveBits","wrapKey","unwrapKey" };[SecureContext,Exposed=(Window,Worker),Serializable]interfaceCryptoKey {  readonly attributeKeyTypetype;  readonly attributebooleanextractable;  readonly attributeobjectalgorithm;  readonly attributeobjectusages;};

13.1Description

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 CryptoKey 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, e.g. when performing a cryptographic operation.

13.2Key interface data types

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

13.3CryptoKey internal slots

EveryCryptoKey object has a set of internal slots that store information about the key. These slots are not exposed as part of this specification; they represent internal state that an implementation uses to implement this specification. The notational convention used in [ECMA-262] is re-used here; internal slots are identified by names enclosed in double square brackets [[ ]].

AllCryptoKey objects have internal slots named[[type]],[[extractable]],[[algorithm]],[[algorithm_cached]],[[usages]],[[usages_cached]], and[[handle]].

The contents of the[[algorithm]] internal slot shall be, or be derived from, aKeyAlgorithm. The contents of the[[usages]] internal slot shall be of type Sequence<KeyUsage>.

Note

The[[handle]] slot is an opaque type that contains whatever data the underlying cryptographic implementation uses to represent a logical key. Different cryptographic implementations may use different types, ranging from opaque identifiers represented as integers, pointer types, or structures that provide identifying information. These handles are never exposed to applications.

13.4CryptoKey interface members

type
Reflects the[[type]] internal slot, which contains the type of the underlying key.
extractable
Reflects the[[extractable]] internal slot, which indicates whether or not the raw keying material may be exported by the application.
algorithm
Returns thecached ECMAScript object associated with the[[algorithm]] internal slot.
usages
Returns thecached ECMAScript object associated with the[[usages]] internal slot, which indicates which cryptographic operations are permissible to be used with this key.

13.5Serialization and deserialization steps

CryptoKey objects areserializable objects. Theirserialization steps, givenvalue andserialized, are:

  1. Setserialized.[[Type]] to the[[type]] internal slot ofvalue.
  2. Setserialized.[[Extractable]] to the[[extractable]] internal slot ofvalue.
  3. Setserialized.[[Algorithm]] to thesub-serialization of the[[algorithm]] internal slot ofvalue.
  4. Setserialized.[[Usages]] to thesub-serialization of the[[usages]] internal slot ofvalue.
  5. Setserialized.[[Handle]] to the[[handle]] internal slot ofvalue.

Theirdeserialization steps, givenserialized andvalue, are:

  1. Initialize the[[type]] internal slot ofvalue toserialized.[[Type]].
  2. Initialize the[[extractable]] internal slot ofvalue toserialized.[[Extractable]].
  3. Initialize the[[algorithm]] internal slot ofvalue to thesub-deserialization ofserialized.[[Algorithm]].
  4. Initialize the[[usages]] internal slot ofvalue to thesub-deserialization ofserialized.[[Usages]].
  5. Initialize the[[handle]] internal slot ofvalue toserialized.[[Handle]].
Note
When deserializing a serializedCryptoKey object, it is important that the object is not deserialized as a different type. This is normatively required by the definition of thedeserialization steps, but it merits specific attention, as such deserialization may expose the contents of the key material, which in some cases (such as when the[[extractable]] internal slot is false) should not be exposed to applications.

14.SubtleCrypto interface

TheSubtleCrypto interface provides a set of methods for dealing with low-level cryptographic primitives and algorithms.

WebIDLenumKeyFormat {"raw","spki","pkcs8","jwk" };[SecureContext,Exposed=(Window,Worker)]interfaceSubtleCrypto {Promise<ArrayBuffer>encrypt(AlgorithmIdentifieralgorithm,CryptoKeykey,BufferSourcedata  );Promise<ArrayBuffer>decrypt(AlgorithmIdentifieralgorithm,CryptoKeykey,BufferSourcedata  );Promise<ArrayBuffer>sign(AlgorithmIdentifieralgorithm,CryptoKeykey,BufferSourcedata  );Promise<boolean>verify(AlgorithmIdentifieralgorithm,CryptoKeykey,BufferSourcesignature,BufferSourcedata  );Promise<ArrayBuffer>digest(AlgorithmIdentifieralgorithm,BufferSourcedata  );Promise<(CryptoKey orCryptoKeyPair)>generateKey(AlgorithmIdentifieralgorithm,booleanextractable,sequence<KeyUsage>keyUsages  );Promise<CryptoKey>deriveKey(AlgorithmIdentifieralgorithm,CryptoKeybaseKey,AlgorithmIdentifierderivedKeyType,booleanextractable,sequence<KeyUsage>keyUsages  );Promise<ArrayBuffer>deriveBits(AlgorithmIdentifieralgorithm,CryptoKeybaseKey,    optionalunsigned long?length = null  );Promise<CryptoKey>importKey(KeyFormatformat,    (BufferSource orJsonWebKey)keyData,AlgorithmIdentifieralgorithm,booleanextractable,sequence<KeyUsage>keyUsages  );Promise<(ArrayBuffer orJsonWebKey)>exportKey(KeyFormatformat,CryptoKeykey  );Promise<ArrayBuffer>wrapKey(KeyFormatformat,CryptoKeykey,CryptoKeywrappingKey,AlgorithmIdentifierwrapAlgorithm  );Promise<CryptoKey>unwrapKey(KeyFormatformat,BufferSourcewrappedKey,CryptoKeyunwrappingKey,AlgorithmIdentifierunwrapAlgorithm,AlgorithmIdentifierunwrappedKeyAlgorithm,booleanextractable,sequence<KeyUsage>keyUsages  );};
Note

TheSubtleCrypto interface 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 asAES 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.1Data Types

KeyFormat
Specifies a serialization format for a key. Therecognized key format values are:
raw
An unformatted sequence of bytes. Intended for secret keys.
pkcs8
The DER encoding of the PrivateKeyInfo structure from [RFC5208].
spki
The DER encoding of the SubjectPublicKeyInfo structure from [RFC5280].
jwk
The key is aJsonWebKey dictionary encoded as a JavaScript object

14.2Task Source

Thecrypto task source
Thistask source is used to queue tasks to resolve or reject promises created in response to calls to methods ofSubtleCrypto.
Note
This specification makes no specific requirements on the ordering of responses to calls to methods ofSubtleCrypto, neither between multiple calls, nor between calls and tasks from othertask sources. This task source is merely used toqueue a task to resolve or reject the relevant promise whenever the cryptographic operation is completed, in order toprevent race conditions.

14.3Methods and Parameters

Note

All errors are reported asynchronously by rejecting the returned Promise. This includes Web IDL type mapping errors.

14.3.1The encrypt method

Theencrypt method returns a new Promise object that will encrypt data using the specifiedAlgorithmIdentifier with the suppliedCryptoKey. It must act as follows:

  1. Letalgorithm andkey be thealgorithm andkey parameters passed to theencrypt() method, respectively.

  2. Letdata be the result ofgetting a copy of the bytes held by thedata parameter passed to theencrypt() method.

  3. LetnormalizedAlgorithm be the result ofnormalizing an algorithm, withalg set toalgorithm andop set to "encrypt".

  4. If an error occurred, return a Promise rejected withnormalizedAlgorithm.

  5. Letrealm be therelevant realm ofthis.

  6. Letpromise be a new Promise.

  7. Returnpromise and perform the remaining stepsin parallel.

  8. If the following steps or referenced procedures say tothrow an error,queue a global task on thecrypto task source, givenrealm's global object, to rejectpromise with the returned error; and thenterminate the algorithm.

  9. If thename member ofnormalizedAlgorithm is not equal to thename attribute of the[[algorithm]] internal slot ofkey thenthrow anInvalidAccessError.

  10. If the[[usages]] internal slot ofkey does not contain an entry that is "encrypt", thenthrow anInvalidAccessError.

  11. Letciphertext be the result of performing the encrypt operation specified bynormalizedAlgorithm usingalgorithm andkey and withdata asplaintext.

  12. Queue a global task on thecrypto task source, givenrealm's global object, to perform the remaining steps.

  13. Letresult be the result ofcreating anArrayBuffer inrealm, containingciphertext.

  14. Resolvepromise withresult.

14.3.2The decrypt method

Thedecrypt method returns a new Promise object that will decrypt data using the specifiedAlgorithmIdentifier with the suppliedCryptoKey. It must act as follows:

  1. Letalgorithm andkey be thealgorithm andkey parameters passed to thedecrypt() method, respectively.

  2. Letdata be the result ofgetting a copy of the bytes held by thedata parameter passed to thedecrypt() method.

  3. LetnormalizedAlgorithm be the result ofnormalizing an algorithm, withalg set toalgorithm andop set to "decrypt".

  4. If an error occurred, return a Promise rejected withnormalizedAlgorithm.

  5. Letrealm be therelevant realm ofthis.

  6. Letpromise be a new Promise.

  7. Returnpromise and perform the remaining stepsin parallel.

  8. If the following steps or referenced procedures say tothrow an error,queue a global task on thecrypto task source, givenrealm's global object, to rejectpromise with the returned error; and thenterminate the algorithm.

  9. If thename member ofnormalizedAlgorithm is not equal to thename attribute of the[[algorithm]] internal slot ofkey thenthrow anInvalidAccessError.

  10. If the[[usages]] internal slot ofkey does not contain an entry that is "decrypt", thenthrow anInvalidAccessError.

  11. Letplaintext be the result of performing the decrypt operation specified bynormalizedAlgorithm usingkey andalgorithm and withdata asciphertext.

  12. Queue a global task on thecrypto task source, givenrealm's global object, to perform the remaining steps.

  13. Letresult be the result ofcreating anArrayBuffer inrealm, containingplaintext.

  14. Resolvepromise withresult.

14.3.3The sign method

Thesign method returns a new Promise object that will sign data using the specifiedAlgorithmIdentifier with the suppliedCryptoKey. It must act as follows:

  1. Letalgorithm andkey be thealgorithm andkey parameters passed to thesign() method, respectively.

  2. Letdata be the result ofgetting a copy of the bytes held by thedata parameter passed to thesign() method.

  3. LetnormalizedAlgorithm be the result ofnormalizing an algorithm, withalg set toalgorithm andop set to "sign".

  4. If an error occurred, return a Promise rejected withnormalizedAlgorithm.

  5. Letrealm be therelevant realm ofthis.

  6. Letpromise be a new Promise.

  7. Returnpromise and perform the remaining stepsin parallel.

  8. If the following steps or referenced procedures say tothrow an error,queue a global task on thecrypto task source, givenrealm's global object, to rejectpromise with the returned error; and thenterminate the algorithm.

  9. If thename member ofnormalizedAlgorithm is not equal to thename attribute of the[[algorithm]] internal slot ofkey thenthrow anInvalidAccessError.

  10. If the[[usages]] internal slot ofkey does not contain an entry that is "sign", thenthrow anInvalidAccessError.

  11. Letsignature be the result of performing the sign operation specified bynormalizedAlgorithm usingkey andalgorithm and withdata asmessage.

  12. Queue a global task on thecrypto task source, givenrealm's global object, to perform the remaining steps.

  13. Letresult be the result ofcreating anArrayBuffer inrealm, containingsignature.

  14. Resolvepromise withresult.

14.3.4The verify method

Theverify method returns a new Promise object that will verify data using the specifiedAlgorithmIdentifier with the suppliedCryptoKey. It must act as follows:

  1. Letalgorithm andkey be thealgorithm andkey parameters passed to theverify() method, respectively.

  2. Letsignature be the result ofgetting a copy of the bytes held by thesignature parameter passed to theverify() method.

  3. Letdata be the result ofgetting a copy of the bytes held by thedata parameter passed to theverify() method.

  4. LetnormalizedAlgorithm be the result ofnormalizing an algorithm, withalg set toalgorithm andop set to "verify".

  5. If an error occurred, return a Promise rejected withnormalizedAlgorithm.

  6. Letrealm be therelevant realm ofthis.

  7. Letpromise be a new Promise.

  8. Returnpromise and perform the remaining stepsin parallel.

  9. If the following steps or referenced procedures say tothrow an error,queue a global task on thecrypto task source, givenrealm's global object, to rejectpromise with the returned error; and thenterminate the algorithm.

  10. If thename member ofnormalizedAlgorithm is not equal to thename attribute of the[[algorithm]] internal slot ofkey thenthrow anInvalidAccessError.

  11. If the[[usages]] internal slot ofkey does not contain an entry that is "verify", thenthrow anInvalidAccessError.

  12. Letresult be the result of performing the verify operation specified bynormalizedAlgorithm usingkey,algorithm andsignature and withdata asmessage.

  13. Queue a global task on thecrypto task source, givenrealm's global object, to perform the remaining steps.

  14. Resolvepromise withresult.

14.3.5The digest method

Thedigest method returns a new Promise object that will digest data using the specifiedAlgorithmIdentifier. It must act as follows:

  1. Letalgorithm be thealgorithm parameter passed to thedigest() method.

  2. Letdata be the result ofgetting a copy of the bytes held by thedata parameter passed to thedigest() method.

  3. LetnormalizedAlgorithm be the result ofnormalizing an algorithm, withalg set toalgorithm andop set to "digest".

  4. If an error occurred, return a Promise rejected withnormalizedAlgorithm.

  5. Letrealm be therelevant realm ofthis.

  6. Letpromise be a new Promise.

  7. Returnpromise and perform the remaining stepsin parallel.

  8. If the following steps or referenced procedures say tothrow an error,queue a global task on thecrypto task source, givenrealm's global object, to rejectpromise with the returned error; and thenterminate the algorithm.

  9. Letdigest be the result of performing the digest operation specified bynormalizedAlgorithm usingalgorithm, withdata asmessage.

  10. Queue a global task on thecrypto task source, givenrealm's global object, to perform the remaining steps.

  11. Letresult be the result ofcreating anArrayBuffer inrealm, containingdigest.

  12. Resolvepromise withresult.

14.3.6The generateKey method

When invoked,generateKeyMUST perform the following steps:

  1. Letalgorithm,extractable andusages be thealgorithm,extractable andkeyUsages parameters passed to thegenerateKey() method, respectively.

  2. LetnormalizedAlgorithm be the result ofnormalizing an algorithm, withalg set toalgorithm andop set to "generateKey".

  3. If an error occurred, return a Promise rejected withnormalizedAlgorithm.

  4. Letrealm be therelevant realm ofthis.

  5. Letpromise be a new Promise.

  6. Returnpromise and perform the remaining stepsin parallel.

  7. If the following steps or referenced procedures say tothrow an error,queue a global task on thecrypto task source, givenrealm's global object, to rejectpromise with the returned error; and thenterminate the algorithm.

  8. Letresult be the result of performing the generate key operation specified bynormalizedAlgorithm usingalgorithm,extractable andusages.

  9. Ifresult is aCryptoKey object:

    If the[[type]] internal slot ofresult is "secret" or "private" andusages is empty, thenthrow aSyntaxError.

    Ifresult is aCryptoKeyPair object:

    If the[[usages]] internal slot of theprivateKey attribute ofresult is the empty sequence, thenthrow aSyntaxError.

  10. Queue a global task on thecrypto task source, givenrealm's global object, to perform the remaining steps.

  11. Letresult be the result of convertingresult to an ECMAScript Object inrealm, as defined by [WebIDL].

  12. Resolvepromise withresult.

14.3.7The deriveKey method

When invoked,deriveKeyMUST perform the following steps:

  1. Letalgorithm,baseKey,derivedKeyType,extractable andusages be thealgorithm,baseKey,derivedKeyType,extractable andkeyUsages parameters passed to thederiveKey() method, respectively.

  2. LetnormalizedAlgorithm be the result ofnormalizing an algorithm, withalg set toalgorithm andop set to "deriveBits".

  3. If an error occurred, return a Promise rejected withnormalizedAlgorithm.

  4. LetnormalizedDerivedKeyAlgorithmImport be the result ofnormalizing an algorithm, withalg set toderivedKeyType andop set to "importKey".

  5. If an error occurred, return a Promise rejected withnormalizedDerivedKeyAlgorithmImport.

  6. LetnormalizedDerivedKeyAlgorithmLength be the result ofnormalizing an algorithm, withalg set toderivedKeyType andop set to "get key length".

  7. If an error occurred, return a Promise rejected withnormalizedDerivedKeyAlgorithmLength.

  8. Letrealm be therelevant realm ofthis.

  9. Letpromise be a new Promise.

  10. Returnpromise and perform the remaining stepsin parallel.

  11. If the following steps or referenced procedures say tothrow an error,queue a global task on thecrypto task source, givenrealm's global object, to rejectpromise with the returned error; and thenterminate the algorithm.

  12. If thename member ofnormalizedAlgorithm is not equal to thename attribute of the[[algorithm]] internal slot ofbaseKey thenthrow anInvalidAccessError.

  13. If the[[usages]] internal slot ofbaseKey does not contain an entry that is "deriveKey", thenthrow anInvalidAccessError.

  14. Letlength be the result of performing the get key length algorithm specified bynormalizedDerivedKeyAlgorithmLength usingderivedKeyType.

  15. Letsecret be the result of performing the derive bits operation specified bynormalizedAlgorithm usingkey,algorithm andlength.

  16. Letresult be the result of performing the import key operation specified bynormalizedDerivedKeyAlgorithmImport using "raw" asformat,secret askeyData,derivedKeyType asalgorithm and usingextractable andusages.

  17. If the[[type]] internal slot ofresult is "secret" or "private" andusages is empty, thenthrow aSyntaxError.

  18. Set the[[extractable]] internal slot ofresult toextractable.

  19. Set the[[usages]] internal slot ofresult to thenormalized value ofusages.

  20. Queue a global task on thecrypto task source, givenrealm's global object, to perform the remaining steps.

  21. Letresult be the result of convertingresult to an ECMAScript Object inrealm, as defined by [WebIDL].

  22. Resolvepromise withresult.

14.3.8The deriveBits method

When invoked,deriveBitsMUST perform the following steps:

  1. Letalgorithm,baseKey andlength, be thealgorithm,baseKey andlength parameters passed to thederiveBits() method, respectively.

  2. LetnormalizedAlgorithm be the result ofnormalizing an algorithm, withalg set toalgorithm andop set to "deriveBits".

  3. If an error occurred, return a Promise rejected withnormalizedAlgorithm.

  4. Letrealm be therelevant realm ofthis.

  5. Letpromise be a new Promise.

  6. Returnpromise and perform the remaining stepsin parallel.

  7. If the following steps or referenced procedures say tothrow an error,queue a global task on thecrypto task source, givenrealm's global object, to rejectpromise with the returned error; and thenterminate the algorithm.

  8. If thename member ofnormalizedAlgorithm is not equal to thename attribute of the[[algorithm]] internal slot ofbaseKey thenthrow anInvalidAccessError.

  9. If the[[usages]] internal slot ofbaseKey does not contain an entry that is "deriveBits", thenthrow anInvalidAccessError.

  10. Letbits be the result of performing the derive bits operation specified bynormalizedAlgorithm usingbaseKey,algorithm andlength.

  11. Queue a global task on thecrypto task source, givenrealm's global object, to perform the remaining steps.

  12. Letresult be the result ofcreating anArrayBuffer inrealm, containingbits.

  13. Resolvepromise withresult.

14.3.9The importKey method

When invoked, theimportKey methodMUST perform the following steps:

  1. Letformat,algorithm,extractable andusages, be theformat,algorithm,extractable andkeyUsages parameters passed to theimportKey() method, respectively.

  2. Ifformat is equal to the string "raw", "pkcs8", or "spki":
    1. If thekeyData parameter passed to theimportKey() method is aJsonWebKey dictionary,throw aTypeError.

    2. LetkeyData be the result ofgetting a copy of the bytes held by thekeyData parameter passed to theimportKey() method.

    Ifformat is equal to the string "jwk":
    1. If thekeyData parameter passed to theimportKey() method is not aJsonWebKey dictionary,throw aTypeError.

    2. LetkeyData be thekeyData parameter passed to theimportKey() method.

  3. LetnormalizedAlgorithm be the result ofnormalizing an algorithm, withalg set toalgorithm andop set to "importKey".

  4. If an error occurred, return a Promise rejected withnormalizedAlgorithm.

  5. Letrealm be therelevant realm ofthis.

  6. Letpromise be a new Promise.

  7. Returnpromise and perform the remaining stepsin parallel.

  8. If the following steps or referenced procedures say tothrow an error,queue a global task on thecrypto task source, givenrealm's global object, to rejectpromise with the returned error; and thenterminate the algorithm.

  9. Letresult be theCryptoKey object that results from performing the import key operation specified bynormalizedAlgorithm usingkeyData,algorithm,format,extractable andusages.

  10. If the[[type]] internal slot ofresult is "secret" or "private" andusages is empty, thenthrow aSyntaxError.

  11. Set the[[extractable]] internal slot ofresult toextractable.

  12. Set the[[usages]] internal slot ofresult to thenormalized value ofusages.

  13. Queue a global task on thecrypto task source, givenrealm's global object, to perform the remaining steps.

  14. Letresult be the result of convertingresult to an ECMAScript Object inrealm, as defined by [WebIDL].

  15. Resolvepromise withresult.

Note

Support of "raw" key formats is encouraged for interoperability. Web developers should consult the test-suite for detailed information on implementations support of other key formats.

Note

For structured key formats, "spki", "pkcs8" and "jwk", fields that are not explicitly referred to in the key import procedures for an algorithm are ignored.

14.3.10The exportKey method

When invoked, theexportKey methodMUST perform the following steps:

  1. Letformat andkey be theformat andkey parameters passed to theexportKey() method, respectively.

  2. Letrealm be therelevant realm ofthis.

  3. Letpromise be a new Promise.

  4. Returnpromise and perform the remaining stepsin parallel.

  5. If the following steps or referenced procedures say tothrow an error,queue a global task on thecrypto task source, givenrealm's global object, to rejectpromise with the returned error; and thenterminate the algorithm.

  6. If thename member of the[[algorithm]] internal slot ofkey does not identify aregistered algorithm that supports the export key operation, thenthrow aNotSupportedError.

  7. If the[[extractable]] internal slot ofkey is false, thenthrow anInvalidAccessError.

  8. Letresult be the result of performing the export key operation specified by the[[algorithm]] internal slot ofkey usingkey andformat.

  9. Queue a global task on thecrypto task source, givenrealm's global object, to perform the remaining steps.

  10. Ifformat is equal to the strings "raw", "pkcs8", or "spki":
    Letresult be the result ofcreating anArrayBuffer inrealm, containingresult.
    Ifformat is equal to the string "jwk":
    Letresult be the result of convertingresult to an ECMAScript Object inrealm, as defined by [WebIDL].
  11. Resolvepromise withresult.

Note

Support of "raw" key formats is encouraged for interoperability. Web developers should consult the test-suite for detailed information on implementations support of other key formats.

14.3.11The wrapKey method

When invoked, thewrapKey methodMUST perform the following steps:

  1. Letformat,key,wrappingKey andalgorithm be theformat,key,wrappingKey andwrapAlgorithm parameters passed to thewrapKey() method, respectively.

  2. LetnormalizedAlgorithm be the result ofnormalizing an algorithm, withalg set toalgorithm andop set to "wrapKey".

  3. If an error occurred, letnormalizedAlgorithm be the result ofnormalizing an algorithm, withalg set toalgorithm andop set to "encrypt".

  4. If an error occurred, return a Promise rejected withnormalizedAlgorithm.

  5. Letrealm be therelevant realm ofthis.

  6. Letpromise be a new Promise.

  7. Returnpromise and perform the remaining stepsin parallel.

  8. If the following steps or referenced procedures say tothrow an error,queue a global task on thecrypto task source, givenrealm's global object, to rejectpromise with the returned error; and thenterminate the algorithm.

  9. If thename member ofnormalizedAlgorithm is not equal to thename attribute of the[[algorithm]] internal slot ofwrappingKey thenthrow anInvalidAccessError.

  10. If the[[usages]] internal slot ofwrappingKey does not contain an entry that is "wrapKey", thenthrow anInvalidAccessError.

  11. If the algorithm identified by the[[algorithm]] internal slot ofkey does not support the export key operation, thenthrow aNotSupportedError.

  12. If the[[extractable]] internal slot ofkey is false, thenthrow anInvalidAccessError.

    Note

    Because the wrapKey method effectively exports the key, only keys marked as extractable may be wrapped. In particular, this means that this API cannot create a wrapped JWK key that is marked as non-extractable using theext JWK member.

    However, the unwrapKey methoddoes support theext JWK member, so that wrapped non-extractable keys created elsewhere, for example by a server, can be unwrapped using this API.

  13. LetexportedKey be the result of performing the export key operation specified by the[[algorithm]] internal slot ofkey usingkey andformat.

  14. Ifformat is equal to the strings "raw", "pkcs8", or "spki":
    Letbytes beexportedKey.
    Ifformat is equal to the string "jwk":
    1. Letjson be the result of representingexportedKey as a UTF-16 string conforming to the JSON grammar; for example, by executing theJSON.stringify algorithm specified in [ECMA-262] in the context of a new global object.

    2. Letbytes be the result ofUTF-8 encodingjson.

    Note

    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. This is why JSON.stringify is not normatively required, as otherwise it would prohibit implementations from introducing added padding.

  15. IfnormalizedAlgorithm supports the wrap key operation:

    Letresult be the result of performing the wrap key operation specified bynormalizedAlgorithm usingalgorithm,wrappingKey askey andbytes asplaintext.

    Otherwise, ifnormalizedAlgorithm supports the encrypt operation:

    Letresult be the result of performing the encrypt operation specified bynormalizedAlgorithm usingalgorithm,wrappingKey askey andbytes asplaintext.

    Otherwise:
    throw aNotSupportedError.
  16. Queue a global task on thecrypto task source, givenrealm's global object, to perform the remaining steps.

  17. Letresult be the result ofcreating anArrayBuffer inrealm, containingresult.

  18. Resolvepromise withresult.

Note

Support of "raw" key formats is encouraged for interoperability. Web developers should consult the test-suite for detailed information on implementations support of other key formats.

14.3.12The unwrapKey method

When invoked, theunwrapKey methodMUST perform the following steps:

  1. Letformat,unwrappingKey,algorithm,unwrappedKeyAlgorithm,extractable andusages, be theformat,unwrappingKey,unwrapAlgorithm,unwrappedKeyAlgorithm,extractable andkeyUsages parameters passed to theunwrapKey() method, respectively.

  2. LetwrappedKey be the result ofgetting a copy of the bytes held by thewrappedKey parameter passed to theunwrapKey() method.

  3. LetnormalizedAlgorithm be the result ofnormalizing an algorithm, withalg set toalgorithm andop set to "unwrapKey".

  4. If an error occurred, letnormalizedAlgorithm be the result ofnormalizing an algorithm, withalg set toalgorithm andop set to "decrypt".

  5. If an error occurred, return a Promise rejected withnormalizedAlgorithm.

  6. LetnormalizedKeyAlgorithm be the result ofnormalizing an algorithm, withalg set tounwrappedKeyAlgorithm andop set to "importKey".

  7. If an error occurred, return a Promise rejected withnormalizedKeyAlgorithm.

  8. Letrealm be therelevant realm ofthis.

  9. Letpromise be a new Promise.

  10. Returnpromise and perform the remaining stepsin parallel.

  11. If the following steps or referenced procedures say tothrow an error,queue a global task on thecrypto task source, givenrealm's global object, to rejectpromise with the returned error; and thenterminate the algorithm.

  12. If thename member ofnormalizedAlgorithm is not equal to thename attribute of the[[algorithm]] internal slot ofunwrappingKey thenthrow anInvalidAccessError.

  13. If the[[usages]] internal slot ofunwrappingKey does not contain an entry that is "unwrapKey", thenthrow anInvalidAccessError.

  14. IfnormalizedAlgorithm supports an unwrap key operation:
    Letbytes be the result of performing the unwrap key operation specified bynormalizedAlgorithm usingalgorithm,unwrappingKey askey andwrappedKey asciphertext.
    Otherwise, ifnormalizedAlgorithm supports a decrypt operation:
    Letbytes be the result of performing the decrypt operation specified bynormalizedAlgorithm usingalgorithm,unwrappingKey askey andwrappedKey asciphertext.
    Otherwise:
    throw aNotSupportedError.
  15. Ifformat is equal to the strings "raw", "pkcs8", or "spki":
    Letkey bebytes.
    Ifformat is equal to the string "jwk":
    Letkey be the result of executing theparse a JWK algorithm, withbytes as thedata to be parsed.
  16. Letresult be the result of performing the import key operation specified bynormalizedKeyAlgorithm usingunwrappedKeyAlgorithm asalgorithm,format,usages andextractable and withkey askeyData.

  17. If the[[type]] internal slot ofresult is "secret" or "private" andusages is empty, thenthrow aSyntaxError.

  18. Set the[[extractable]] internal slot ofresult toextractable.

  19. Set the[[usages]] internal slot ofresult to thenormalized value ofusages.

  20. Queue a global task on thecrypto task source, givenrealm's global object, to perform the remaining steps.

  21. Letresult be the result of convertingresult to an ECMAScript Object inrealm, as defined by [WebIDL].

  22. Resolvepromise withresult.

Note

Support of "raw" key formats is encouraged for interoperability. Web developers should consult the test-suite for detailed information on implementations support of other key formats.

14.4Exceptions

The methods of theSubtleCrypto interface return errors by rejecting the returned promise with a predefined exception defined in ECMAScript [ECMA-262] orDOMException. The following predefined exceptions are used:TypeError. The following DOMException types from [DOM] are used:

NameDescription
NotSupportedErrorThe algorithm is not supported
SyntaxErrorA required parameter was missing or out-of-range
InvalidAccessErrorThe requested operation is not valid for the provided key
DataErrorData provided to an operation does not meet requirements
OperationErrorThe operation failed for an operation-specific reason

When this specification says tothrow an error, the user agent must throw an error as described in [WebIDL]. When this occurs in a sub-algorithm, this results in termination of execution of the sub-algorithm and all ancestor algorithms until one is reached that explicitly describes procedures for catching exceptions. The error object thrown shall be associated with therelevant realm ofthis.

15.JsonWebKey dictionary

WebIDLdictionaryRsaOtherPrimesInfo {  // The following fields are defined in Section 6.3.2.7 of JSON Web AlgorithmsDOMStringr;DOMStringd;DOMStringt;};dictionaryJsonWebKey {  // The following fields are defined in Section 3.1 of JSON Web KeyDOMStringkty;DOMStringuse;sequence<DOMString>key_ops;DOMStringalg;  // The following fields are defined in JSON Web Key Parameters Registrationbooleanext;  // The following fields are defined in Section 6 of JSON Web AlgorithmsDOMStringcrv;DOMStringx;DOMStringy;DOMStringd;DOMStringn;DOMStringe;DOMStringp;DOMStringq;DOMStringdp;DOMStringdq;DOMStringqi;sequence<RsaOtherPrimesInfo>oth;DOMStringk;};

TheJsonWebKey dictionary provides a way to represent and exchange cryptographic keys represented by the JSON Web Key [JWK] structure, while allowing native and efficient use within Web Cryptography API applications.

The members of theRsaOtherPrimesInfo are defined in Section 6.3.2.7 of JSON Web Algorithms.

16.BigInteger

WebIDLtypedefUint8ArrayBigInteger;

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

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.CryptoKeyPair dictionary

WebIDLdictionaryCryptoKeyPair {CryptoKeypublicKey;CryptoKeyprivateKey;};

TheCryptoKeyPair dictionary represents an asymmetric key pair that is comprised of both public (publicKey) and private (privateKey) keys.

18.Algorithms

18.1Overview

This section is non-normative.

In addition to providing a common interface to perform cryptographic operations, by way of theSubtleCrypto interface, this specification also provides descriptions for a variety of algorithms that authors may wish to use and that User Agents may choose to implement. This includes a selection of commonly-deployed symmetric and asymmetric algorithms, key derivation mechanisms, and methods for wrapping and unwrapping keys. Further, this specification defines a process to allow additional specifications to introduce additional cryptographic algorithms.

18.2Concepts

18.2.1Naming

Every cryptographic algorithm defined for use with the Web Cryptography APIMUST have a unique name, referred to as itsrecognized algorithm name, such that no other specification defines the same case-insensitive string for use with the Web Cryptography API.

18.2.2Supported Operations

Every cryptographic algorithm defined for use with the Web Cryptography API has a list ofsupported operations, which are a set of sub-algorithms to be invoked by theSubtleCrypto interface in order to perform the desired cryptographic operation. This specification makes use of the following operations:

  • encrypt
  • decrypt
  • sign
  • verify
  • digest
  • deriveBits
  • wrapKey
  • unwrapKey
  • generateKey
  • importKey
  • exportKey
  • get key length

If a given algorithm specification does not list a particular operation as supported, or explicitly lists an operation as not-supported, then the User AgentMUST behave as if the invocation of the sub-algorithm threw a NotSupportedError.

18.2.3Normalization

Every cryptographic algorithm defined for use with the Web Cryptography APIMUST define, for everysupported operation, the IDL type to use foralgorithm normalization, as well as the IDL type or types of the return values of the sub-algorithms.

18.3Specification Conventions

Every cryptographic algorithm definition within this specification employs the following specification conventions. A section, titled"Registration", will include therecognized algorithm name. Additionally, it includes a table, which will list each of thesupported operations as rows, identified by theOperation column. The contents of theParameters column for a given row will contain the IDL type to use foralgorithm normalization for that operation, and the contents of theResult column for that row indicate the IDL type that results from performing the supported operation.

If a conforming User Agent implements an algorithm, itMUST implement all of the supported operations andMUST return the IDL type specified.

Additionally, upon initialization, conforming User Agents must perform thedefine an algorithm steps for each of the supported operations, registering their IDL parameter type as indicated.

Unless otherwise stated, objects created by the operations defined in this specification shall be associated with therelevant realm ofthis.

18.4Algorithm Normalization

18.4.1Description

This section is non-normative.

TheAlgorithmIdentifier typedef permits algorithms to either be specified as aDOMString or an object. The usage ofDOMString is to permit authors a short-hand for noting algorithms that have no parameters (e.g. SHA-1). The usage of object is to allow anAlgorithm (or appropriate subclass) to be specified, which contains all of the associated parameters for an object.

Because of this, it's necessary to define the algorithm for converting anAlgorithmIdentifier into an appropriate dictionary that is usable with this API. This algorithm must be extensible, so as to allow new cryptographic algorithms to be added, and consistent, so that Web IDL type mapping can occur before any control is returned to the calling script, which would potentially allow the mutation of parameters or the script environment.

18.4.2Internal State Objects

This specification makes use of an internal object,supportedAlgorithms. This internal object is not exposed to applications.

Because this value is not exposed to applications, the exact type is not specified. It is only required to behave as an associative container of key/value pairs, where comparisons of keys are performed in a case-sensitive manner.

The initial contents of this internal object are as follows:

  1. For each value,v in the List ofsupported operations, set thev key of the internal objectsupportedAlgorithms to a new associative container.

18.4.3Defining an Algorithm

Thedefine an algorithm algorithm is used by specification authors to indicate how a user agent should normalize arguments for a particular algorithm. Its input is an algorithm namealg, represented as a DOMString, operation nameop, represented as a DOMString, and desired IDL dictionary typetype. The algorithm behaves as follows:

  1. LetregisteredAlgorithms be the associative container stored at theop key ofsupportedAlgorithms.
  2. Set thealg key ofregisteredAlgorithms to the IDL dictionary typetype.

18.4.4Normalizing an algorithm

Thenormalize an algorithm algorithm defines a process for coercing inputs to a targeted IDL dictionary type, after Web IDL conversion has occurred. It is designed to be extensible, to allow future specifications to define additional algorithms, as well as safe for use with Promises. Its input is an operation nameop and anAlgorithmIdentifieralg. Its output is either an IDL dictionary type or an error. It behaves as follows:

Ifalg is an instance of a DOMString:

Return the result of running thenormalize an algorithm algorithm, with thealg set to a newAlgorithm dictionary whosename attribute isalg, and with theop set toop.

Ifalg is an object:
  1. LetregisteredAlgorithms be the associative container stored at theop key ofsupportedAlgorithms.
  2. LetinitialAlg be the result of converting the ECMAScript object represented byalg to the IDL dictionary typeAlgorithm, as defined by [WebIDL].
  3. If an error occurred, return the error and terminate this algorithm.
  4. LetalgName be the value of thename attribute ofinitialAlg.
  5. IfregisteredAlgorithms contains a key that is acase-insensitive string match foralgName:
    1. SetalgName to the value of the matching key.

    2. LetdesiredType be the IDL dictionary type stored atalgName inregisteredAlgorithms.

    Otherwise:
    Return a newNotSupportedError and terminate this algorithm.
  6. LetnormalizedAlgorithm be the result of converting the ECMAScript object represented byalg to the IDL dictionary typedesiredType, as defined by [WebIDL].
  7. Set thename attribute ofnormalizedAlgorithm toalgName.
  8. If an error occurred, return the error and terminate this algorithm.
  9. Letdictionaries be a list consisting of the IDL dictionary typedesiredType and all ofdesiredType's inherited dictionaries, in order from least to most derived.
  10. For each dictionarydictionary indictionaries:

    1. For each dictionary membermember declared ondictionary, in order:

      1. Letkey be the identifier ofmember.
      2. LetidlValue be the value of the dictionary member with key name ofkey onnormalizedAlgorithm.
      3. Ifmember is of the typeBufferSource and is present:
        Set the dictionary member onnormalizedAlgorithm with key namekey to the result ofgetting a copy of the bytes held byidlValue, replacing the current value.
        Ifmember is of the typeHashAlgorithmIdentifier:
        Set the dictionary member onnormalizedAlgorithm with key namekey to the result ofnormalizing an algorithm, with thealg set toidlValue and theop set to "digest".
        Ifmember is of the typeAlgorithmIdentifier:
        Set the dictionary member onnormalizedAlgorithm with key namekey to the result ofnormalizing an algorithm, with thealg set toidlValue and theop set to the operation defined by the specification that defines the algorithm identified byalgName.
      4. If an error occurred, return the error and terminate this algorithm.
  11. ReturnnormalizedAlgorithm.

18.5Recommendations

This section is non-normative.

18.5.1For Authors

As this API is meant to be extensible, in order to keep up with future developments within cryptography, there are no algorithms that conforming user agents are required to implement. As such, authors should check to see what algorithms are currently recommended and supported by implementations.

As highlighted in theSecurity Considerations, even cryptographic algorithms that might be considered strong for one purpose may be insufficient when used with another purpose. Authors should therefore proceed with extreme caution before inventing new cryptographic protocols.

Additionally, this specification includes several algorithms which, in their default usage, can result in cryptographic vulnerabilities. While these concerns may be mitigated, such as through the combination and composition with additional algorithms provided by this specification, authors should proceed with caution and review the relevant cryptographic literature before using a given algorithm. The inclusion of algorithms within this specification is not an indicator of their suitability for any or all purpose, and instead merely serve to provide as a specification for how a conforming User Agent must implement the given algorithm, if it choses to implement the algorithm.

18.5.2For Implementers

In order to promote interoperability for developers, this specification includes a list of suggested algorithms. These are considered to be the most widely used algorithms in practice at the time of writing, and therefore provide a good starting point for initial implementations of this specification. The suggested algorithms are:

19.Algorithm Overview

This section is non-normative.

The table below contains an overview of the algorithms described within this specification, as well as the set ofSubtleCrypto methods the algorithm may be used with. In order for an algorithm to be used with a method the corresponding operation or operations, as defined in the procedures for the method, must be defined in the algorithm specification. Note that this mapping of methods to underlying operations is not one-to-one:

Note

Application developers and script authors should not interpret this table as a recommendation for the use of particular algorithms. Instead, it simply documents what methods are supported. Authors should refer to theSecurity considerations for authors section of this document to better understand the risks and concerns that may arise when using certain algorithms.

Algorithm nameencryptdecryptsignverifydigestgenerateKeyderiveKeyderiveBitsimportKeyexportKeywrapKeyunwrapKey
RSASSA-PKCS1-v1_5
RSA-PSS
RSA-OAEP
ECDSA
ECDH
Ed25519
X25519
AES-CTR
AES-CBC
AES-GCM
AES-KW
HMAC
SHA-1
SHA-256
SHA-384
SHA-512
HKDF
PBKDF2

20.RSASSA-PKCS1-v1_5

20.1Description

This section is non-normative.

The "RSASSA-PKCS1-v1_5" algorithm identifier is used to perform signing and verification using the RSASSA-PKCS1-v1_5 algorithm specified in [RFC3447] and using the SHA hash functions defined in this specification.

Other specifications may specify the use of additional hash algorithms with RSASSA-PKCS1-v1_5. Such specifications must define the digest operations for the additional hash algorithms andkey import steps andkey export steps for RSASSA-PKCS1-v1_5.

20.2Registration

Therecognized algorithm name for this algorithm is "RSASSA-PKCS1-v1_5".

OperationParametersResult
signNonebyte sequence
verifyNoneboolean
generateKeyRsaHashedKeyGenParamsCryptoKeyPair
importKeyRsaHashedImportParamsCryptoKey
exportKeyNoneobject

20.3RsaKeyGenParams dictionary

WebIDLdictionaryRsaKeyGenParams :Algorithm {  required [EnforceRange]unsigned longmodulusLength;  requiredBigIntegerpublicExponent;};

ThemodulusLength member contains the length, in bits, of the RSA modulus.

ThepublicExponent member contains the RSA public exponent.

20.4RsaHashedKeyGenParams dictionary

WebIDLdictionaryRsaHashedKeyGenParams :RsaKeyGenParams {  requiredHashAlgorithmIdentifierhash;};

Thehash member represents the hash algorithm to use.

20.5RsaKeyAlgorithm dictionary

WebIDLdictionaryRsaKeyAlgorithm :KeyAlgorithm {  requiredunsigned longmodulusLength;  requiredBigIntegerpublicExponent;};

ThemodulusLength member contains the length, in bits, of the RSA modulus.

ThepublicExponent member contains the RSA public exponent.

20.6RsaHashedKeyAlgorithm dictionary

WebIDLdictionaryRsaHashedKeyAlgorithm :RsaKeyAlgorithm {  requiredKeyAlgorithmhash;};

Thehash member describes the hash algorithm that is used with this key.

20.7RsaHashedImportParams dictionary

WebIDLdictionaryRsaHashedImportParams :Algorithm {  requiredHashAlgorithmIdentifierhash;};

Thehash member describes the hash algorithm to use.

20.8Operations

20.8.1Sign

  1. If the[[type]] internal slot ofkey is not "private", thenthrow anInvalidAccessError.

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

  3. If performing the operation results in an error, thenthrow anOperationError.

  4. Letsignature be the valueS that results from performing the operation.

  5. Returnsignature.

20.8.2Verify

  1. If the[[type]] internal slot ofkey is not "public", thenthrow anInvalidAccessError.

  2. Perform the signature verification operation defined in Section 8.2 of [RFC3447] with the key represented by the[[handle]] internal slot ofkey as the signer's RSA public key andmessage asM andsignature asS and using the hash function specified in thehash attribute of the[[algorithm]] internal slot ofkey as the Hash option for the EMSA-PKCS1-v1_5 encoding method.

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

  4. Returnresult.

20.8.3Generate Key

  1. Ifusages contains an entry which is not "sign" or "verify", thenthrow aSyntaxError.

  2. Generate an RSA key pair, as defined in [RFC3447], with RSA modulus length equal to themodulusLength attribute ofnormalizedAlgorithm and RSA public exponent equal to thepublicExponent attribute ofnormalizedAlgorithm.

  3. If generation of the key pair fails, thenthrow anOperationError.

  4. Letalgorithm be a newRsaHashedKeyAlgorithm dictionary.

  5. Set thename attribute ofalgorithm to "RSASSA-PKCS1-v1_5".

  6. Set themodulusLength attribute ofalgorithm to equal themodulusLength attribute ofnormalizedAlgorithm.

  7. Set thepublicExponent attribute ofalgorithm to equal thepublicExponent attribute ofnormalizedAlgorithm.

  8. Set thehash attribute ofalgorithm to equal thehash member ofnormalizedAlgorithm.

  9. LetpublicKey be a newCryptoKey representing the public key of the generated key pair.

  10. Set the[[type]] internal slot ofpublicKey to "public"

  11. Set the[[algorithm]] internal slot ofpublicKey toalgorithm.

  12. Set the[[extractable]] internal slot ofpublicKey to true.

  13. Set the[[usages]] internal slot ofpublicKey to be theusage intersection ofusages and[ "verify" ].

  14. LetprivateKey be a newCryptoKey representing the private key of the generated key pair.

  15. Set the[[type]] internal slot ofprivateKey to "private"

  16. Set the[[algorithm]] internal slot ofprivateKey toalgorithm.

  17. Set the[[extractable]] internal slot ofprivateKey toextractable.

  18. Set the[[usages]] internal slot ofprivateKey to be theusage intersection ofusages and[ "sign" ].

  19. Letresult be a newCryptoKeyPair dictionary.

  20. Set thepublicKey attribute ofresult to bepublicKey.

  21. Set theprivateKey attribute ofresult to beprivateKey.

  22. Returnresult.

20.8.4Import Key

  1. LetkeyData be the key data to be imported.

  2. Ifformat is "spki":
    1. Ifusages contains an entry which is not "verify", thenthrow aSyntaxError.

    2. Letspki be the result of running theparse a subjectPublicKeyInfo algorithm overkeyData.

    3. If an error occurred while parsing, thenthrow aDataError.

    4. If thealgorithm object identifier field of thealgorithm AlgorithmIdentifier field ofspki is not equal to thersaEncryption object identifier defined in [RFC3447], thenthrow aDataError.

    5. LetpublicKey be the result of performing theparse an ASN.1 structure algorithm, withdata as thesubjectPublicKeyInfo field ofspki,structure as theRSAPublicKey structure specified in Section A.1.1 of [RFC3447], andexactData set to true.

    6. If an error occurred while parsing, or it can be determined thatpublicKey is not a valid public key according to [RFC3447], thenthrow aDataError.

    7. Letkey be a newCryptoKey that represents the RSA public key identified bypublicKey.

    8. Set the[[type]] internal slot ofkey to "public"

    Ifformat is "pkcs8":
    1. Ifusages contains an entry which is not "sign" thenthrow aSyntaxError.

    2. LetprivateKeyInfo be the result of running theparse a privateKeyInfo algorithm overkeyData.

    3. If an error occurred while parsing, thenthrow aDataError.

    4. If thealgorithm object identifier field of theprivateKeyAlgorithm PrivateKeyAlgorithm field ofprivateKeyInfo is not equal to thersaEncryption object identifier defined in [RFC3447], thenthrow aDataError.

    5. LetrsaPrivateKey be the result of performing theparse an ASN.1 structure algorithm, withdata as theprivateKey field ofprivateKeyInfo,structure as theRSAPrivateKey structure specified in Section A.1.2 of [RFC3447], andexactData set to true.

    6. If an error occurred while parsing, or ifrsaPrivateKey is not a valid RSA private key according to [RFC3447], thenthrow aDataError.

    7. Letkey be a newCryptoKey that represents the RSA private key identified byrsaPrivateKey.

    8. Set the[[type]] internal slot ofkey to "private"

    Ifformat is "jwk":
    1. IfkeyData is aJsonWebKey dictionary:

      Letjwk equalkeyData.

      Otherwise:

      Throw aDataError.

    2. If thed field ofjwk is present andusages contains an entry which is not "sign", or, if thed field ofjwk is not present andusages contains an entry which is not "verify" thenthrow aSyntaxError.

    3. If thekty field ofjwk is not a case-sensitive string match to "RSA", thenthrow aDataError.

    4. Ifusages is non-empty and theuse field ofjwk is present and is not a case-sensitive string match to "sig", thenthrow aDataError.

    5. If thekey_ops field ofjwk is present, and is invalid according to the requirements of JSON Web Key [JWK] or does not contain all of the specifiedusages values, thenthrow aDataError.

    6. If theext field ofjwk is present and has the value false andextractable is true, thenthrow aDataError.

    7. Lethash be a be a string whose initial value is undefined.

    8. If thealg field ofjwk is not present:

      Lethash be undefined.

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

      Lethash be the string "SHA-1".

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

      Lethash be the string "SHA-256".

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

      Lethash be the string "SHA-384".

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

      Lethash be the string "SHA-512".

      Otherwise:
      1. Perform anykey import steps defined byother applicable specifications, passingformat,jwk and obtaininghash.

      2. If an error occurred or there are noapplicable specifications,throw aDataError.

    9. Ifhash is not undefined:
      1. LetnormalizedHash be the result ofnormalize an algorithm withalg set tohash andop set todigest.

      2. IfnormalizedHash is not equal to thehash member ofnormalizedAlgorithm,throw aDataError.

    10. If thed field ofjwk is present:
      1. Ifjwk does not meet the requirements of Section 6.3.2 of JSON Web Algorithms [JWA], thenthrow aDataError.

      2. LetprivateKey represents the RSA private key identified by interpretingjwk according to Section 6.3.2 of JSON Web Algorithms [JWA].

      3. IfprivateKey is not a valid RSA private key according to [RFC3447], thenthrow aDataError.

      4. Letkey be a newCryptoKey object that representsprivateKey.

      5. Set the[[type]] internal slot ofkey to "private"

      Otherwise:
      1. Ifjwk does not meet the requirements of Section 6.3.1 of JSON Web Algorithms [JWA], thenthrow aDataError.

      2. LetpublicKey represent the RSA public key identified by interpretingjwk according to Section 6.3.1 of JSON Web Algorithms [JWA].

      3. IfpublicKey can be determined to not be a valid RSA public key according to [RFC3447], thenthrow aDataError.

      4. Letkey be a newCryptoKey representingpublicKey.

      5. Set the[[type]] internal slot ofkey to "public"

    Otherwise:
    throw aNotSupportedError.
  3. Letalgorithm be a newRsaHashedKeyAlgorithm dictionary.

  4. Set thename attribute ofalgorithm to "RSASSA-PKCS1-v1_5"

  5. Set themodulusLength attribute ofalgorithm to the length, in bits, of the RSA public modulus.

  6. Set thepublicExponent attribute ofalgorithm to theBigInteger representation of the RSA public exponent.

  7. Set thehash attribute ofalgorithm to thehash member ofnormalizedAlgorithm.

  8. Set the[[algorithm]] internal slot ofkey toalgorithm.

  9. Returnkey.

20.8.5Export Key

  1. Letkey be the key to be exported.

  2. If the underlying cryptographic key material represented by the[[handle]] internal slot ofkey cannot be accessed, thenthrow anOperationError.

  3. Ifformat is "spki"
    1. If the[[type]] internal slot ofkey is not "public", thenthrow anInvalidAccessError.

    2. Letdata be an instance of theSubjectPublicKeyInfo ASN.1 structure defined in [RFC5280] with the following properties:

      • Set thealgorithm field to anAlgorithmIdentifier ASN.1 type with the following properties:

        • Set thealgorithm field to the OIDrsaEncryption defined in [RFC3447].

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

      • Set thesubjectPublicKey field to the result of DER-encoding anRSAPublicKey ASN.1 type, as defined in [RFC3447], Appendix A.1.1, that represents the RSA public key represented by the[[handle]] internal slot ofkey

    3. Letresult be the result of DER-encodingdata.

    Ifformat is "pkcs8":
    1. If the[[type]] internal slot ofkey is not "private", thenthrow anInvalidAccessError.

    2. Letdata be an instance of thePrivateKeyInfo ASN.1 structure defined in [RFC5208] with the following properties:

      • Set theversion field to0.

      • Set theprivateKeyAlgorithm field to aPrivateKeyAlgorithmIdentifier ASN.1 type with the following properties:

        • Set thealgorithm field to the OIDrsaEncryption defined in [RFC3447].

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

      • Set theprivateKey field to the result of DER-encoding anRSAPrivateKey ASN.1 type, as defined in [RFC3447], Appendix A.1.2, that represents the RSA private key represented by the[[handle]] internal slot ofkey

        Note
        [RFC5208] specifies that the encoding of this field should beBER encoded in Section 5 (as a "for example"). However, to avoid requiring WebCrypto implementations support BER-encoding and BER-decoding, onlyDER encodings are produced or accepted.
    3. Letresult be the result of DER-encodingdata.

    Ifformat is "jwk":
    1. Letjwk be a newJsonWebKey dictionary.

    2. Set thekty attribute ofjwk to the string "RSA".

    3. Lethash be thename attribute of thehash attribute of the[[algorithm]] internal slot ofkey.

    4. Ifhash is "SHA-1":

      Set thealg attribute ofjwk to the string "RS1".

      Ifhash is "SHA-256":

      Set thealg attribute ofjwk to the string "RS256".

      Ifhash is "SHA-384":

      Set thealg attribute ofjwk to the string "RS384".

      Ifhash is "SHA-512":

      Set thealg attribute ofjwk to the string "RS512".

      Otherwise:
      1. Perform anykey export steps defined byother applicable specifications, passingformat,key and obtainingalg.

      2. If an error occurred or there are noapplicable specifications,throw aNotSupportedError.

      3. Set thealg attribute ofjwk toalg.

    5. Set the attributesn ande ofjwk according to the corresponding definitions in JSON Web Algorithms [JWA], Section 6.3.1.

    6. If the[[type]] internal slot ofkey is "private":
      1. Set the attributes namedd,p,q,dp,dq, andqi ofjwk according to the corresponding definitions in JSON Web Algorithms [JWA], Section 6.3.2.

      2. If the underlying RSA private key represented by the[[handle]] internal slot ofkey is represented by more than two primes, set the attribute namedoth ofjwk according to the corresponding definition in JSON Web Algorithms [JWA], Section 6.3.2.7

    7. Set thekey_ops attribute ofjwk to theusages attribute ofkey.

    8. Set theext attribute ofjwk to the[[extractable]] internal slot ofkey.

    9. Letresult bejwk.

    Otherwise

    throw aNotSupportedError.

  4. Returnresult.

21.RSA-PSS

21.1Description

This section is non-normative.

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

Other specifications may specify the use of additional hash algorithms with RSASSA-PSS. Such specifications must define the digest operation for the additional hash algorithms andkey import steps andkey export steps for RSASSA-PSS.

21.2Registration

Therecognized algorithm name for this algorithm is "RSA-PSS".

OperationParametersResult
signRsaPssParamsbyte sequence
verifyRsaPssParamsboolean
generateKeyRsaHashedKeyGenParamsCryptoKeyPair
importKeyRsaHashedImportParamsCryptoKey
exportKeyNoneobject

21.3RsaPssParams dictionary

WebIDLdictionaryRsaPssParams :Algorithm {  required [EnforceRange]unsigned longsaltLength;};

ThesaltLength member represents the desired length of the random salt in bytes.

21.4Operations

21.4.1Sign

  1. If the[[type]] internal slot ofkey is not "private", thenthrow anInvalidAccessError.

  2. Perform the signature generation operation defined in Section 8.1 of [RFC3447] with the key represented by the[[handle]] internal slot ofkey as the signer's private key,K, andmessage as the message to be signed,M, and using the hash function specified by thehash attribute of the[[algorithm]] internal slot ofkey as the Hash option, MGF1 (defined in Section B.2.1 of [RFC3447]) as the MGF option and thesaltLength member ofnormalizedAlgorithm as the salt length option for the EMSA-PSS-ENCODE operation.

  3. If performing the operation results in an error, thenthrow anOperationError.

  4. Letsignature be the signature, S, that results from performing the operation.

  5. Returnsignature.

21.4.2Verify

  1. If the[[type]] internal slot ofkey is not "public", thenthrow anInvalidAccessError.

  2. Perform the signature verification operation defined in Section 8.1 of [RFC3447] with the key represented by the[[handle]] internal slot ofkey as the signer's RSA public key andmessage asM andsignature asS and using the hash function specified by thehash attribute of the[[algorithm]] internal slot ofkey as the Hash option, MGF1 (defined in Section B.2.1 of [RFC3447]) as the MGF option and thesaltLength member ofnormalizedAlgorithm as the salt length option for the EMSA-PSS-VERIFY operation.

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

21.4.3Generate Key

  1. Ifusages contains an entry which is not "sign" or "verify", thenthrow aSyntaxError.

  2. Generate an RSA key pair, as defined in [RFC3447], with RSA modulus length equal to themodulusLength member ofnormalizedAlgorithm and RSA public exponent equal to thepublicExponent member ofnormalizedAlgorithm.

  3. If performing the operation results in an error, thenthrow anOperationError.

  4. Letalgorithm be a newRsaHashedKeyAlgorithm dictionary.

  5. Set thename attribute ofalgorithm to "RSA-PSS".

  6. Set themodulusLength attribute ofalgorithm to equal themodulusLength member ofnormalizedAlgorithm.

  7. Set thepublicExponent attribute ofalgorithm to equal thepublicExponent member ofnormalizedAlgorithm.

  8. Set thehash attribute ofalgorithm to equal thehash member ofnormalizedAlgorithm.

  9. LetpublicKey be a newCryptoKey representing the public key of the generated key pair.

  10. Set the[[type]] internal slot ofpublicKey to "public"

  11. Set the[[algorithm]] internal slot ofpublicKey toalgorithm.

  12. Set the[[extractable]] internal slot ofpublicKey to true.

  13. Set the[[usages]] internal slot ofpublicKey to be theusage intersection ofusages and[ "verify" ].

  14. LetprivateKey be a newCryptoKey representing the private key of the generated key pair.

  15. Set the[[type]] internal slot ofprivateKey to "private"

  16. Set the[[algorithm]] internal slot ofprivateKey toalgorithm.

  17. Set the[[extractable]] internal slot ofprivateKey toextractable.

  18. Set the[[usages]] internal slot ofprivateKey to be theusage intersection ofusages and[ "sign" ].

  19. Letresult be a newCryptoKeyPair dictionary.

  20. Set thepublicKey attribute ofresult topublicKey.

  21. Set theprivateKey attribute ofresult toprivateKey.

  22. Returnresult.

21.4.4Import Key

  1. LetkeyData be the key data to be imported.

  2. Ifformat is "spki":
    1. Ifusages contains an entry which is not "verify" thenthrow aSyntaxError.

    2. Letspki be the result of running theparse a subjectPublicKeyInfo algorithm overkeyData.

    3. If an error occurred while parsing, thenthrow aDataError.

    4. If thealgorithm object identifier field of thealgorithm AlgorithmIdentifier field ofspki is not equal to thersaEncryption object identifier defined in [RFC3447], thenthrow aDataError.

    5. LetpublicKey be the result of performing theparse an ASN.1 structure algorithm, withdata as thesubjectPublicKeyInfo field ofspki,structure as theRSAPublicKey structure specified in Section A.1.1 of [RFC3447], andexactData set to true.

    6. If an error occurred while parsing, or it can be determined thatpublicKey is not a valid public key according to [RFC3447], thenthrow aDataError.

    7. Letkey be a newCryptoKey that represents the RSA public key identified bypublicKey.

    8. Set the[[type]] internal slot ofkey to "public"

    Ifformat is "pkcs8":
    1. Ifusages contains an entry which is not "sign" thenthrow aSyntaxError.

    2. LetprivateKeyInfo be the result of running theparse a privateKeyInfo algorithm overkeyData.

    3. If an error occurred while parsing, thenthrow aDataError.

    4. If thealgorithm object identifier field of theprivateKeyAlgorithm PrivateKeyAlgorithm field ofprivateKeyInfo is not equal to thersaEncryption object identifier defined in [RFC3447], thenthrow aDataError.

    5. LetrsaPrivateKey be the result of performing theparse an ASN.1 structure algorithm, withdata as theprivateKey field ofprivateKeyInfo,structure as theRSAPrivateKey structure specified in Section A.1.2 of [RFC3447], andexactData set to true.

    6. If an error occurred while parsing, or ifrsaPrivateKey is not a valid RSA private key according to [RFC3447], thenthrow aDataError.

    7. Letkey be a newCryptoKey that represents the RSA private key identified byrsaPrivateKey.

    8. Set the[[type]] internal slot ofkey to "private"

    Ifformat is "jwk":
    1. IfkeyData is aJsonWebKey dictionary:

      Letjwk equalkeyData.

      Otherwise:

      throw aDataError.

    2. If thed field ofjwk is present andusages contains an entry which is not "sign", or, if thed field ofjwk is not present andusages contains an entry which is not "verify" thenthrow aSyntaxError.

    3. If thekty field ofjwk is not a case-sensitive string match to "RSA", thenthrow aDataError.

    4. Ifusages is non-empty and theuse field ofjwk is present and is not a case-sensitive string match to "sig", thenthrow aDataError.

    5. If thekey_ops field ofjwk is present, and is invalid according to the requirements of JSON Web Key [JWK] or does not contain all of the specifiedusages values, thenthrow aDataError.

    6. If theext field ofjwk is present and has the value false andextractable is true, thenthrow aDataError.

    7. If thealg field ofjwk is not present:

      Lethash be undefined.

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

      Lethash be the string "SHA-1".

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

      Lethash be the string "SHA-256".

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

      Lethash be the string "SHA-384".

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

      Lethash be the string "SHA-512".

      Otherwise:
      1. Perform anykey import steps defined byother applicable specifications, passingformat,jwk and obtaininghash.

      2. If an error occurred or there are noapplicable specifications,throw aDataError.

    8. Ifhash is not undefined:
      1. LetnormalizedHash be the result ofnormalize an algorithm withalg set tohash andop set todigest.

      2. IfnormalizedHash is not equal to thehash member ofnormalizedAlgorithm,throw aDataError.

    9. If thed field ofjwk is present:
      1. Ifjwk does not meet the requirements of Section 6.3.2 of JSON Web Algorithms [JWA], thenthrow aDataError.

      2. LetprivateKey represent the RSA private key identified by interpretingjwk according to Section 6.3.2 of JSON Web Algorithms [JWA].

      3. IfprivateKey can be determined to not be a valid RSA private key according to [RFC3447], thenthrow aDataError.

      4. Letkey be a newCryptoKey representingprivateKey.

      5. Set the[[type]] internal slot ofkey to "private"

      Otherwise:
      1. Ifjwk does not meet the requirements of Section 6.3.1 of JSON Web Algorithms [JWA], thenthrow aDataError.

      2. LetpublicKey represent the RSA public key identified by interpretingjwk according to Section 6.3.1 of JSON Web Algorithms [JWA].

      3. IfpublicKey can be determined to not be a valid RSA public key according to [RFC3447], thenthrow aDataError.

      4. Letkey be a newCryptoKey representingpublicKey.

      5. Set the[[type]] internal slot ofkey to "public"

    Otherwise:
    throw aNotSupportedError.
  3. Letalgorithm be a newRsaHashedKeyAlgorithm dictionary.

  4. Set thename attribute ofalgorithm to "RSA-PSS"

  5. Set themodulusLength attribute ofalgorithm to the length, in bits, of the RSA public modulus.

  6. Set thepublicExponent attribute ofalgorithm to theBigInteger representation of the RSA public exponent.

  7. Set thehash attribute ofalgorithm to thehash member ofnormalizedAlgorithm.

  8. Set the[[algorithm]] internal slot ofkey toalgorithm

  9. Returnkey.

21.4.5Export Key

  1. Letkey be the key to be exported.

  2. If the underlying cryptographic key material represented by the[[handle]] internal slot ofkey cannot be accessed, thenthrow anOperationError.

  3. Ifformat is "spki"
    1. If the[[type]] internal slot ofkey is not "public", thenthrow anInvalidAccessError.

    2. Letdata be an instance of theSubjectPublicKeyInfo ASN.1 structure defined in [RFC5280] with the following properties:

      • Set thealgorithm field to anAlgorithmIdentifier ASN.1 type with the following properties:

        • Set thealgorithm field to the OIDrsaEncryption defined in [RFC3447].

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

      • Set thesubjectPublicKey field to the result of DER-encoding anRSAPublicKey ASN.1 type, as defined in [RFC3447], Appendix A.1.1, that represents the RSA public key represented by the[[handle]] internal slot ofkey

    3. Letresult be the result of DER-encodingdata.

    Ifformat is "pkcs8":
    1. If the[[type]] internal slot ofkey is not "private", thenthrow anInvalidAccessError.

    2. Letdata be an instance of thePrivateKeyInfo ASN.1 structure defined in [RFC5208] with the following properties:

      • Set theversion field to0.

      • Set theprivateKeyAlgorithm field to aPrivateKeyAlgorithmIdentifier ASN.1 type with the following properties:

        • Set thealgorithm field to the OIDrsaEncryption defined in [RFC3447].

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

      • Set theprivateKey field to the result of DER-encoding anRSAPrivateKey ASN.1 type, as defined in [RFC3447], Appendix A.1.2, that represents the RSA private key represented by the[[handle]] internal slot ofkey

        Note
        [RFC5208] specifies that the encoding of this field should beBER encoded in Section 5 (as a "for example"). However, to avoid requiring WebCrypto implementations support BER-encoding and BER-decoding, onlyDER encodings are produced or accepted.
    3. Letresult be the result of DER-encodingdata.

    Ifformat is "jwk":
    1. Letjwk be a newJsonWebKey dictionary.

    2. Set thekty attribute ofjwk to the string "RSA".

    3. Lethash be thename attribute of thehash attribute of the[[algorithm]] internal slot ofkey.

    4. Ifhash is "SHA-1":

      Set thealg attribute ofjwk to the string "PS1".

      Ifhash is "SHA-256":

      Set thealg attribute ofjwk to the string "PS256".

      Ifhash is "SHA-384":

      Set thealg attribute ofjwk to the string "PS384".

      Ifhash is "SHA-512":

      Set thealg attribute ofjwk to the string "PS512".

      Otherwise:
      1. Perform anykey export steps defined byother applicable specifications, passingformat and thehash attribute of the[[algorithm]] internal slot ofkey and obtainingalg.

      2. Set thealg attribute ofjwk toalg.

    5. Set the attributesn ande ofjwk according to the corresponding definitions in JSON Web Algorithms [JWA], Section 6.3.1.

    6. If the[[type]] internal slot ofkey is "private":
      1. Set the attributes namedd,p,q,dp,dq, andqi ofjwk according to the corresponding definitions in JSON Web Algorithms [JWA], Section 6.3.2.

      2. If the underlying RSA private key represented by the[[handle]] internal slot ofkey is represented by more than two primes, set the attribute namedoth ofjwk according to the corresponding definition in JSON Web Algorithms [JWA], Section 6.3.2.7

    7. Set thekey_ops attribute ofjwk to theusages attribute ofkey.

    8. Set theext attribute ofjwk to the[[extractable]] internal slot ofkey.

    9. Letresult bejwk.

    Otherwise

    throw aNotSupportedError.

  4. Returnresult.

22.RSA-OAEP

22.1Description

This section is non-normative.

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

Other specifications may specify the use of additional hash algorithms with RSAES-OAEP. Such specifications must define the digest operation for the additional hash algorithm andkey import steps andkey export steps for RSAES-OAEP.

22.2Registration

Therecognized algorithm name for this algorithm is "RSA-OAEP".

OperationParametersResult
encryptRsaOaepParamsbyte sequence
decryptRsaOaepParamsbyte sequence
generateKeyRsaHashedKeyGenParamsCryptoKeyPair
importKeyRsaHashedImportParamsCryptoKey
exportKeyNoneobject

22.3RsaOaepParams dictionary

WebIDLdictionaryRsaOaepParams :Algorithm {BufferSourcelabel;};

Thelabel member represents the optional label/application data to associate with the message.

22.4Operations

22.4.1Encrypt

  1. If the[[type]] internal slot ofkey is not "public", thenthrow anInvalidAccessError.

  2. Letlabel be thelabel member ofnormalizedAlgorithm or the empty byte sequence if thelabel member ofnormalizedAlgorithm is not present.

  3. Perform the encryption operation defined in Section 7.1 of [RFC3447] with the key represented bykey as the recipient's RSA public key,plaintext as the message to be encrypted,M andlabel as the label,L, and with the hash function specified by thehash attribute of the[[algorithm]] internal slot ofkey as the Hash option and MGF1 (defined in Section B.2.1 of [RFC3447]) as the MGF option.

  4. If performing the operation results in an error, thenthrow anOperationError.

  5. Letciphertext be the valueC that results from performing the operation.

  6. Returnciphertext.

22.4.2Decrypt

  1. If the[[type]] internal slot ofkey is not "private", thenthrow anInvalidAccessError.

  2. Letlabel be thelabel member ofnormalizedAlgorithm or the empty byte sequence if thelabel member ofnormalizedAlgorithm is not present.

  3. Perform the decryption operation defined in Section 7.1 of [RFC3447] with the key represented bykey as the recipient's RSA private key,ciphertext as the ciphertext to be decrypted, C, andlabel as the label,L, and with the hash function specified by thehash attribute of the[[algorithm]] internal slot ofkey as the Hash option and MGF1 (defined in Section B.2.1 of [RFC3447]) as the MGF option.

  4. If performing the operation results in an error, thenthrow anOperationError.

  5. Letplaintext the valueM that results from performing the operation.

  6. Returnplaintext.

22.4.3Generate Key

  1. Ifusages contains an entry which is not "encrypt", "decrypt", "wrapKey" or "unwrapKey", thenthrow aSyntaxError.

  2. Generate an RSA key pair, as defined in [RFC3447], with RSA modulus length equal to themodulusLength member ofnormalizedAlgorithm and RSA public exponent equal to thepublicExponent member ofnormalizedAlgorithm.

  3. If performing the operation results in an error, thenthrow anOperationError.

  4. Letalgorithm be a newRsaHashedKeyAlgorithm object.

  5. Set thename attribute ofalgorithm to "RSA-OAEP".

  6. Set themodulusLength attribute ofalgorithm to equal themodulusLength member ofnormalizedAlgorithm.

  7. Set thepublicExponent attribute ofalgorithm to equal thepublicExponent member ofnormalizedAlgorithm.

  8. Set thehash attribute ofalgorithm to equal thehash member ofnormalizedAlgorithm.

  9. LetpublicKey be a newCryptoKey representing the public key of the generated key pair.

  10. Set the[[type]] internal slot ofpublicKey to "public"

  11. Set the[[algorithm]] internal slot ofpublicKey toalgorithm.

  12. Set the[[extractable]] internal slot ofpublicKey to true.

  13. Set the[[usages]] internal slot ofpublicKey to be theusage intersection ofusages and[ "encrypt", "wrapKey" ].

  14. LetprivateKey be a newCryptoKey representing the private key of the generated key pair.

  15. Set the[[type]] internal slot ofprivateKey to "private"

  16. Set the[[algorithm]] internal slot ofprivateKey toalgorithm.

  17. Set the[[extractable]] internal slot ofprivateKey toextractable.

  18. Set the[[usages]] internal slot ofprivateKey to be theusage intersection ofusages and[ "decrypt", "unwrapKey" ].

  19. Letresult be a newCryptoKeyPair dictionary.

  20. Set thepublicKey attribute ofresult to bepublicKey.

  21. Set theprivateKey attribute ofresult to beprivateKey.

  22. Returnresult.

22.4.4Import Key

  1. LetkeyData be the key data to be imported.

  2. Ifformat is "spki":
    1. Ifusages contains an entry which is not "encrypt" or "wrapKey", thenthrow aSyntaxError.

    2. Letspki be the result of running theparse a subjectPublicKeyInfo algorithm overkeyData.

    3. If an error occurred while parsing, thenthrow aDataError.

    4. If thealgorithm object identifier field of thealgorithm AlgorithmIdentifier field ofspki is not equal to thersaEncryption object identifier defined in [RFC3447], thenthrow aDataError.

    5. LetpublicKey be the result of performing theparse an ASN.1 structure algorithm, withdata as thesubjectPublicKeyInfo field ofspki,structure as theRSAPublicKey structure specified in Section A.1.1 of [RFC3447], andexactData set to true.

    6. If an error occurred while parsing, or it can be determined thatpublicKey is not a valid public key according to [RFC3447], thenthrow aDataError.

    7. Letkey be a newCryptoKey that represents the RSA public key identified bypublicKey.

    8. Set the[[type]] internal slot ofkey to "public"

    Ifformat is "pkcs8":
    1. Ifusages contains an entry which is not "decrypt" or "unwrapKey", thenthrow aSyntaxError.

    2. LetprivateKeyInfo be the result of running theparse a privateKeyInfo algorithm overkeyData.

    3. If an error occurred while parsing, thenthrow aDataError.

    4. If thealgorithm object identifier field of theprivateKeyAlgorithm PrivateKeyAlgorithm field ofprivateKeyInfo is not equal to thersaEncryption object identifier defined in [RFC3447], thenthrow aDataError.

    5. LetrsaPrivateKey be the result of performing theparse an ASN.1 structure algorithm, withdata as theprivateKey field ofprivateKeyInfo,structure as theRSAPrivateKey structure specified in Section A.1.2 of [RFC3447], andexactData set to true.

    6. If an error occurred while parsing, or ifrsaPrivateKey is not a valid RSA private key according to [RFC3447], thenthrow aDataError.

    7. Letkey be a newCryptoKey that represents the RSA private key identified byrsaPrivateKey.

    8. Set the[[type]] internal slot ofkey to "private"

    Ifformat is "jwk":
    1. IfkeyData is aJsonWebKey dictionary:

      Letjwk equalkeyData.

      Otherwise:

      Throw aDataError.

    2. If thed field ofjwk is present andusages contains an entry which is not "decrypt" or "unwrapKey", thenthrow aSyntaxError.

    3. If thed field ofjwk is not present andusages contains an entry which is not "encrypt" or "wrapKey", thenthrow aSyntaxError.

    4. If thekty field ofjwk is not a case-sensitive string match to "RSA", thenthrow aDataError.

    5. Ifusages is non-empty and theuse field ofjwk is present and is not a case-sensitive string match to "enc", thenthrow aDataError.

    6. If thekey_ops field ofjwk is present, and is invalid according to the requirements of JSON Web Key [JWK] or does not contain all of the specifiedusages values, thenthrow aDataError.

    7. If theext field ofjwk is present and has the value false andextractable is true, thenthrow aDataError.

    8. If thealg field ofjwk is not present:
      Lethash be undefined.
      If thealg field ofjwk is equal to "RSA-OAEP":
      Lethash be the string "SHA-1".
      If thealg field ofjwk is equal to "RSA-OAEP-256":
      Lethash be the string "SHA-256".
      If thealg field ofjwk is equal to "RSA-OAEP-384":
      Lethash be the string "SHA-384".
      If thealg field ofjwk is equal to "RSA-OAEP-512":
      Lethash be the string "SHA-512".
      Otherwise:
      1. Perform anykey import steps defined byother applicable specifications, passingformat,jwk and obtaininghash.

      2. If an error occurred or there are noapplicable specifications,throw aDataError.

    9. Ifhash is not undefined:
      1. LetnormalizedHash be the result ofnormalize an algorithm withalg set tohash andop set todigest.

      2. IfnormalizedHash is not equal to thehash member ofnormalizedAlgorithm,throw aDataError.

    10. If thed field ofjwk is present:
      1. Ifjwk does not meet the requirements of Section 6.3.2 of JSON Web Algorithms [JWA], thenthrow aDataError.

      2. LetprivateKey represent the RSA private key identified by interpretingjwk according to Section 6.3.2 of JSON Web Algorithms [JWA].

      3. IfprivateKey can be determined to not be a valid RSA private key according to [RFC3447], thenthrow aDataError.

      4. Letkey be a newCryptoKey representingprivateKey.

      5. Set the[[type]] internal slot ofkey to "private"

      Otherwise:
      1. Ifjwk does not meet the requirements of Section 6.3.1 of JSON Web Algorithms [JWA], thenthrow aDataError.

      2. LetpublicKey represent the RSA public key identified by interpretingjwk according to Section 6.3.1 of JSON Web Algorithms [JWA].

      3. IfpublicKey can be determined to not be a valid RSA public key according to [RFC3447], thenthrow aDataError.

      4. Letkey be a newCryptoKey representingpublicKey.

      5. Set the[[type]] internal slot ofkey to "public"

    Otherwise:
    throw aNotSupportedError.
  3. Letalgorithm be a newRsaHashedKeyAlgorithm.

  4. Set thename attribute ofalgorithm to "RSA-OAEP"

  5. Set themodulusLength attribute ofalgorithm to the length, in bits, of the RSA public modulus.

  6. Set thepublicExponent attribute ofalgorithm to theBigInteger representation of the RSA public exponent.

  7. Set thehash attribute ofalgorithm to thehash member ofnormalizedAlgorithm.

  8. Set the[[algorithm]] internal slot ofkey toalgorithm

  9. Returnkey.

22.4.5Export Key

  1. Letkey be the key to be exported.

  2. If the underlying cryptographic key material represented by the[[handle]] internal slot ofkey cannot be accessed, thenthrow anOperationError.

  3. Ifformat is "spki"
    1. If the[[type]] internal slot ofkey is not "public", thenthrow anInvalidAccessError.

    2. Letdata be an instance of theSubjectPublicKeyInfo ASN.1 structure defined in [RFC5280] with the following properties:

      • Set thealgorithm field to anAlgorithmIdentifier ASN.1 type with the following properties:

        • Set thealgorithm field to the OIDrsaEncryption defined in [RFC3447].

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

      • Set thesubjectPublicKey field to the result of DER-encoding anRSAPublicKey ASN.1 type, as defined in [RFC3447], Appendix A.1.1, that represents the RSA public key represented by the[[handle]] internal slot ofkey

    3. Letresult be the result of DER-encodingdata.

    Ifformat is "pkcs8":
    1. If the[[type]] internal slot ofkey is not "private", thenthrow anInvalidAccessError.

    2. Letdata be an instance of thePrivateKeyInfo ASN.1 structure defined in [RFC5208] with the following properties:

      • Set theversion field to0.

      • Set theprivateKeyAlgorithm field to aPrivateKeyAlgorithmIdentifier ASN.1 type with the following properties:

        • Set thealgorithm field to the OIDrsaEncryption defined in [RFC3447].

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

      • Set theprivateKey field to the result of DER-encoding anRSAPrivateKey ASN.1 type, as defined in [RFC3447], Appendix A.1.2, that represents the RSA private key represented by the[[handle]] internal slot ofkey

        Note
        [RFC5208] specifies that the encoding of this field should beBER encoded in Section 5 (as a "for example"). However, to avoid requiring WebCrypto implementations support BER-encoding and BER-decoding, onlyDER encodings are produced or accepted.
    3. Letresult be the result of DER-encodingdata.

    Ifformat is "jwk":
    1. Letjwk be a newJsonWebKey dictionary.

    2. Set thekty attribute ofjwk to the string "RSA".

    3. Lethash be thename attribute of thehash attribute of the[[algorithm]] internal slot ofkey.

    4. Ifhash is "SHA-1":

      Set thealg attribute ofjwk to the string "RSA-OAEP".

      Ifhash is "SHA-256":

      Set thealg attribute ofjwk to the string "RSA-OAEP-256".

      Ifhash is "SHA-384":

      Set thealg attribute ofjwk to the string "RSA-OAEP-384".

      Ifhash is "SHA-512":

      Set thealg attribute ofjwk to the string "RSA-OAEP-512".

      Otherwise:
      1. Perform anykey export steps defined byother applicable specifications, passingformat and thehash attribute of the[[algorithm]] internal slot ofkey and obtainingalg.

      2. Set thealg attribute ofjwk toalg.

    5. Set the attributesn ande ofjwk according to the corresponding definitions in JSON Web Algorithms [JWA], Section 6.3.1.

    6. If the[[type]] internal slot ofkey is "private":
      1. Set the attributes namedd,p,q,dp,dq, andqi ofjwk according to the corresponding definitions in JSON Web Algorithms [JWA], Section 6.3.2.

      2. If the underlying RSA private key represented by the[[handle]] internal slot ofkey is represented by more than two primes, set the attribute namedoth ofjwk according to the corresponding definition in JSON Web Algorithms [JWA], Section 6.3.2.7

    7. Set thekey_ops attribute ofjwk to theusages attribute ofkey.

    8. Set theext attribute ofjwk to the[[extractable]] internal slot ofkey.

    9. Letresult bejwk.

    Otherwise

    throw aNotSupportedError.

  4. Returnresult.

23.ECDSA

23.1Description

This section is non-normative.

The "ECDSA" algorithm identifier is used to perform signing and verification using the ECDSA algorithm specified in [RFC6090] and using the SHA hash functions and elliptic curves defined in this specification.

Other specifications may specify the use of additional elliptic curves and hash algorithms with ECDSA. To specify additional hash algorithms to be used with ECDSA, a specification must define aregistered algorithm that supports the digest operation. To specify an additional elliptic curve a specification must definethe curve name,ECDSA signature steps,ECDSA verification steps,ECDSA generation steps,ECDSA key import steps andECDSA key export steps.

23.2Registration

Therecognized algorithm name for this algorithm is "ECDSA".

OperationParametersResult
signEcdsaParamsbyte sequence
verifyEcdsaParamsboolean
generateKeyEcKeyGenParamsCryptoKeyPair
importKeyEcKeyImportParamsCryptoKey
exportKeyNoneobject

23.3EcdsaParams dictionary

WebIDLdictionaryEcdsaParams :Algorithm {  requiredHashAlgorithmIdentifierhash;};

Thehash member represents the hash algorithm to use.

23.4EcKeyGenParams dictionary

WebIDLtypedefDOMStringNamedCurve;dictionaryEcKeyGenParams :Algorithm {  requiredNamedCurvenamedCurve;};

TheNamedCurve type represents named elliptic curves, which are a convenient way to specify the domain parameters of well-known elliptic curves. The following values defined by this specification:

"P-256"
NIST recommended curve P-256, also known assecp256r1.
"P-384"
NIST recommended curve P-384, also known assecp384r1.
"P-521"
NIST recommended curve P-521, also known assecp521r1.

Other specifications may defineadditional values.

ThenamedCurve member of theEcKeyGenParams dictionary represents a named curve.

23.5EcKeyAlgorithm dictionary

WebIDLdictionaryEcKeyAlgorithm :KeyAlgorithm {  requiredNamedCurvenamedCurve;};

ThenamedCurve member represents the named curve that the key uses.

23.6EcKeyImportParams dictionary

WebIDLdictionaryEcKeyImportParams :Algorithm {  requiredNamedCurvenamedCurve;};

ThenamedCurve member represents a named curve.

23.7Operations

23.7.1Sign

  1. If the[[type]] internal slot ofkey is not "private", thenthrow anInvalidAccessError.

  2. LethashAlgorithm be thehash member ofnormalizedAlgorithm.

  3. LetM be the result of performing the digest operation specified byhashAlgorithm usingmessage.

  4. Letd be the ECDSA private key associated withkey.

  5. Letparams be the EC domain parameters associated withkey.

  6. If thenamedCurve attribute of the[[algorithm]] internal slot ofkey is "P-256", "P-384" or "P-521":
    1. Perform the ECDSA signing process, as specified in [RFC6090], Section 5.4, withM as the message, usingparams as the EC domain parameters, and withd as the private key.

    2. Letr ands be the pair of integers resulting from performing the ECDSA signing process.

    3. Letresult be an emptybyte sequence.

    4. Letn be the smallest integer such thatn * 8 is greater than the logarithm to base 2 of the order of the base point of the elliptic curve identified byparams.

    5. Convertr to a byte sequence of lengthn and append it toresult.

    6. Converts to a byte sequence of lengthn and append it toresult.

    Otherwise, thenamedCurve attribute of the[[algorithm]] internal slot ofkey is a value specified in anapplicable specification:

    Perform theECDSA signature steps specified in that specification, passing inM,params andd and resulting inresult.

  7. Returnresult.

23.7.2Verify

  1. If the[[type]] internal slot ofkey is not "public", thenthrow anInvalidAccessError.

  2. LethashAlgorithm be thehash member ofnormalizedAlgorithm.

  3. LetM be the result of performing the digest operation specified byhashAlgorithm usingmessage.

  4. LetQ be the ECDSA public key associated withkey.

  5. Letparams be the EC domain parameters associated withkey.

  6. If thenamedCurve attribute of the[[algorithm]] internal slot ofkey is "P-256", "P-384" or "P-521":

    Perform the ECDSA verifying process, as specified in [RFC6090], Section 5.3, withM as the received message,signature as the received signature and usingparams as the EC domain parameters, andQ as the public key.

    Otherwise, thenamedCurve attribute of the[[algorithm]] internal slot ofkey is a value specified in anapplicable specification:

    Perform theECDSA verification steps specified in that specification passing inM,signature,params andQ and resulting in an indication of whether or not the purported signature is valid.

  7. Letresult be a boolean with the valuetrue if the signature is valid and the valuefalse otherwise.

  8. Returnresult.

23.7.3Generate Key

  1. Ifusages contains a value which is not one of "sign" or "verify", thenthrow aSyntaxError.

  2. If thenamedCurve member ofnormalizedAlgorithm is "P-256", "P-384" or "P-521":

    Generate an Elliptic Curve key pair, as defined in [RFC6090] with domain parameters for the curve identified by thenamedCurve member ofnormalizedAlgorithm.

    If thenamedCurve member ofnormalizedAlgorithm is a value specified in anapplicable specification:

    Perform theECDSA generation steps specified in that specification, passing innormalizedAlgorithm and resulting in an elliptic curve key pair.

    Otherwise:

    throw aNotSupportedError

  3. If performing the key generation operation results in an error, thenthrow anOperationError.

  4. Letalgorithm be a newEcKeyAlgorithm object.

  5. Set thename attribute ofalgorithm to "ECDSA".

  6. Set thenamedCurve attribute ofalgorithm to equal thenamedCurve member ofnormalizedAlgorithm.

  7. LetpublicKey be a newCryptoKey representing the public key of the generated key pair.

  8. Set the[[type]] internal slot ofpublicKey to "public"

  9. Set the[[algorithm]] internal slot ofpublicKey toalgorithm.

  10. Set the[[extractable]] internal slot ofpublicKey to true.

  11. Set the[[usages]] internal slot ofpublicKey to be theusage intersection ofusages and[ "verify" ].

  12. LetprivateKey be a newCryptoKey representing the private key of the generated key pair.

  13. Set the[[type]] internal slot ofprivateKey to "private"

  14. Set the[[algorithm]] internal slot ofprivateKey toalgorithm.

  15. Set the[[extractable]] internal slot ofprivateKey toextractable.

  16. Set the[[usages]] internal slot ofprivateKey to be theusage intersection ofusages and[ "sign" ].

  17. Letresult be a newCryptoKeyPair dictionary.

  18. Set thepublicKey attribute ofresult to bepublicKey.

  19. Set theprivateKey attribute ofresult to beprivateKey.

  20. Returnresult.

23.7.4Import Key

  1. LetkeyData be the key data to be imported.

  2. Ifformat is "spki":
    1. Ifusages contains a value which is not "verify" thenthrow aSyntaxError.

    2. Letspki be the result of running theparse a subjectPublicKeyInfo algorithm overkeyData

    3. If an error occurred while parsing, thenthrow aDataError.

    4. If thealgorithm object identifier field of thealgorithm AlgorithmIdentifier field ofspki is not equal to theid-ecPublicKey object identifier defined in [RFC5480], thenthrow aDataError.

    5. If theparameters field of thealgorithm AlgorithmIdentifier field ofspki is absent, thenthrow aDataError.

    6. Letparams be theparameters field of thealgorithm AlgorithmIdentifier field ofspki.

    7. Ifparams is not an instance of theECParameters ASN.1 type defined in [RFC5480] that specifies anamedCurve, thenthrow aDataError.

    8. LetnamedCurve be a string whose initial value is undefined.

    9. Ifparams is equivalent to thesecp256r1 object identifier defined in [RFC5480]:

      SetnamedCurve "P-256".

      Ifparams is equivalent to thesecp384r1 object identifier defined in [RFC5480]:

      SetnamedCurve "P-384".

      Ifparams is equivalent to thesecp521r1 object identifier defined in [RFC5480]:

      SetnamedCurve "P-521".

    10. IfnamedCurve is not undefined:
      1. LetpublicKey be the Elliptic Curve public key identified by performing the conversion steps defined in Section 2.3.4 of [SEC1] using thesubjectPublicKey field ofspki.

        The uncompressed point formatMUST be supported.

      2. If the implementation does not support the compressed point format and a compressed point is provided,throw aDataError.

      3. If a decode error occurs or an identity point is found,throw aDataError.

      4. Letkey be a newCryptoKey that representspublicKey.

      Otherwise:
      1. Perform anykey import steps defined byother applicable specifications, passingformat,spki and obtainingnamedCurve andkey.

      2. If an error occurred or there are noapplicable specifications,throw aDataError.

    11. IfnamedCurve is defined, and not equal to thenamedCurve member ofnormalizedAlgorithm,throw aDataError.

    12. If the public key value is not a valid point on the Elliptic Curve identified by thenamedCurve member ofnormalizedAlgorithmthrow aDataError.

    13. Set the[[type]] internal slot ofkey to "public"

    14. Letalgorithm be a newEcKeyAlgorithm.

    15. Set thename attribute ofalgorithm to "ECDSA".

    16. Set thenamedCurve attribute ofalgorithm tonamedCurve.

    17. Set the[[algorithm]] internal slot ofkey toalgorithm.

    Ifformat is "pkcs8":
    1. Ifusages contains a value which is not "sign" thenthrow aSyntaxError.

    2. LetprivateKeyInfo be the result of running theparse a privateKeyInfo algorithm overkeyData.

    3. If an error occurs while parsing, thenthrow aDataError.

    4. If thealgorithm object identifier field of theprivateKeyAlgorithm PrivateKeyAlgorithm field ofprivateKeyInfo is not equal to theid-ecPublicKey object identifier defined in [RFC5480], thenthrow aDataError.

    5. If theparameters field of theprivateKeyAlgorithm PrivateKeyAlgorithmIdentifier field ofprivateKeyInfo is not present, thenthrow aDataError.

    6. Letparams be theparameters field of theprivateKeyAlgorithm PrivateKeyAlgorithmIdentifier field ofprivateKeyInfo.

    7. Ifparams is not an instance of theECParameters ASN.1 type defined in [RFC5480] that specifies anamedCurve, thenthrow aDataError.

    8. LetnamedCurve be a string whose initial value is undefined.

    9. Ifparams is equivalent to thesecp256r1 object identifier defined in [RFC5480]:

      SetnamedCurve "P-256".

      Ifparams is equivalent to thesecp384r1 object identifier defined in [RFC5480]:

      SetnamedCurve "P-384".

      Ifparams is equivalent to thesecp521r1 object identifier defined in [RFC5480]:

      SetnamedCurve "P-521".

    10. IfnamedCurve is not undefined:
      1. LetecPrivateKey be the result of performing theparse an ASN.1 structure algorithm, withdata as theprivateKey field ofprivateKeyInfo,structure as the ASN.1ECPrivateKey structure specified in Section 3 of [RFC5915], andexactData set to true.

      2. If an error occurred while parsing, thenthrow aDataError.

      3. If theparameters field ofecPrivateKey is present, and is not an instance of thenamedCurve ASN.1 type defined in [RFC5480], or does not contain the same object identifier as theparameters field of theprivateKeyAlgorithm PrivateKeyAlgorithmIdentifier field ofprivateKeyInfo, thenthrow aDataError.

      4. Letkey be a newCryptoKey that represents the Elliptic Curve private key identified by performing the conversion steps defined in Section 3 of [RFC5915] usingecPrivateKey.

      Otherwise:
      1. Perform anykey import steps defined byother applicable specifications, passingformat,privateKeyInfo and obtainingnamedCurve andkey.

      2. If an error occurred or there are noapplicable specifications,throw aDataError.

    11. IfnamedCurve is defined, and not equal to thenamedCurve member ofnormalizedAlgorithm,throw aDataError.

    12. If the private key value is not a valid point on the Elliptic Curve identified by thenamedCurve member ofnormalizedAlgorithmthrow aDataError.

    13. Set the[[type]] internal slot ofkey to "private"

    14. Letalgorithm be a newEcKeyAlgorithm.

    15. Set thename attribute ofalgorithm to "ECDSA".

    16. Set thenamedCurve attribute ofalgorithm tonamedCurve.

    17. Set the[[algorithm]] internal slot ofkey toalgorithm.

    Ifformat is "jwk":
    1. IfkeyData is aJsonWebKey dictionary:

      Letjwk equalkeyData.

      Otherwise:

      Throw aDataError.

    2. If thed field is present andusages contains a value which is not "sign", or, if thed field is not present andusages contains a value which is not "verify" thenthrow aSyntaxError.

    3. If thekty field ofjwk is not "EC", thenthrow aDataError.

    4. Ifusages is non-empty and theuse field ofjwk is present and is not "sig", thenthrow aDataError.

    5. If thekey_ops field ofjwk is present, and is invalid according to the requirements of JSON Web Key [JWK], or it does not contain all of the specifiedusages values, thenthrow aDataError.

    6. If theext field ofjwk is present and has the value false andextractable is true, thenthrow aDataError.

    7. LetnamedCurve be a string whose value is equal to thecrv field ofjwk.

    8. IfnamedCurve is not equal to thenamedCurve member ofnormalizedAlgorithm,throw aDataError.

    9. IfnamedCurve is equal to "P-256", "P-384" or "P-521":
      1. LetalgNamedCurve be a string whose initial value is undefined.

      2. If thealg field is not present:
        LetalgNamedCurve be undefined.
        If thealg field is equal to the string "ES256":
        LetalgNamedCurve be the string "P-256".
        If thealg field is equal to the string "ES384":
        LetalgNamedCurve be the string "P-384".
        If thealg field is equal to the string "ES512":
        LetalgNamedCurve be the string "P-521".
        otherwise:
        throw aDataError.
      3. IfalgNamedCurve is defined, and is not equal tonamedCurve,throw aDataError.

      4. If thed field is present:
        1. Ifjwk does not meet the requirements of Section 6.2.2 of JSON Web Algorithms [JWA], thenthrow aDataError.

        2. Letkey be a newCryptoKey object that represents the Elliptic Curve private key identified by interpretingjwk according to Section 6.2.2 of JSON Web Algorithms [JWA].

        3. Set the[[type]] internal slot ofKey to "private".

        Otherwise:
        1. Ifjwk does not meet the requirements of Section 6.2.1 of JSON Web Algorithms [JWA], thenthrow aDataError.

        2. Letkey be a newCryptoKey object that represents the Elliptic Curve public key identified by interpretingjwk according to Section 6.2.1 of JSON Web Algorithms [JWA].

        3. Set the[[type]] internal slot ofKey to "public".

      Otherwise:
      1. Perform anykey import steps defined byother applicable specifications, passingformat,jwk and obtainingkey.

      2. If an error occurred or there are noapplicable specifications,throw aDataError.

    10. If the key value is not a valid point on the Elliptic Curve identified by thenamedCurve member ofnormalizedAlgorithmthrow aDataError.

    11. Letalgorithm be a new instance of anEcKeyAlgorithm object.

    12. Set thename attribute ofalgorithm to "ECDSA".

    13. Set thenamedCurve attribute ofalgorithm tonamedCurve.

    14. Set the[[algorithm]] internal slot ofkey toalgorithm.

    Ifformat is "raw":
    1. If thenamedCurve member ofnormalizedAlgorithm is not anamed curve, thenthrow aDataError.

    2. Ifusages contains a value which is not "verify" thenthrow aSyntaxError.

    3. IfnamedCurve is "P-256", "P-384" or "P-521":
      1. LetQ be the elliptic curve point on the curve identified by thenamedCurve member ofnormalizedAlgorithm identified by performing the conversion steps defined in Section 2.3.4 of [SEC1] onkeyData.

        The uncompressed point formatMUST be supported.

      2. If the implementation does not support the compressed point format and a compressed point is provided,throw aDataError.

      3. If a decode error occurs or an identity point is found,throw aDataError.

      4. Letkey be a newCryptoKey that representsQ.

      Otherwise:
      1. Perform anykey import steps defined byother applicable specifications, passingformat,keyData and obtainingkey.

      2. If an error occurred or there are noapplicable specifications,throw aDataError.

    4. Letalgorithm be a newEcKeyAlgorithm object.

    5. Set thename attribute ofalgorithm to "ECDSA".

    6. Set thenamedCurve attribute ofalgorithm to equal thenamedCurve member ofnormalizedAlgorithm.

    7. Set the[[type]] internal slot ofkey to "public"

    8. Set the[[algorithm]] internal slot ofkey toalgorithm.

    Otherwise:

    throw aNotSupportedError.

  3. Returnkey

23.7.5Export Key

  1. Letkey be theCryptoKey to be exported.

  2. If the underlying cryptographic key material represented by the[[handle]] internal slot ofkey cannot be accessed, thenthrow anOperationError.

  3. Ifformat is "spki":
    1. If the[[type]] internal slot ofkey is not "public", thenthrow anInvalidAccessError.

    2. Letdata be an instance of theSubjectPublicKeyInfo ASN.1 structure defined in [RFC5280] with the following properties:

      • Set thealgorithm field to anAlgorithmIdentifier ASN.1 type with the following properties:

        • Set thealgorithm field to the OIDid-ecPublicKey defined in [RFC5480].

        • Set theparameters field to an instance of theECParameters ASN.1 type defined in [RFC5480] as follows:

          If thenamedCurve attribute of the[[algorithm]] internal slot ofkey is "P-256", "P-384" or "P-521":

          LetkeyData be thebyte sequence that represents the Elliptic Curve public key represented by the[[handle]] internal slot ofkey according to the encoding rules specified in Section 2.2 of [RFC5480] and using the uncompressed form. andkeyData.

          If thenamedCurve attribute of the[[algorithm]] internal slot ofkey is "P-256":

          Setparameters to thenamedCurve choice with value equal to the object identifiersecp256r1 defined in [RFC5480]

          If thenamedCurve attribute of the[[algorithm]] internal slot ofkey is "P-384":

          Setparameters to thenamedCurve choice with value equal to the object identifiersecp384r1 defined in [RFC5480]

          If thenamedCurve attribute of the[[algorithm]] internal slot ofkey is "P-521":

          Setparameters to thenamedCurve choice with value equal to the object identifiersecp521r1 defined in [RFC5480]

          Otherwise:
          1. Perform anykey export steps defined byother applicable specifications, passingformat and thenamedCurve attribute of the[[algorithm]] internal slot ofkey and obtainingnamedCurveOid andkeyData.

          2. Setparameters to thenamedCurve choice with value equal to the object identifiernamedCurveOid.

      • Set thesubjectPublicKey field tokeyData.

    3. Letresult be the result of DER-encodingdata.

    Ifformat is "pkcs8":
    1. If the[[type]] internal slot ofkey is not "private", thenthrow anInvalidAccessError.

    2. Letdata be an instance of thePrivateKeyInfo ASN.1 structure defined in [RFC5208] with the following properties:

      • Set theversion field to0.

      • Set theprivateKeyAlgorithm field to aPrivateKeyAlgorithmIdentifier ASN.1 type with the following properties:

        • Set thealgorithm field to the OIDid-ecPublicKey defined in [RFC5480].

        • Set theparameters field to an instance of theECParameters ASN.1 type defined in [RFC5480] as follows:

          If thenamedCurve attribute of the[[algorithm]] internal slot ofkey is "P-256", "P-384" or "P-521":

          LetkeyData be the result of DER-encoding an instance of theECPrivateKey structure defined in Section 3 of [RFC5915] for the Elliptic Curve private key represented by the[[handle]] internal slot ofkey and that conforms to the following:

          • Theparameters field is present, and is equivalent to theparameters field of theprivateKeyAlgorithm field of thisPrivateKeyInfo ASN.1 structure.

          • ThepublicKey field is present and represents the Elliptic Curve public key associated with the Elliptic Curve private key represented by the[[handle]] internal slot ofkey.

          If thenamedCurve attribute of the[[algorithm]] internal slot ofkey is "P-256":

          Setparameters to thenamedCurve choice with value equal to the object identifiersecp256r1 defined in [RFC5480]

          If thenamedCurve attribute of the[[algorithm]] internal slot ofkey is "P-384":

          Setparameters to thenamedCurve choice with value equal to the object identifiersecp384r1 defined in [RFC5480]

          If thenamedCurve attribute of the[[algorithm]] internal slot ofkey is "P-521":

          Setparameters to thenamedCurve choice with value equal to the object identifiersecp521r1 defined in [RFC5480]

          Otherwise:
          1. Perform anykey export steps defined byother applicable specifications, passingformat and thenamedCurve attribute of the[[algorithm]] internal slot ofkey and obtainingnamedCurveOid andkeyData.

          2. Setparameters to thenamedCurve choice with value equal to the object identifiernamedCurveOid.

      • Set theprivateKey field tokeyData.

    3. Letresult be the result of DER-encodingdata.

    Ifformat is "jwk":
    1. Letjwk be a newJsonWebKey dictionary.

    2. Set thekty attribute ofjwk to "EC".

    3. If thenamedCurve attribute of the[[algorithm]] internal slot ofkey is "P-256", "P-384" or "P-521":
      1. If thenamedCurve attribute of the[[algorithm]] internal slot ofkey is "P-256":
        Set thecrv attribute ofjwk to "P-256"
        If thenamedCurve attribute of the[[algorithm]] internal slot ofkey is "P-384":
        Set thecrv attribute ofjwk to "P-384"
        If thenamedCurve attribute of the[[algorithm]] internal slot ofkey is "P-521":
        Set thecrv attribute ofjwk to "P-521"
      2. Set thex attribute ofjwk according to the definition in Section 6.2.1.2 of JSON Web Algorithms [JWA].

      3. Set they attribute ofjwk according to the definition in Section 6.2.1.3 of JSON Web Algorithms [JWA].

      4. If the[[type]] internal slot ofkey is "private"

        Set thed attribute ofjwk according to the definition in Section 6.2.2.1 of JSON Web Algorithms [JWA].

      Otherwise:
      1. Perform anykey export steps defined byother applicable specifications, passingformat and thenamedCurve attribute of the[[algorithm]] internal slot ofkey and obtainingnamedCurve and a new value ofjwk.

      2. Set thecrv attribute ofjwk tonamedCurve.

    4. Set thekey_ops attribute ofjwk to theusages attribute ofkey.

    5. Set theext attribute ofjwk to the[[extractable]] internal slot ofkey.

    6. Letresult bejwk.

    Ifformat is "raw":
    1. If the[[type]] internal slot ofkey is not "public", thenthrow anInvalidAccessError.

    2. If thenamedCurve attribute of the[[algorithm]] internal slot ofkey is "P-256", "P-384" or "P-521":

      Letdata be abyte sequence representing the Elliptic Curve pointQ represented by the[[handle]] internal slot ofkey according to [SEC1] 2.3.3 using the uncompressed format.

      Otherwise:

      Perform anykey export steps defined byother applicable specifications, passingformat and thenamedCurve attribute of the[[algorithm]] internal slot ofkey and obtainingnamedCurve anddata.

    3. Letresult bedata.

    Otherwise:

    throw aNotSupportedError.

  4. Returnresult.

24.ECDH

24.1Description

This section is non-normative.

This describes using Elliptic Curve Diffie-Hellman (ECDH) for key generation and key agreement, as specified by [RFC6090].

Other specifications may specify the use of additional elliptic curves with ECDH. To specify an additional elliptic curve a specification must definethe curve name,ECDH generation steps,ECDH derivation steps,ECDH key import steps andECDH key export steps.

24.2Registration

Therecognized algorithm name for this algorithm is "ECDH".

OperationParametersResult
generateKeyEcKeyGenParamsCryptoKeyPair
deriveBitsEcdhKeyDeriveParamsbyte sequence
importKeyEcKeyImportParamsCryptoKey
exportKeyNoneobject

24.3EcdhKeyDeriveParams dictionary

WebIDLdictionaryEcdhKeyDeriveParams :Algorithm {  requiredCryptoKeypublic;};

Thepublic member represents the peer's EC public key.

24.4Operations

24.4.1Generate Key

  1. Ifusages contains an entry which is not "deriveKey" or "deriveBits" thenthrow aSyntaxError.

  2. If thenamedCurve member ofnormalizedAlgorithm is "P-256", "P-384" or "P-521":

    Generate an Elliptic Curve key pair, as defined in [RFC6090] with domain parameters for the curve identified by thenamedCurve member ofnormalizedAlgorithm.

    If thenamedCurve member ofnormalizedAlgorithm is a value specified in anapplicable specification that specifies the use of that value with ECDH:

    Perform theECDH generation steps specified in that specification, passing innormalizedAlgorithm and resulting in an elliptic curve key pair.

    Otherwise:

    throw aNotSupportedError

  3. If performing the operation results in an error, thenthrow aOperationError.

  4. Letalgorithm be a newEcKeyAlgorithm object.

  5. Set thename member ofalgorithm to "ECDH".

  6. Set thenamedCurve attribute ofalgorithm to equal thenamedCurve member ofnormalizedAlgorithm.

  7. LetpublicKey be a newCryptoKey representing the public key of the generated key pair.

  8. Set the[[type]] internal slot ofpublicKey to "public"

  9. Set the[[algorithm]] internal slot ofpublicKey toalgorithm.

  10. Set the[[extractable]] internal slot ofpublicKey to true.

  11. Set the[[usages]] internal slot ofpublicKey to be the empty list.

  12. LetprivateKey be a newCryptoKey representing the private key of the generated key pair.

  13. Set the[[type]] internal slot ofprivateKey to "private"

  14. Set the[[algorithm]] internal slot ofprivateKey toalgorithm.

  15. Set the[[extractable]] internal slot ofprivateKey toextractable.

  16. Set the[[usages]] internal slot ofprivateKey to be theusage intersection ofusages and[ "deriveKey", "deriveBits" ].

  17. Letresult be a newCryptoKeyPair dictionary.

  18. Set thepublicKey attribute ofresult to bepublicKey.

  19. Set theprivateKey attribute ofresult to beprivateKey.

  20. Returnresult.

24.4.2Derive Bits

  1. If the[[type]] internal slot ofkey is not "private", thenthrow anInvalidAccessError.

  2. LetpublicKey be thepublic member ofnormalizedAlgorithm.

  3. If the[[type]] internal slot ofpublicKey is not "public", thenthrow anInvalidAccessError.

  4. If thename attribute of the[[algorithm]] internal slot ofpublicKey is not equal to thename property of the[[algorithm]] internal slot ofkey, thenthrow anInvalidAccessError.

  5. If thenamedCurve attribute of the[[algorithm]] internal slot ofpublicKey is not equal to thenamedCurve property of the[[algorithm]] internal slot ofkey, thenthrow anInvalidAccessError.

  6. If thenamedCurve property of the[[algorithm]] internal slot ofkey is "P-256", "P-384" or "P-521":
    1. Perform the ECDH primitive specified in [RFC6090] Section 4 withkey as the EC private keyd and the EC public key represented by the[[handle]] internal slot ofpublicKey as the EC public key.

    2. Letsecret be abyte sequence containing the result of applying the field element to octet string conversion defined in Section 6.2 of [RFC6090] to the output of the ECDH primitive.

    If thenamedCurve property of the[[algorithm]] internal slot ofkey is a value specified in anapplicable specification that specifies the use of that value with ECDH:

    Perform theECDH derivation steps specified in that specification, passing inkey andpublicKey and resulting insecret.

    Otherwise:

    throw aNotSupportedError

  7. If performing the operation results in an error, thenthrow aOperationError.

  8. Iflength is null:
    Returnsecret
    Otherwise:
    If thelength in bits ofsecret is less thanlength:
    throw anOperationError.
    Otherwise:
    Return abyte sequence containing the firstlength bits ofsecret.

24.4.3Import Key

  1. LetkeyData be the key data to be imported.

  2. Ifformat is "spki":
    1. Ifusages is not empty thenthrow aSyntaxError.

    2. Letspki be the result of running theparse a subjectPublicKeyInfo algorithm overkeyData

    3. If an error occurred while parsing, thenthrow aDataError.

    4. If thealgorithm object identifier field of thealgorithm AlgorithmIdentifier field ofspki is not equal to theid-ecPublicKey object identifier defined in [RFC5480], thenthrow aDataError.

    5. If theparameters field of thealgorithm AlgorithmIdentifier field ofspki is absent, thenthrow aDataError.

    6. Letparams be theparameters field of thealgorithm AlgorithmIdentifier field ofspki.

    7. Ifparams is not an instance of theECParameters ASN.1 type defined in [RFC5480] that specifies anamedCurve, thenthrow aDataError.

    8. LetnamedCurve be a string whose initial value is undefined.

    9. Ifparams is equivalent to thesecp256r1 object identifier defined in [RFC5480]:

      SetnamedCurve "P-256".

      Ifparams is equivalent to thesecp384r1 object identifier defined in [RFC5480]:

      SetnamedCurve "P-384".

      Ifparams is equivalent to thesecp521r1 object identifier defined in [RFC5480]:

      SetnamedCurve "P-521".

    10. IfnamedCurve is not undefined:
      1. LetpublicKey be the Elliptic Curve public key identified by performing the conversion steps defined in Section 2.3.4 of [SEC1] to thesubjectPublicKey field ofspki.

        The uncompressed point formatMUST be supported.

      2. If the implementation does not support the compressed point format and a compressed point is provided,throw aDataError.

      3. If a decode error occurs or an identity point is found,throw aDataError.

      4. Letkey be a newCryptoKey that representspublicKey.

      Otherwise:
      1. Perform anykey import steps defined byother applicable specifications, passingformat,spki and obtainingnamedCurve andkey.

      2. If an error occurred or there are noapplicable specifications,throw aDataError.

    11. IfnamedCurve is defined, and not equal to thenamedCurve member ofnormalizedAlgorithm,throw aDataError.

    12. If the key value is not a valid point on the Elliptic Curve identified by thenamedCurve member ofnormalizedAlgorithmthrow aDataError.

    13. Set the[[type]] internal slot ofkey to "public"

    14. Letalgorithm be a newEcKeyAlgorithm.

    15. Set thename attribute ofalgorithm to "ECDH".

    16. Set thenamedCurve attribute ofalgorithm tonamedCurve.

    17. Set the[[algorithm]] internal slot ofkey toalgorithm.

    Ifformat is "pkcs8":
    1. Ifusages contains an entry which is not "deriveKey" or "deriveBits" thenthrow aSyntaxError.

    2. LetprivateKeyInfo be the result of running theparse a privateKeyInfo algorithm overkeyData.

    3. If an error occurs while parsing,throw aDataError.

    4. If thealgorithm object identifier field of theprivateKeyAlgorithm PrivateKeyAlgorithm field ofprivateKeyInfo is not equal to theid-ecPublicKey object identifier defined in [RFC5480],throw aDataError.

    5. If theparameters field of theprivateKeyAlgorithm PrivateKeyAlgorithmIdentifier field ofprivateKeyInfo is not present,throw aDataError.

    6. Letparams be theparameters field of theprivateKeyAlgorithm PrivateKeyAlgorithmIdentifier field ofprivateKeyInfo.

    7. Ifparams is not an instance of theECParameters ASN.1 type defined in [RFC5480] that specifies anamedCurve, thenthrow aDataError.

    8. LetnamedCurve be a string whose initial value is undefined.

    9. Ifparams is equivalent to thesecp256r1 object identifier defined in [RFC5480]:

      SetnamedCurve to "P-256".

      Ifparams is equivalent to thesecp384r1 object identifier defined in [RFC5480]:

      SetnamedCurve to "P-384".

      Ifparams is equivalent to thesecp521r1 object identifier defined in [RFC5480]:

      SetnamedCurve to "P-521".

    10. IfnamedCurve is not undefined:
      1. LetecPrivateKey be the result of performing theparse an ASN.1 structure algorithm, withdata as theprivateKey field ofprivateKeyInfo,structure as the ASN.1ECPrivateKey structure specified in Section 3 of [RFC5915], andexactData set to true.

      2. If an error occurred while parsing, thenthrow aDataError.

      3. If theparameters field ofecPrivateKey is present, and is not an instance of thenamedCurve ASN.1 type defined in [RFC5480], or does not contain the same object identifier as theparameters field of theprivateKeyAlgorithm PrivateKeyAlgorithmIdentifier field ofprivateKeyInfo,throw aDataError.

      4. Letkey be a newCryptoKey that represents the Elliptic Curve private key identified by performing the conversion steps defined in Section 3 of [RFC5915] usingecPrivateKey.

      Otherwise:
      1. Perform anykey import steps defined byother applicable specifications, passingformat,privateKeyInfo and obtainingnamedCurve andkey.

      2. If an error occurred or there are noapplicable specifications,throw aDataError.

    11. IfnamedCurve is defined, and not equal to thenamedCurve member ofnormalizedAlgorithm,throw aDataError.

    12. If the key value is not a valid point on the Elliptic Curve identified by thenamedCurve member ofnormalizedAlgorithmthrow aDataError.

    13. Set the[[type]] internal slot ofkey to "private".

    14. Letalgorithm be a newEcKeyAlgorithm.

    15. Set thename attribute ofalgorithm to "ECDH".

    16. Set thenamedCurve attribute ofalgorithm tonamedCurve.

    17. Set the[[algorithm]] internal slot ofkey toalgorithm.

    Ifformat is "jwk":
    1. IfkeyData is aJsonWebKey dictionary:

      Letjwk equalkeyData.

      Otherwise:

      Throw aDataError.

    2. If thed field is present and ifusages contains an entry which is not "deriveKey" or "deriveBits" thenthrow aSyntaxError.

    3. If thed field is not present and ifusages is not empty thenthrow aSyntaxError.

    4. If thekty field ofjwk is not "EC", thenthrow aDataError.

    5. Ifusages is non-empty and theuse field ofjwk is present and is not equal to "enc" thenthrow aDataError.

    6. If thekey_ops field ofjwk is present, and is invalid according to the requirements of JSON Web Key [JWK], or it does not contain all of the specifiedusages values, thenthrow aDataError.

    7. If theext field ofjwk is present and has the value false andextractable is true, thenthrow aDataError.

    8. LetnamedCurve be a string whose value is equal to thecrv field ofjwk.

    9. IfnamedCurve is not equal to thenamedCurve member ofnormalizedAlgorithm,throw aDataError.

    10. IfnamedCurve is "P-256", "P-384" or "P-521":
      If thed field is present:
      1. Ifjwk does not meet the requirements of Section 6.2.2 of JSON Web Algorithms [JWA], thenthrow aDataError.

      2. Letkey be a newCryptoKey object that represents the Elliptic Curve private key identified by interpretingjwk according to Section 6.2.2 of JSON Web Algorithms [JWA].

      3. Set the[[type]] internal slot ofKey to "private".

      Otherwise:
      1. Ifjwk does not meet the requirements of Section 6.2.1 of JSON Web Algorithms [JWA], thenthrow aDataError.

      2. Letkey be a newCryptoKey object that represents the Elliptic Curve public key identified by interpretingjwk according to Section 6.2.1 of JSON Web Algorithms [JWA].

      3. Set the[[type]] internal slot ofKey to "public".

      Otherwise
      1. Perform anykey import steps defined byother applicable specifications, passingformat,jwk and obtainingkey.

      2. If an error occurred or there are noapplicable specifications,throw aDataError.

    11. If the key value is not a valid point on the Elliptic Curve identified by thenamedCurve member ofnormalizedAlgorithmthrow aDataError.

    12. Letalgorithm be a new instance of anEcKeyAlgorithm object.

    13. Set thename attribute ofalgorithm to "ECDH".

    14. Set thenamedCurve attribute ofalgorithm tonamedCurve.

    15. Set the[[algorithm]] internal slot ofkey toalgorithm.

    Ifformat is "raw":
    1. If thenamedCurve member ofnormalizedAlgorithm is not anamed curve, thenthrow aDataError.

    2. Ifusages is not the empty list, thenthrow aSyntaxError.

    3. IfnamedCurve is "P-256", "P-384" or "P-521":
      1. LetQ be the Elliptic Curve public key on the curve identified by thenamedCurve member ofnormalizedAlgorithm identified by performing the conversion steps defined in Section 2.3.4 of [SEC1] tokeyData.

        The uncompressed point formatMUST be supported.

      2. If the implementation does not support the compressed point format and a compressed point is provided,throw aDataError.

      3. If a decode error occurs or an identity point is found,throw aDataError.

      4. Letkey be a newCryptoKey that representsQ.

      Otherwise:
      1. Perform anykey import steps defined byother applicable specifications, passingformat,keyData and obtainingkey.

      2. If an error occured or there are noapplicable specifications,throw aDataError.

    4. Letalgorithm be a newEcKeyAlgorithm object.

    5. Set thename attribute ofalgorithm to "ECDH".

    6. Set thenamedCurve attribute ofalgorithm to equal thenamedCurve member ofnormalizedAlgorithm.

    7. Set the[[type]] internal slot ofkey to "public"

    8. Set the[[algorithm]] internal slot ofkey toalgorithm.

  3. Returnkey

24.4.4Export Key

  1. Letkey be theCryptoKey to be exported.

  2. If the underlying cryptographic key material represented by the[[handle]] internal slot ofkey cannot be accessed, thenthrow anOperationError.

  3. Ifformat is "spki":
    1. If the[[type]] internal slot ofkey is not "public", thenthrow anInvalidAccessError.

    2. Letdata be an instance of theSubjectPublicKeyInfo ASN.1 structure defined in [RFC5280] with the following properties:

      • Set thealgorithm field to anAlgorithmIdentifier ASN.1 type with the following properties:

        • Set thealgorithm field to the OIDid-ecPublicKey defined in [RFC5480].

        • Set theparameters field to an instance of theECParameters ASN.1 type defined in [RFC5480] as follows:

          If thenamedCurve attribute of the[[algorithm]] internal slot ofkey is "P-256", "P-384" or "P-521":

          LetkeyData be thebyte sequence that represents the Elliptic Curve public key represented by the[[handle]] internal slot ofkey according to the encoding rules specified in Section 2.3.3 of [SEC1] and using the uncompressed form.

          If thenamedCurve attribute of the[[algorithm]] internal slot ofkey is "P-256":

          Setparameters to thenamedCurve choice with value equal to the object identifiersecp256r1 defined in [RFC5480]

          If thenamedCurve attribute of the[[algorithm]] internal slot ofkey is "P-384":

          Setparameters to thenamedCurve choice with value equal to the object identifiersecp384r1 defined in [RFC5480]

          If thenamedCurve attribute of the[[algorithm]] internal slot ofkey is "P-521":

          Setparameters to thenamedCurve choice with value equal to the object identifiersecp521r1 defined in [RFC5480]

          Otherwise:
          1. Perform anykey export steps defined byother applicable specifications, passingformat and thenamedCurve attribute of the[[algorithm]] internal slot ofkey and obtainingnamedCurveOid andkeyData.

          2. Setparameters to thenamedCurve choice with value equal to the object identifiernamedCurveOid.

      • Set thesubjectPublicKey field tokeyData

    Ifformat is "pkcs8":
    1. If the[[type]] internal slot ofkey is not "private", thenthrow anInvalidAccessError.

    2. Letdata be an instance of thePrivateKeyInfo ASN.1 structure defined in [RFC5208] with the following properties:

      • Set theversion field to0.

      • Set theprivateKeyAlgorithm field to aPrivateKeyAlgorithmIdentifier ASN.1 type with the following properties:

        • Set thealgorithm field to the OIDid-ecPublicKey defined in [RFC5480].

        • Set theparameters field to an instance of theECParameters ASN.1 type defined in [RFC5480] as follows:

          If thenamedCurve attribute of the[[algorithm]] internal slot ofkey is "P-256", "P-384" or "P-521":

          LetkeyData be the result of DER-encoding an instance of theECPrivateKey structure defined in Section 3 of [RFC5915] for the Elliptic Curve private key represented by the[[handle]] internal slot ofkey and that conforms to the following:

          • Theparameters field is present, and is equivalent to theparameters field of theprivateKeyAlgorithm field of thisPrivateKeyInfo ASN.1 structure.

          • ThepublicKey field is present and represents the Elliptic Curve public key associated with the Elliptic Curve private key represented by the[[handle]] internal slot ofkey.

          If thenamedCurve attribute of the[[algorithm]] internal slot ofkey is "P-256":

          Setparameters to thenamedCurve choice with value equal to the object identifiersecp256r1 defined in [RFC5480]

          If thenamedCurve attribute of the[[algorithm]] internal slot ofkey is "P-384":

          Setparameters to thenamedCurve choice with value equal to the object identifiersecp384r1 defined in [RFC5480]

          If thenamedCurve attribute of the[[algorithm]] internal slot ofkey is "P-521":

          Setparameters to thenamedCurve choice with value equal to the object identifiersecp521r1 defined in [RFC5480]

          Otherwise:
          1. Perform anykey export steps defined byother applicable specifications, passingformat and thenamedCurve attribute of the[[algorithm]] internal slot ofkey and obtainingnamedCurveOid andkeyData.

          2. Setparameters to thenamedCurve choice with value equal to the object identifiernamedCurveOid.

      • Set theprivateKey field tokeyData.

    Ifformat is "jwk":
    1. Letjwk be a newJsonWebKey dictionary.

    2. Set thekty attribute ofjwk to "EC".

    3. If thenamedCurve attribute of the[[algorithm]] internal slot ofkey is "P-256", "P-384" or "P-521":
      1. If thenamedCurve attribute of the[[algorithm]] internal slot ofkey is "P-256":
        Set thecrv attribute ofjwk to "P-256"
        If thenamedCurve attribute of the[[algorithm]] internal slot ofkey is "P-384":
        Set thecrv attribute ofjwk to "P-384"
        If thenamedCurve attribute of the[[algorithm]] internal slot ofkey is "P-521":
        Set thecrv attribute ofjwk to "P-521"
      2. Set thex attribute ofjwk according to the definition in Section 6.2.1.2 of JSON Web Algorithms [JWA].

      3. Set they attribute ofjwk according to the definition in Section 6.2.1.3 of JSON Web Algorithms [JWA].

      4. If the[[type]] internal slot ofkey is "private"

        Set thed attribute ofjwk according to the definition in Section 6.2.2.1 of JSON Web Algorithms [JWA].

      Otherwise:
      1. Perform anykey export steps defined byother applicable specifications, passingformat and thenamedCurve attribute of the[[algorithm]] internal slot ofkey and obtainingnamedCurve and a new value ofjwk.

      2. Set thecrv attribute ofjwk tonamedCurve.

    4. Set thekey_ops attribute ofjwk to theusages attribute ofkey.

    5. Set theext attribute ofjwk to the[[extractable]] internal slot ofkey.

    6. Letresult bejwk.

    Ifformat is "raw":
    1. If the[[type]] internal slot ofkey is not "public", thenthrow anInvalidAccessError.

    2. If thenamedCurve attribute of the[[algorithm]] internal slot ofkey is "P-256", "P-384" or "P-521":

      Letdata be thebyte sequence that represents the Elliptic Curve public key represented by the[[handle]] internal slot ofkey according to the encoding rules specified in Section 2.3.3 of [SEC1] and using the uncompressed form.

      Otherwise:

      Perform anykey export steps defined byother applicable specifications, passingformat and thenamedCurve attribute of the[[algorithm]] internal slot ofkey and obtainingnamedCurve anddata.

    3. Letresult bedata.

  4. Returnresult.

25.Ed25519

25.1Description

This section is non-normative.

The "Ed25519" algorithm identifier is used to perform signing and verification using the Ed25519 algorithm specified in [RFC8032].

25.2Registration

Therecognized algorithm name for this algorithm is "Ed25519".

OperationParametersResult
signNonebyte sequence
verifyNoneboolean
generateKeyNoneCryptoKeyPair
importKeyNoneCryptoKey
exportKeyNoneobject

25.3Operations

25.3.1Sign

  1. If the[[type]] internal slot ofkey is not "private", thenthrow anInvalidAccessError.

  2. Letresult be the result of performing the Ed25519 signing process, as specified in [RFC8032], Section 5.1.6, withmessage asM, using the Ed25519 private key associated withkey.

    Issue 1

    Some implementations may (wish to) generate randomized signatures as perdraft-irtf-cfrg-det-sigs-with-noise instead of deterministic signatures as per [RFC8032].

    SeeWICG/webcrypto-secure-curves issue 28.

  3. Returnresult.

25.3.2Verify

  1. If the[[type]] internal slot ofkey is not "public", thenthrow anInvalidAccessError.

  2. If the key data ofkey represents an invalid point or a small-order element on the Elliptic Curve of Ed25519, returnfalse.

    Issue 2

    Not all implementations perform this check.

    SeeWICG/webcrypto-secure-curves issue 27.

  3. If the point R, encoded in the first half ofsignature, represents an invalid point or a small-order element on the Elliptic Curve of Ed25519, returnfalse.

    Issue 3

    Not all implementations perform this check.

    SeeWICG/webcrypto-secure-curves issue 27.

  4. Perform the Ed25519 verification steps, as specified in [RFC8032], Section 5.1.7, using the cofactorless (unbatched) equation,[S]B = R + [k]A', on thesignature, withmessage asM, using the Ed25519 public key associated withkey.

  5. Letresult be a boolean with the valuetrue if the signature is valid and the valuefalse otherwise.

  6. Returnresult.

25.3.3Generate Key

  1. Ifusages contains a value which is not one of "sign" or "verify", thenthrow aSyntaxError.

  2. Generate an Ed25519 key pair, as defined in [RFC8032], section 5.1.5.

  3. Letalgorithm be a newKeyAlgorithm object.

  4. Set thename attribute ofalgorithm to "Ed25519".

  5. LetpublicKey be a newCryptoKey representing the public key of the generated key pair.

  6. Set the[[type]] internal slot ofpublicKey to "public"

  7. Set the[[algorithm]] internal slot ofpublicKey toalgorithm.

  8. Set the[[extractable]] internal slot ofpublicKey to true.

  9. Set the[[usages]] internal slot ofpublicKey to be theusage intersection ofusages and[ "verify" ].

  10. LetprivateKey be a newCryptoKey representing the private key of the generated key pair.

  11. Set the[[type]] internal slot ofprivateKey to "private"

  12. Set the[[algorithm]] internal slot ofprivateKey toalgorithm.

  13. Set the[[extractable]] internal slot ofprivateKey toextractable.

  14. Set the[[usages]] internal slot ofprivateKey to be theusage intersection ofusages and[ "sign" ].

  15. Letresult be a newCryptoKeyPair dictionary.

  16. Set thepublicKey attribute ofresult to bepublicKey.

  17. Set theprivateKey attribute ofresult to beprivateKey.

  18. Returnresult.

25.3.4Import Key

  1. LetkeyData be the key data to be imported.

  2. Ifformat is "spki":
    1. Ifusages contains a value which is not "verify" thenthrow aSyntaxError.

    2. Letspki be the result of running theparse a subjectPublicKeyInfo algorithm overkeyData.

    3. If an error occurred while parsing, thenthrow aDataError.

    4. If thealgorithm object identifier field of thealgorithm AlgorithmIdentifier field ofspki is not equal to theid-Ed25519 object identifier defined in [RFC8410], thenthrow aDataError.

    5. If theparameters field of thealgorithm AlgorithmIdentifier field ofspki is present, thenthrow aDataError.

    6. LetpublicKey be the Ed25519 public key identified by thesubjectPublicKey field ofspki.

    7. Letkey be a newCryptoKey that representspublicKey.

    8. Set the[[type]] internal slot ofkey to "public"

    9. Letalgorithm be a newKeyAlgorithm.

    10. Set thename attribute ofalgorithm to "Ed25519".

    11. Set the[[algorithm]] internal slot ofkey toalgorithm.

    Ifformat is "pkcs8":
    1. Ifusages contains a value which is not "sign" thenthrow aSyntaxError.

    2. LetprivateKeyInfo be the result of running theparse a privateKeyInfo algorithm overkeyData.

    3. If an error occurs while parsing, thenthrow aDataError.

    4. If thealgorithm object identifier field of theprivateKeyAlgorithm PrivateKeyAlgorithm field ofprivateKeyInfo is not equal to theid-Ed25519 object identifier defined in [RFC8410], thenthrow aDataError.

    5. If theparameters field of theprivateKeyAlgorithm PrivateKeyAlgorithmIdentifier field ofprivateKeyInfo is present, thenthrow aDataError.

    6. LetcurvePrivateKey be the result of performing theparse an ASN.1 structure algorithm, withdata as theprivateKey field ofprivateKeyInfo,structure as the ASN.1CurvePrivateKey structure specified in Section 7 of [RFC8410], andexactData set to true.

    7. If an error occurred while parsing, thenthrow aDataError.

    8. Letkey be a newCryptoKey that represents the Ed25519 private key identified bycurvePrivateKey.

    9. Set the[[type]] internal slot ofkey to "private"

    10. Letalgorithm be a newKeyAlgorithm.

    11. Set thename attribute ofalgorithm to "Ed25519".

    12. Set the[[algorithm]] internal slot ofkey toalgorithm.

    Ifformat is "jwk":
    1. IfkeyData is aJsonWebKey dictionary:

      Letjwk equalkeyData.

      Otherwise:

      Throw aDataError.

    2. If thed field is present andusages contains a value which is not "sign", or, if thed field is not present andusages contains a value which is not "verify" thenthrow aSyntaxError.

    3. If thekty field ofjwk is not "OKP", thenthrow aDataError.

    4. If thecrv field ofjwk is not "Ed25519", thenthrow aDataError.

    5. If thealg field ofjwk is present and is not "Ed25519" or "EdDSA", thenthrow aDataError.

    6. Ifusages is non-empty and theuse field ofjwk is present and is not "sig", thenthrow aDataError.

    7. If thekey_ops field ofjwk is present, and is invalid according to the requirements of JSON Web Key [JWK], or it does not contain all of the specifiedusages values, thenthrow aDataError.

    8. If theext field ofjwk is present and has the value false andextractable is true, thenthrow aDataError.

    9. If thed field is present:
      1. Ifjwk does not meet the requirements of the JWK private key format described in Section 2 of [RFC8037], thenthrow aDataError.

      2. Letkey be a newCryptoKey object that represents the Ed25519 private key identified by interpretingjwk according to Section 2 of [RFC8037].

      3. Set the[[type]] internal slot ofKey to "private".

      Otherwise:
      1. Ifjwk does not meet the requirements of the JWK public key format described in Section 2 of [RFC8037], thenthrow aDataError.

      2. Letkey be a newCryptoKey object that represents the Ed25519 public key identified by interpretingjwk according to Section 2 of [RFC8037].

      3. Set the[[type]] internal slot ofKey to "public".

    10. Letalgorithm be a new instance of aKeyAlgorithm object.

    11. Set thename attribute ofalgorithm to "Ed25519".

    12. Set the[[algorithm]] internal slot ofkey toalgorithm.

    Ifformat is "raw":
    1. Ifusages contains a value which is not "verify" thenthrow aSyntaxError.

    2. Letalgorithm be a newKeyAlgorithm object.

    3. Set thename attribute ofalgorithm to "Ed25519".

    4. Letkey be a newCryptoKey representing the key data provided inkeyData.

    5. Set the[[type]] internal slot ofkey to "public"

    6. Set the[[algorithm]] internal slot ofkey toalgorithm.

    Otherwise:

    throw aNotSupportedError.

  3. Returnkey

25.3.5Export Key

  1. Letkey be theCryptoKey to be exported.

  2. If the underlying cryptographic key material represented by the[[handle]] internal slot ofkey cannot be accessed, thenthrow anOperationError.

  3. Ifformat is "spki":
    1. If the[[type]] internal slot ofkey is not "public", thenthrow anInvalidAccessError.

    2. Letdata be an instance of theSubjectPublicKeyInfo ASN.1 structure defined in [RFC5280] with the following properties:

      • Set thealgorithm field to anAlgorithmIdentifier ASN.1 type with the following properties:

        • Set thealgorithm object identifier to theid-Ed25519 OID defined in [RFC8410].

      • Set thesubjectPublicKey field tokeyData.

    3. Letresult be the result of DER-encodingdata.

    Ifformat is "pkcs8":
    1. If the[[type]] internal slot ofkey is not "private", thenthrow anInvalidAccessError.

    2. Letdata be an instance of thePrivateKeyInfo ASN.1 structure defined in [RFC5208] with the following properties:

      • Set theversion field to0.

      • Set theprivateKeyAlgorithm field to aPrivateKeyAlgorithmIdentifier ASN.1 type with the following properties:

        • Set thealgorithm object identifier to theid-Ed25519 OID defined in [RFC8410].

      • Set theprivateKey field to the result of DER-encoding aCurvePrivateKey ASN.1 type, as defined in Section 7 of [RFC8410], that represents the Ed25519 private key represented by the[[handle]] internal slot ofkey

    3. Letresult be the result of DER-encodingdata.

    Ifformat is "jwk":
    1. Letjwk be a newJsonWebKey dictionary.

    2. Set thekty attribute ofjwk to "OKP".

    3. Set thealg attribute ofjwk to "Ed25519".

    4. Set thecrv attribute ofjwk to "Ed25519".

    5. Set thex attribute ofjwk according to the definition in Section 2 of [RFC8037].

    6. If the[[type]] internal slot ofkey is "private"
      Set thed attribute ofjwk according to the definition in Section 2 of [RFC8037].
    7. Set thekey_ops attribute ofjwk to theusages attribute ofkey.

    8. Set theext attribute ofjwk to the[[extractable]] internal slot ofkey.

    9. Letresult bejwk.

    Ifformat is "raw":
    1. If the[[type]] internal slot ofkey is not "public", thenthrow anInvalidAccessError.

    2. Letdata be abyte sequence representing the Ed25519 public key represented by the[[handle]] internal slot ofkey.

    3. Letresult bedata.

    Otherwise:

    throw aNotSupportedError.

  4. Returnresult.

26.X25519

26.1Description

This section is non-normative.

The "X25519" algorithm identifier is used to perform key agreement using the X25519 algorithm specified in [RFC7748].

26.2Registration

Therecognized algorithm name for this algorithm is "X25519".

OperationParametersResult
deriveBitsEcdhKeyDeriveParamsbyte sequence
generateKeyNoneCryptoKeyPair
importKeyNoneCryptoKey
exportKeyNoneobject

26.3Operations

26.3.1Derive Bits

  1. If the[[type]] internal slot ofkey is not "private", thenthrow anInvalidAccessError.

  2. LetpublicKey be thepublic member ofnormalizedAlgorithm.

  3. If the[[type]] internal slot ofpublicKey is not "public", thenthrow anInvalidAccessError.

  4. If thename attribute of the[[algorithm]] internal slot ofpublicKey is not equal to thename property of the[[algorithm]] internal slot ofkey, thenthrow anInvalidAccessError.

  5. Letsecret be the result of performing the X25519 function specified in [RFC7748] Section 5 withkey as the X25519 private keyk and the X25519 public key represented by the[[handle]] internal slot ofpublicKey as the X25519 public keyu.

  6. Ifsecret is the all-zero value, thenthrow aOperationError. This check must be performed in constant-time, as per [RFC7748] Section 6.1.

  7. Iflength is null:
    Returnsecret
    Otherwise:
    If the length ofsecret in bits is less thanlength:
    throw anOperationError.
    Otherwise:
    Return abyte sequence containing the firstlength bits ofsecret.

26.3.2Generate Key

  1. Ifusages contains an entry which is not "deriveKey" or "deriveBits" thenthrow aSyntaxError.

  2. Generate an X25519 key pair, with the private key being 32 random bytes, and the public key beingX25519(a, 9), as defined in [RFC7748], section 6.1.

  3. Letalgorithm be a newKeyAlgorithm object.

  4. Set thename attribute ofalgorithm to "X25519".

  5. LetpublicKey be a newCryptoKey representing the public key of the generated key pair.

  6. Set the[[type]] internal slot ofpublicKey to "public"

  7. Set the[[algorithm]] internal slot ofpublicKey toalgorithm.

  8. Set the[[extractable]] internal slot ofpublicKey to true.

  9. Set the[[usages]] internal slot ofpublicKey to be the empty list.

  10. LetprivateKey be a newCryptoKey representing the private key of the generated key pair.

  11. Set the[[type]] internal slot ofprivateKey to "private"

  12. Set the[[algorithm]] internal slot ofprivateKey toalgorithm.

  13. Set the[[extractable]] internal slot ofprivateKey toextractable.

  14. Set the[[usages]] internal slot ofprivateKey to be theusage intersection ofusages and[ "deriveKey", "deriveBits" ].

  15. Letresult be a newCryptoKeyPair dictionary.

  16. Set thepublicKey attribute ofresult to bepublicKey.

  17. Set theprivateKey attribute ofresult to beprivateKey.

  18. Returnresult.

26.3.3Import Key

  1. LetkeyData be the key data to be imported.

  2. Ifformat is "spki":
    1. Ifusages is not empty thenthrow aSyntaxError.

    2. Letspki be the result of running theparse a subjectPublicKeyInfo algorithm overkeyData.

    3. If an error occurred while parsing, thenthrow aDataError.

    4. If thealgorithm object identifier field of thealgorithm AlgorithmIdentifier field ofspki is not equal to theid-X25519 object identifier defined in [RFC8410], thenthrow aDataError.

    5. If theparameters field of thealgorithm AlgorithmIdentifier field ofspki is present, thenthrow aDataError.

    6. LetpublicKey be the X25519 public key identified by thesubjectPublicKey field ofspki.

    7. Letkey be a newCryptoKey that representspublicKey.

    8. Set the[[type]] internal slot ofkey to "public"

    9. Letalgorithm be a newKeyAlgorithm.

    10. Set thename attribute ofalgorithm to "X25519".

    11. Set the[[algorithm]] internal slot ofkey toalgorithm.

    Ifformat is "pkcs8":
    1. Ifusages contains an entry which is not "deriveKey" or "deriveBits" thenthrow aSyntaxError.

    2. LetprivateKeyInfo be the result of running theparse a privateKeyInfo algorithm overkeyData.

    3. If an error occurs while parsing, thenthrow aDataError.

    4. If thealgorithm object identifier field of theprivateKeyAlgorithm PrivateKeyAlgorithm field ofprivateKeyInfo is not equal to theid-X25519 object identifier defined in [RFC8410], thenthrow aDataError.

    5. If theparameters field of theprivateKeyAlgorithm PrivateKeyAlgorithmIdentifier field ofprivateKeyInfo is present, thenthrow aDataError.

    6. LetcurvePrivateKey be the result of performing theparse an ASN.1 structure algorithm, withdata as theprivateKey field ofprivateKeyInfo,structure as the ASN.1CurvePrivateKey structure specified in Section 7 of [RFC8410], andexactData set to true.

    7. If an error occurred while parsing, thenthrow aDataError.

    8. Letkey be a newCryptoKey that represents the X25519 private key identified bycurvePrivateKey.

    9. Set the[[type]] internal slot ofkey to "private"

    10. Letalgorithm be a newKeyAlgorithm.

    11. Set thename attribute ofalgorithm to "X25519".

    12. Set the[[algorithm]] internal slot ofkey toalgorithm.

    Ifformat is "jwk":
    1. IfkeyData is aJsonWebKey dictionary:

      Letjwk equalkeyData.

      Otherwise:

      Throw aDataError.

    2. If thed field is present and ifusages contains an entry which is not "deriveKey" or "deriveBits" thenthrow aSyntaxError.

    3. If thed field is not present and ifusages is not empty thenthrow aSyntaxError.

    4. If thekty field ofjwk is not "OKP", thenthrow aDataError.

    5. If thecrv field ofjwk is not "X25519", thenthrow aDataError.

    6. Ifusages is non-empty and theuse field ofjwk is present and is not equal to "enc" thenthrow aDataError.

    7. If thekey_ops field ofjwk is present, and is invalid according to the requirements of JSON Web Key [JWK], or it does not contain all of the specifiedusages values, thenthrow aDataError.

    8. If theext field ofjwk is present and has the value false andextractable is true, thenthrow aDataError.

    9. If thed field is present:
      1. Ifjwk does not meet the requirements of the JWK private key format described in Section 2 of [RFC8037], thenthrow aDataError.

      2. Letkey be a newCryptoKey object that represents the X25519 private key identified by interpretingjwk according to Section 2 of [RFC8037].

      3. Set the[[type]] internal slot ofKey to "private".

      Otherwise:
      1. Ifjwk does not meet the requirements of the JWK public key format described in Section 2 of [RFC8037], thenthrow aDataError.

      2. Letkey be a newCryptoKey object that represents the X25519 public key identified by interpretingjwk according to Section 2 of [RFC8037].

      3. Set the[[type]] internal slot ofKey to "public".

    10. Letalgorithm be a new instance of aKeyAlgorithm object.

    11. Set thename attribute ofalgorithm to "X25519".

    12. Set the[[algorithm]] internal slot ofkey toalgorithm.

    Ifformat is "raw":
    1. Ifusages is not empty thenthrow aSyntaxError.

    2. Letalgorithm be a newKeyAlgorithm object.

    3. Set thename attribute ofalgorithm to "X25519".

    4. Letkey be a newCryptoKey representing the key data provided inkeyData.

    5. Set the[[type]] internal slot ofkey to "public"

    6. Set the[[algorithm]] internal slot ofkey toalgorithm.

    Otherwise:

    throw aNotSupportedError.

  3. Returnkey

26.3.4Export Key

  1. Letkey be theCryptoKey to be exported.

  2. If the underlying cryptographic key material represented by the[[handle]] internal slot ofkey cannot be accessed, thenthrow anOperationError.

  3. Ifformat is "spki":
    1. If the[[type]] internal slot ofkey is not "public", thenthrow anInvalidAccessError.

    2. Letdata be an instance of theSubjectPublicKeyInfo ASN.1 structure defined in [RFC5280] with the following properties:

      • Set thealgorithm field to anAlgorithmIdentifier ASN.1 type with the following properties:

        • Set thealgorithm object identifier to theid-X25519 OID defined in [RFC8410].

      • Set thesubjectPublicKey field tokeyData.

    3. Letresult be the result of DER-encodingdata.

    Ifformat is "pkcs8":
    1. If the[[type]] internal slot ofkey is not "private", thenthrow anInvalidAccessError.

    2. Letdata be an instance of thePrivateKeyInfo ASN.1 structure defined in [RFC5208] with the following properties:

      • Set theversion field to0.

      • Set theprivateKeyAlgorithm field to aPrivateKeyAlgorithmIdentifier ASN.1 type with the following properties:

        • Set thealgorithm object identifier to theid-X25519 OID defined in [RFC8410].

      • Set theprivateKey field to the result of DER-encoding aCurvePrivateKey ASN.1 type, as defined in Section 7 of [RFC8410], that represents the X25519 private key represented by the[[handle]] internal slot ofkey

    3. Letresult be the result of DER-encodingdata.

    Ifformat is "jwk":
    1. Letjwk be a newJsonWebKey dictionary.

    2. Set thekty attribute ofjwk to "OKP".

    3. Set thecrv attribute ofjwk to "X25519".

    4. Set thex attribute ofjwk according to the definition in Section 2 of [RFC8037].

    5. If the[[type]] internal slot ofkey is "private"
      Set thed attribute ofjwk according to the definition in Section 2 of [RFC8037].
    6. Set thekey_ops attribute ofjwk to theusages attribute ofkey.

    7. Set theext attribute ofjwk to the[[extractable]] internal slot ofkey.

    8. Letresult bejwk.

    Ifformat is "raw":
    1. If the[[type]] internal slot ofkey is not "public", thenthrow anInvalidAccessError.

    2. Letdata be abyte sequence representing the X25519 public key represented by the[[handle]] internal slot ofkey.

    3. Letresult bedata.

    Otherwise:

    throw aNotSupportedError.

  4. Returnresult.

27.AES-CTR

27.1Description

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-SP800-38A].

27.2Registration

Therecognized algorithm name for this algorithm is "AES-CTR".

OperationParametersResult
encryptAesCtrParamsbyte sequence
decryptAesCtrParamsbyte sequence
generateKeyAesKeyGenParamsCryptoKey
importKeyNoneCryptoKey
exportKeyNoneobject
get key lengthAesDerivedKeyParamsInteger

27.3AesCtrParams dictionary

WebIDLdictionaryAesCtrParams :Algorithm {  requiredBufferSourcecounter;  required [EnforceRange]octetlength;};

Thecounter member contains the initial value of the counter block.counterMUST 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.

Thelength member contains the length, in bits, of the rightmost part of the counter block that is incremented.

27.4AesKeyAlgorithm dictionary

WebIDLdictionaryAesKeyAlgorithm :KeyAlgorithm {  requiredunsigned shortlength;};

Thelength member represents the length, in bits, of the key.

27.5AesKeyGenParams dictionary

WebIDLdictionaryAesKeyGenParams :Algorithm {  required [EnforceRange]unsigned shortlength;};

Thelength member represents the length, in bits, of the key.

27.6AesDerivedKeyParams dictionary

WebIDLdictionaryAesDerivedKeyParams :Algorithm {  required [EnforceRange]unsigned shortlength;};

Thelength member represents the length, in bits, of the key.

27.7Operations

27.7.1Encrypt

  1. If thecounter member ofnormalizedAlgorithm does not have alength of 16 bytes, thenthrow anOperationError.

  2. If thelength member ofnormalizedAlgorithm is zero or is greater than 128, thenthrow anOperationError.

  3. Letciphertext be the result of performing the CTR Encryption operation described in Section 6.5 of [NIST-SP800-38A] using AES as the block cipher, thecounter member ofnormalizedAlgorithm as the initial value of the counter block, thelength member ofnormalizedAlgorithm as the input parameterm to the standard counter block incrementing function defined in Appendix B.1 of [NIST-SP800-38A] andplaintext as the input plaintext.

  4. Returnciphertext.

27.7.2Decrypt

  1. If thecounter member ofnormalizedAlgorithm does not have alength of 16 bytes, thenthrow anOperationError.

  2. If thelength member ofnormalizedAlgorithm is zero or is greater than 128, thenthrow anOperationError.

  3. Letplaintext be the result of performing the CTR Decryption operation described in Section 6.5 of [NIST-SP800-38A] using AES as the block cipher, thecounter member ofnormalizedAlgorithm as the initial value of the counter block, thelength member ofnormalizedAlgorithm as the input parameterm to the standard counter block incrementing function defined in Appendix B.1 of [NIST-SP800-38A] andciphertext as the input ciphertext.

  4. Returnplaintext.

27.7.3Generate Key

  1. Ifusages contains any entry which is not one of "encrypt", "decrypt", "wrapKey" or "unwrapKey", thenthrow aSyntaxError.

  2. If thelength member ofnormalizedAlgorithm is not equal to one of 128, 192 or 256, thenthrow anOperationError.

  3. Generate an AES key of length equal to thelength member ofnormalizedAlgorithm.

  4. If the key generation step fails, thenthrow anOperationError.

  5. Letkey be a newCryptoKey object representing the generated AES key.

  6. Letalgorithm be a newAesKeyAlgorithm.

  7. Set thename attribute ofalgorithm to "AES-CTR".

  8. Set thelength attribute ofalgorithm to equal thelength member ofnormalizedAlgorithm.

  9. Set the[[type]] internal slot ofkey to "secret".

  10. Set the[[algorithm]] internal slot ofkey toalgorithm.

  11. Set the[[extractable]] internal slot ofkey to beextractable.

  12. Set the[[usages]] internal slot ofkey to beusages.

  13. Returnkey.

27.7.4Import Key

  1. Ifusages contains an entry which is not one of "encrypt", "decrypt", "wrapKey" or "unwrapKey", thenthrow aSyntaxError.

  2. Ifformat is "raw":
    1. Letdata bekeyData.

    2. If thelength in bits ofdata is not 128, 192 or 256 thenthrow aDataError.

    Ifformat is "jwk":
    1. IfkeyData is aJsonWebKey dictionary:

      Letjwk equalkeyData.

      Otherwise:

      Throw aDataError.

    2. If thekty field ofjwk is not "oct", thenthrow aDataError.

    3. Ifjwk does not meet the requirements of Section 6.4 of JSON Web Algorithms [JWA], thenthrow aDataError.

    4. Letdata be thebyte sequence obtained by decoding thek field ofjwk.

    5. If thelength in bits ofdata is 128:
      If thealg field ofjwk is present, and is not "A128CTR", thenthrow aDataError.
      If thelength in bits ofdata is 192:
      If thealg field ofjwk is present, and is not "A192CTR", thenthrow aDataError.
      If thelength in bits ofdata is 256:
      If thealg field ofjwk is present, and is not "A256CTR", thenthrow aDataError.
      Otherwise:
      throw aDataError.
    6. Ifusages is non-empty and theuse field ofjwk is present and is not "enc", thenthrow aDataError.

    7. If thekey_ops field ofjwk is present, and is invalid according to the requirements of JSON Web Key [JWK] or does not contain all of the specifiedusages values, thenthrow aDataError.

    8. If theext field ofjwk is present and has the value false andextractable is true, thenthrow aDataError.

    Otherwise:
    throw aNotSupportedError.
  3. Letkey be a newCryptoKey object representing an AES key with valuedata.

  4. Set the[[type]] internal slot ofkey to "secret".

  5. Letalgorithm be a newAesKeyAlgorithm.

  6. Set thename attribute ofalgorithm to "AES-CTR".

  7. Set thelength attribute ofalgorithm to the length, in bits, ofdata.

  8. Set the[[algorithm]] internal slot ofkey toalgorithm.

  9. Returnkey.

27.7.5Export Key

  1. If the underlying cryptographic key material represented by the[[handle]] internal slot ofkey cannot be accessed, thenthrow anOperationError.

  2. Ifformat is "raw":
    1. Letdata be abyte sequence containing the raw octets of the key represented by the[[handle]] internal slot ofkey.

    2. Letresult bedata.

    Ifformat is "jwk":
    1. Letjwk be a newJsonWebKey dictionary.

    2. Set thekty attribute ofjwk to the string "oct".

    3. Set thek attribute ofjwk to be a string containing the raw octets of the key represented by the[[handle]] internal slot ofkey, encoded according to Section 6.4 of JSON Web Algorithms [JWA].

    4. If thelength attribute ofkey is 128:
      Set thealg attribute ofjwk to the string "A128CTR".
      If thelength attribute ofkey is 192:
      Set thealg attribute ofjwk to the string "A192CTR".
      If thelength attribute ofkey is 256:
      Set thealg attribute ofjwk to the string "A256CTR".
    5. Set thekey_ops attribute ofjwk to equal the[[usages]] internal slot ofkey.

    6. Set theext attribute ofjwk to equal the[[extractable]] internal slot ofkey.

    7. Letresult bejwk.

    Otherwise:

    throw aNotSupportedError.

  3. Returnresult.

27.7.6Get key length

  1. If thelength member ofnormalizedDerivedKeyAlgorithm is not 128, 192 or 256, thenthrow aOperationError.

  2. Return thelength member ofnormalizedDerivedKeyAlgorithm.

28.AES-CBC

28.1Description

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-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 [RFC2315].

28.2Registration

Therecognized algorithm name for this algorithm is "AES-CBC".

OperationParametersResult
encryptAesCbcParamsbyte sequence
decryptAesCbcParamsbyte sequence
generateKeyAesKeyGenParamsCryptoKey
importKeyNoneCryptoKey
exportKeyNoneobject
get key lengthAesDerivedKeyParamsInteger

28.3AesCbcParams dictionary

WebIDLdictionaryAesCbcParams :Algorithm {  requiredBufferSourceiv;};

Theiv member represents the initialization vector. ItMUST be 16 bytes.

28.4Operations

28.4.1Encrypt

  1. If theiv member ofnormalizedAlgorithm does not have alength of 16 bytes, thenthrow anOperationError.

  2. LetpaddedPlaintext be the result of adding padding octets toplaintext according to the procedure defined in Section 10.3 of [RFC2315], step 2, with a value ofk of 16.

  3. Letciphertext be the result of performing the CBC Encryption operation described in Section 6.2 of [NIST-SP800-38A] using AES as the block cipher, theiv member ofnormalizedAlgorithm as theIV input parameter andpaddedPlaintext as the input plaintext.

  4. Returnciphertext.

28.4.2Decrypt

  1. If theiv member ofnormalizedAlgorithm does not have alength of 16 bytes, thenthrow anOperationError.

  2. If the length ofciphertext is zero or is not a multiple of 16 bytes, thenthrow anOperationError.

  3. LetpaddedPlaintext be the result of performing the CBC Decryption operation described in Section 6.2 of [NIST-SP800-38A] using AES as the block cipher, theiv member ofnormalizedAlgorithm as theIV input parameter andciphertext as the input ciphertext.

  4. Letp be the value of the last octet ofpaddedPlaintext.

  5. Ifp is zero or greater than 16, or if any of the lastp octets ofpaddedPlaintext have a value which is notp, thenthrow anOperationError.

  6. Letplaintext be the result of removingp octets from the end ofpaddedPlaintext.

  7. Returnplaintext.

28.4.3Generate Key

  1. Ifusages contains any entry which is not one of "encrypt", "decrypt", "wrapKey" or "unwrapKey", thenthrow aSyntaxError.

  2. If thelength member ofnormalizedAlgorithm is not equal to one of 128, 192 or 256, thenthrow anOperationError.

  3. Generate an AES key of length equal to thelength member ofnormalizedAlgorithm.

  4. If the key generation step fails, thenthrow anOperationError.

  5. Letkey be a newCryptoKey object representing the generated AES key.

  6. Letalgorithm be a newAesKeyAlgorithm.

  7. Set thename attribute ofalgorithm to "AES-CBC".

  8. Set thelength attribute ofalgorithm to equal thelength member ofnormalizedAlgorithm.

  9. Set the[[type]] internal slot ofkey to "secret".

  10. Set the[[algorithm]] internal slot ofkey toalgorithm.

  11. Set the[[extractable]] internal slot ofkey to beextractable.

  12. Set the[[usages]] internal slot ofkey to beusages.

  13. Returnkey.

28.4.4Import Key

  1. Ifusages contains an entry which is not one of "encrypt", "decrypt", "wrapKey" or "unwrapKey", thenthrow aSyntaxError.

  2. Ifformat is "raw":
    1. Letdata bekeyData.

    2. If thelength in bits ofdata is not 128, 192 or 256 thenthrow aDataError.

    Ifformat is "jwk":
    1. IfkeyData is aJsonWebKey dictionary:

      Letjwk equalkeyData.

      Otherwise:

      Throw aDataError.

    2. If thekty field ofjwk is not "oct", thenthrow aDataError.

    3. Ifjwk does not meet the requirements of Section 6.4 of JSON Web Algorithms [JWA], thenthrow aDataError.

    4. Letdata be thebyte sequence obtained by decoding thek field ofjwk.

    5. If thelength in bits ofdata is 128:
      If thealg field ofjwk is present, and is not "A128CBC", thenthrow aDataError.
      If thelength in bits ofdata is 192:
      If thealg field ofjwk is present, and is not "A192CBC", thenthrow aDataError.
      If thelength in bits ofdata is 256:
      If thealg field ofjwk is present, and is not "A256CBC", thenthrow aDataError.
      Otherwise:
      throw aDataError.
    6. Ifusages is non-empty and theuse field ofjwk is present and is not "enc", thenthrow aDataError.

    7. If thekey_ops field ofjwk is present, and is invalid according to the requirements of JSON Web Key [JWK] or does not contain all of the specifiedusages values, thenthrow aDataError.

    8. If theext field ofjwk is present and has the value false andextractable is true, thenthrow aDataError.

    Otherwise:
    throw aNotSupportedError
  3. Letkey be a newCryptoKey object representing an AES key with valuedata.

  4. Set the[[type]] internal slot ofkey to "secret".

  5. Letalgorithm be a newAesKeyAlgorithm.

  6. Set thename attribute ofalgorithm to "AES-CBC".

  7. Set thelength attribute ofalgorithm to the length, in bits, ofdata.

  8. Set the[[algorithm]] internal slot ofkey toalgorithm.

  9. Returnkey.

28.4.5Export Key

  1. If the underlying cryptographic key material represented by the[[handle]] internal slot ofkey cannot be accessed, thenthrow anOperationError.

  2. Ifformat is "raw":
    1. Letdata be abyte sequence containing the raw octets of the key represented by the[[handle]] internal slot ofkey.

    2. Letresult bedata.

    Ifformat is "jwk":
    1. Letjwk be a newJsonWebKey dictionary.

    2. Set thekty attribute ofjwk to the string "oct".

    3. Set thek attribute ofjwk to be a string containing the raw octets of the key represented by the[[handle]] internal slot ofkey, encoded according to Section 6.4 of JSON Web Algorithms [JWA].

    4. If thelength attribute ofkey is 128:
      Set thealg attribute ofjwk to the string "A128CBC".
      If thelength attribute ofkey is 192:
      Set thealg attribute ofjwk to the string "A192CBC".
      If thelength attribute ofkey is 256:
      Set thealg attribute ofjwk to the string "A256CBC".
    5. Set thekey_ops attribute ofjwk to equal theusages attribute ofkey.

    6. Set theext attribute ofjwk to equal the[[extractable]] internal slot ofkey.

    7. Letresult bejwk.

    Otherwise:

    throw aNotSupportedError.

  3. Returnresult.

28.4.6Get key length

  1. If thelength member ofnormalizedDerivedKeyAlgorithm is not 128, 192 or 256, thenthrow anOperationError.

  2. Return thelength member ofnormalizedDerivedKeyAlgorithm.

29.AES-GCM

29.1Description

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-SP800-38D].

29.2Registration

Therecognized algorithm name for this algorithm is "AES-GCM".

OperationParametersResult
encryptAesGcmParamsbyte sequence
decryptAesGcmParamsbyte sequence
generateKeyAesKeyGenParamsCryptoKey
importKeyNoneCryptoKey
exportKeyNoneobject
get key lengthAesDerivedKeyParamsInteger

29.3AesGcmParams dictionary

WebIDLdictionaryAesGcmParams :Algorithm {  requiredBufferSourceiv;BufferSourceadditionalData;  [EnforceRange]octettagLength;};

Theiv member represents the initialization vector to use. May be up to 2^64-1 bytes long.

TheadditionalData member represents the additional authentication data to include.

ThetagLength member represents the desired length of the authentication tag. May be 0 - 128.

29.4Operations

29.4.1Encrypt

  1. Ifplaintext has alength greater than 2^39 - 256 bytes, thenthrow anOperationError.

  2. If theiv member ofnormalizedAlgorithm has alength greater than 2^64 - 1 bytes, thenthrow anOperationError.

  3. If theadditionalData member ofnormalizedAlgorithm is present and has alength greater than 2^64 - 1 bytes, thenthrow anOperationError.

  4. If thetagLength member ofnormalizedAlgorithm is not present:
    LettagLength be 128.
    If thetagLength member ofnormalizedAlgorithm is one of 32, 64, 96, 104, 112, 120 or 128:
    LettagLength be equal to thetagLength member ofnormalizedAlgorithm
    Otherwise:
    throw anOperationError.
  5. LetadditionalData be theadditionalData member ofnormalizedAlgorithm if present or an emptybyte sequence otherwise.

  6. LetC andT be the outputs that result from performing the Authenticated Encryption Function described in Section 7.1 of [NIST-SP800-38D] using AES as the block cipher, theiv member ofnormalizedAlgorithm as theIV input parameter,additionalData as theA input parameter,tagLength as thet pre-requisite andplaintext as the input plaintext.

  7. Letciphertext be equal toC |T, where '|' denotes concatenation.

  8. Returnciphertext.

29.4.2Decrypt

  1. If thetagLength member ofnormalizedAlgorithm is not present:
    LettagLength be 128.
    If thetagLength member ofnormalizedAlgorithm is one of 32, 64, 96, 104, 112, 120 or 128:
    LettagLength be equal to thetagLength member ofnormalizedAlgorithm
    Otherwise:
    throw anOperationError.
  2. Ifciphertext has alength in bits less thantagLength, thenthrow anOperationError.

  3. If theiv member ofnormalizedAlgorithm has alength greater than 2^64 - 1 bytes, thenthrow anOperationError.

  4. If theadditionalData member ofnormalizedAlgorithm is present and has alength greater than 2^64 - 1 bytes, thenthrow anOperationError.

  5. Lettag be the lasttagLength bits ofciphertext.

  6. LetactualCiphertext be the result of removing the lasttagLength bits fromciphertext.

  7. LetadditionalData be theadditionalData member ofnormalizedAlgorithm if present or an emptybyte sequence otherwise.

  8. Perform the Authenticated Decryption Function described in Section 7.2 of [NIST-SP800-38D] using AES as the block cipher, theiv member ofnormalizedAlgorithm as theIV input parameter,additionalData as theA input parameter,tagLength as thet pre-requisite,actualCiphertext as the input ciphertext,C andtag as the authentication tag,T.

    If the result of the algorithm is the indication of inauthenticity, "FAIL":
    throw anOperationError
    Otherwise:
    Letplaintext be the outputP of the Authenticated Decryption Function.
  9. Returnplaintext.

29.4.3Generate Key

  1. Ifusages contains any entry which is not one of "encrypt", "decrypt", "wrapKey" or "unwrapKey", thenthrow aSyntaxError.

  2. If thelength member ofnormalizedAlgorithm is not equal to one of 128, 192 or 256, thenthrow anOperationError.

  3. Generate an AES key of length equal to thelength member ofnormalizedAlgorithm.

  4. If the key generation step fails, thenthrow anOperationError.

  5. Letkey be a newCryptoKey object representing the generated AES key.

  6. Letalgorithm be a newAesKeyAlgorithm.

  7. Set thename attribute ofalgorithm to "AES-GCM".

  8. Set thelength attribute ofalgorithm to equal thelength member ofnormalizedAlgorithm.

  9. Set the[[type]] internal slot ofkey to "secret".

  10. Set the[[algorithm]] internal slot ofkey toalgorithm.

  11. Set the[[extractable]] internal slot ofkey to beextractable.

  12. Set the[[usages]] internal slot ofkey to beusages.

  13. Returnkey.

29.4.4Import Key

  1. Ifusages contains an entry which is not one of "encrypt", "decrypt", "wrapKey" or "unwrapKey", thenthrow aSyntaxError.

  2. Ifformat is "raw":
    1. Letdata bekeyData.

    2. If thelength in bits ofdata is not 128, 192 or 256 thenthrow aDataError.

    Ifformat is "jwk":
    1. IfkeyData is aJsonWebKey dictionary:

      Letjwk equalkeyData.

      Otherwise:

      Throw aDataError.

    2. If thekty field ofjwk is not "oct", thenthrow aDataError.

    3. Ifjwk does not meet the requirements of Section 6.4 of JSON Web Algorithms [JWA], thenthrow aDataError.

    4. Letdata be thebyte sequence obtained by decoding thek field ofjwk.

    5. If thelength in bits ofdata is 128:
      If thealg field ofjwk is present, and is not "A128GCM", thenthrow aDataError.
      If thelength in bits ofdata is 192:
      If thealg field ofjwk is present, and is not "A192GCM", thenthrow aDataError.
      If thelength in bits ofdata is 256:
      If thealg field ofjwk is present, and is not "A256GCM", thenthrow aDataError.
      Otherwise:
      throw aDataError.
    6. Ifusages is non-empty and theuse field ofjwk is present and is not "enc", thenthrow aDataError.

    7. If thekey_ops field ofjwk is present, and is invalid according to the requirements of JSON Web Key [JWK] or does not contain all of the specifiedusages values, thenthrow aDataError.

    8. If theext field ofjwk is present and has the value false andextractable is true, thenthrow aDataError.

    Otherwise:
    throw aNotSupportedError.
  3. Letkey be a newCryptoKey object representing an AES key with valuedata.

  4. Set the[[type]] internal slot ofkey to "secret".

  5. Letalgorithm be a newAesKeyAlgorithm.

  6. Set thename attribute ofalgorithm to "AES-GCM".

  7. Set thelength attribute ofalgorithm to the length, in bits, ofdata.

  8. Set the[[algorithm]] internal slot ofkey toalgorithm.

  9. Returnkey.

29.4.5Export Key

  1. If the underlying cryptographic key material represented by the[[handle]] internal slot ofkey cannot be accessed, thenthrow anOperationError.

  2. Ifformat is "raw":
    1. Letdata be abyte sequence containing the raw octets of the key represented by the[[handle]] internal slot ofkey.

    2. Letresult bedata.

    Ifformat is "jwk":
    1. Letjwk be a newJsonWebKey dictionary.

    2. Set thekty attribute ofjwk to the string "oct".

    3. Set thek attribute ofjwk to be a string containing the raw octets of the key represented by the[[handle]] internal slot ofkey, encoded according to Section 6.4 of JSON Web Algorithms [JWA].

    4. If thelength attribute ofkey is 128:
      Set thealg attribute ofjwk to the string "A128GCM".
      If thelength attribute ofkey is 192:
      Set thealg attribute ofjwk to the string "A192GCM".
      If thelength attribute ofkey is 256:
      Set thealg attribute ofjwk to the string "A256GCM".
    5. Set thekey_ops attribute ofjwk to equal theusages attribute ofkey.

    6. Set theext attribute ofjwk to equal the[[extractable]] internal slot ofkey.

    7. Letresult bejwk.

    Otherwise:

    throw aNotSupportedError.

  3. Returnresult.

29.4.6Get key length

  1. If thelength member ofnormalizedDerivedKeyAlgorithm is not 128, 192 or 256, thenthrow anOperationError.

  2. Return thelength member ofnormalizedDerivedKeyAlgorithm.

30.AES-KW

30.1Description

This section is non-normative.

The "AES-KW" algorithm identifier is used to perform key wrapping using AES, as described in [RFC3394].

30.2Registration

Therecognized algorithm name for this algorithm is "AES-KW".

OperationParametersResult
wrapKeyNonebyte sequence
unwrapKeyNonebyte sequence
generateKeyAesKeyGenParamsCryptoKey
importKeyNoneCryptoKey
exportKeyNoneobject
get key lengthAesDerivedKeyParamsInteger

30.3Operations

30.3.1Wrap Key

  1. Ifplaintext is not a multiple of 64 bits in length, thenthrow anOperationError.

  2. Letciphertext be the result of performing the Key Wrap operation described in Section 2.2.1 of [RFC3394] withplaintext as the plaintext to be wrapped and using the default Initial Value defined in Section 2.2.3.1 of the same document.

  3. Returnciphertext.

30.3.2Unwrap Key

  1. Letplaintext be the result of performing the Key Unwrap operation described in Section 2.2.2 of [RFC3394] withciphertext 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, thenthrow anOperationError.

  3. Returnplaintext.

30.3.3Generate Key

  1. Ifusages contains any entry which is not one of "wrapKey" or "unwrapKey", thenthrow aSyntaxError.

  2. If thelength property ofnormalizedAlgorithm is not equal to one of 128, 192 or 256, thenthrow anOperationError.

  3. Generate an AES key of length equal to thelength member ofnormalizedAlgorithm.

  4. If the key generation step fails, thenthrow anOperationError.

  5. Letkey be a newCryptoKey object representing the generated AES key.

  6. Letalgorithm be a newAesKeyAlgorithm.

  7. Set thename attribute ofalgorithm to "AES-KW".

  8. Set thelength attribute ofalgorithm to equal thelength property ofnormalizedAlgorithm.

  9. Set the[[type]] internal slot ofkey to "secret".

  10. Set the[[algorithm]] internal slot ofkey toalgorithm.

  11. Set the[[extractable]] internal slot ofkey to beextractable.

  12. Set the[[usages]] internal slot ofkey to beusages.

  13. Returnkey.

30.3.4Import Key

  1. Ifusages contains an entry which is not one of "wrapKey" or "unwrapKey", thenthrow aSyntaxError.

  2. Ifformat is "raw":
    1. Letdata bekeyData.

    2. If thelength in bits ofdata is not 128, 192 or 256 thenthrow aDataError.

    Ifformat is "jwk":
    1. IfkeyData is aJsonWebKey dictionary:

      Letjwk equalkeyData.

      Otherwise:

      Throw aDataError.

    2. If thekty field ofjwk is not "oct", thenthrow aDataError.

    3. Ifjwk does not meet the requirements of Section 6.4 of JSON Web Algorithms [JWA], thenthrow aDataError.

    4. Letdata be thebyte sequence obtained by decoding thek field ofjwk.

    5. If thelength in bits ofdata is 128:
      If thealg field ofjwk is present, and is not "A128KW", thenthrow aDataError.
      If thelength in bits ofdata is 192:
      If thealg field ofjwk is present, and is not "A192KW", thenthrow aDataError.
      If thelength in bits ofdata is 256:
      If thealg field ofjwk is present, and is not "A256KW", thenthrow aDataError.
      Otherwise:
      throw aDataError.
    6. Ifusages is non-empty and theuse field ofjwk is present and is not "enc", thenthrow aDataError.

    7. If thekey_ops field ofjwk is present, and is invalid according to the requirements of JSON Web Key [JWK] or does not contain all of the specifiedusages values, thenthrow aDataError.

    8. If theext field ofjwk is present and has the value false andextractable is true, thenthrow aDataError.

    Otherwise:
    throw aNotSupportedError.
  3. Letkey be a newCryptoKey representing an AES key with valuedata.

  4. Set the[[type]] internal slot ofkey to "secret".

  5. Letalgorithm be a newAesKeyAlgorithm.

  6. Set thename attribute ofalgorithm to "AES-KW".

  7. Set thelength attribute ofalgorithm to the length, in bits, ofdata.

  8. Set the[[algorithm]] internal slot ofkey toalgorithm.

  9. Returnkey.

30.3.5Export Key

  1. If the underlying cryptographic key material represented by the[[handle]] internal slot ofkey cannot be accessed, thenthrow anOperationError.

  2. Ifformat is "raw":
    1. Letdata be abyte sequence containing the raw octets of the key represented by the[[handle]] internal slot ofkey.

    2. Letresult bedata.

    Ifformat is "jwk":
    1. Letjwk be a newJsonWebKey dictionary.

    2. Set thekty attribute ofjwk to the string "oct".

    3. Set thek attribute ofjwk to be a string containing the raw octets of the key represented by the[[handle]] internal slot ofkey, encoded according to Section 6.4 of JSON Web Algorithms [JWA].

    4. If thelength attribute ofkey is 128:
      Set thealg attribute ofjwk to the string "A128KW".
      If thelength attribute ofkey is 192:
      Set thealg attribute ofjwk to the string "A192KW".
      If thelength attribute ofkey is 256:
      Set thealg attribute ofjwk to the string "A256KW".
    5. Set thekey_ops attribute ofjwk to equal theusages attribute ofkey.

    6. Set theext attribute ofjwk to equal the[[extractable]] internal slot ofkey.

    7. Letresult bejwk.

    Otherwise:

    throw aNotSupportedError.

  3. Returnresult.

30.3.6Get key length

  1. If thelength member ofnormalizedDerivedKeyAlgorithm is not 128, 192 or 256, thenthrow anOperationError.

  2. Return thelength member ofnormalizedDerivedKeyAlgorithm.

31.HMAC

31.1Description

This section is non-normative.

TheHMAC algorithm calculates and verifies hash-based message authentication codes according to [FIPS-198-1] using the SHA hash functions defined in this specification.

Other specifications may specify the use of additional hash algorithms with HMAC. Such specifications must define the digest operation for the additional hash algorithms andkey import steps andkey export steps for HMAC.

31.2Registration

Therecognized algorithm name for this algorithm is "HMAC".

OperationParametersResult
signNonebyte sequence
verifyNoneboolean
generateKeyHmacKeyGenParamsCryptoKey
importKeyHmacImportParamsCryptoKey
exportKeyNoneobject
get key lengthHmacImportParamsInteger

31.3HmacImportParams dictionary

WebIDLdictionaryHmacImportParams :Algorithm {  requiredHashAlgorithmIdentifierhash;  [EnforceRange]unsigned longlength;};

Thehash member represents the inner hash function to use.

Thelength member represent the length (in bits) of the key.

31.4HmacKeyAlgorithm dictionary

WebIDLdictionaryHmacKeyAlgorithm :KeyAlgorithm {  requiredKeyAlgorithmhash;  requiredunsigned longlength;};

Thehash member represents the inner hash function to use.

Thelength member represent the length (in bits) of the key.

31.5HmacKeyGenParams dictionary

WebIDLdictionaryHmacKeyGenParams :Algorithm {  requiredHashAlgorithmIdentifierhash;  [EnforceRange]unsigned longlength;};

Thehash member represents the inner hash function to use.

Thelength member represent 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.

31.6Operations

31.6.1Sign

  1. Letmac be the result of performing the MAC Generation operation described in Section 4 of [FIPS-198-1] using the key represented by the[[handle]] internal slot ofkey, the hash function identified by thehash attribute of the[[algorithm]] internal slot ofkey andmessage as the input datatext.

  2. Returnmac.

31.6.2Verify

  1. Letmac be the result of performing the MAC Generation operation described in Section 4 of [FIPS-198-1] using the key represented by the[[handle]] internal slot ofkey, the hash function identified by thehash attribute of the[[algorithm]] internal slot ofkey andmessage as the input datatext.

  2. Return true ifmac is equal tosignature and false otherwise.

31.6.3Generate Key

  1. Ifusages contains any entry which is not "sign" or "verify", thenthrow aSyntaxError.

  2. If thelength member ofnormalizedAlgorithm is not present:
    Letlength be the block size in bits of the hash function identified by thehash member ofnormalizedAlgorithm.
    Otherwise, if thelength member ofnormalizedAlgorithm is non-zero:
    Letlength be equal to thelength member ofnormalizedAlgorithm.
    Otherwise:
    throw anOperationError.
  3. Generate a key of lengthlength bits.

  4. If the key generation step fails, thenthrow anOperationError.

  5. Letkey be a newCryptoKey object representing the generated key.

  6. Letalgorithm be a newHmacKeyAlgorithm.

  7. Set thename attribute ofalgorithm to "HMAC".

  8. Set thelength attribute ofalgorithm tolength.

  9. Lethash be a newKeyAlgorithm.

  10. Set thename attribute ofhash to equal thename member of thehash member ofnormalizedAlgorithm.

  11. Set thehash attribute ofalgorithm tohash.

  12. Set the[[type]] internal slot ofkey to "secret".

  13. Set the[[algorithm]] internal slot ofkey toalgorithm.

  14. Set the[[extractable]] internal slot ofkey to beextractable.

  15. Set the[[usages]] internal slot ofkey to beusages.

  16. Returnkey.

31.6.4Import Key

  1. LetkeyData be the key data to be imported.

  2. Ifusages contains an entry which is not "sign" or "verify", thenthrow aSyntaxError.

  3. Lethash be a newKeyAlgorithm.

  4. Ifformat is "raw":
    1. Letdata bekeyData.

    2. Sethash to equal thehash member ofnormalizedAlgorithm.

    Ifformat is "jwk":
    1. IfkeyData is aJsonWebKey dictionary:

      Letjwk equalkeyData.

      Otherwise:

      Throw aDataError.

    2. If thekty field ofjwk is not "oct", thenthrow aDataError.

    3. Ifjwk does not meet the requirements of Section 6.4 of JSON Web Algorithms [JWA], thenthrow aDataError.

    4. Letdata be thebyte sequence obtained by decoding thek field ofjwk.

    5. Set thehash to equal thehash member ofnormalizedAlgorithm.

    6. If thename attribute ofhash is "SHA-1":
      If thealg field ofjwk is present and is not "HS1", thenthrow aDataError.
      If thename attribute ofhash is "SHA-256":
      If thealg field ofjwk is present and is not "HS256", thenthrow aDataError.
      If thename attribute ofhash is "SHA-384":
      If thealg field ofjwk is present and is not "HS384", thenthrow aDataError.
      If thename attribute ofhash is "SHA-512":
      If thealg field ofjwk is present and is not "HS512", thenthrow aDataError.
      Otherwise, if thename attribute ofhash is defined inanother applicable specification:
      Perform anykey import steps defined byother applicable specifications, passingformat,jwk andhash and obtaininghash.
    7. Ifusages is non-empty and theuse field ofjwk is present and is not "sign", thenthrow aDataError.

    8. If thekey_ops field ofjwk is present, and is invalid according to the requirements of JSON Web Key [JWK] or does not contain all of the specifiedusages values, thenthrow aDataError.

    9. If theext field ofjwk is present and has the value false andextractable is true, thenthrow aDataError.

    Otherwise:
    throw aNotSupportedError.
  5. Letlength be thelength in bits ofdata.

  6. Iflength is zero thenthrow aDataError.

  7. If thelength member ofnormalizedAlgorithm is present:
    If thelength member ofnormalizedAlgorithm is greater thanlength:
    throw aDataError.
    If thelength member ofnormalizedAlgorithm, is less than or equal tolength minus eight:
    throw aDataError.
    Otherwise:
    Setlength equal to thelength member ofnormalizedAlgorithm.
  8. Letkey be a newCryptoKey object representing an HMAC key with the firstlength bits ofdata.

  9. Set the[[type]] internal slot ofkey to "secret".

  10. Letalgorithm be a newHmacKeyAlgorithm.

  11. Set thename attribute ofalgorithm to "HMAC".

  12. Set thelength attribute ofalgorithm tolength.

  13. Set thehash attribute ofalgorithm tohash.

  14. Set the[[algorithm]] internal slot ofkey toalgorithm.

  15. Returnkey.

31.6.5Export Key

  1. If the underlying cryptographic key material represented by the[[handle]] internal slot ofkey cannot be accessed, thenthrow anOperationError.

  2. Letbits be the raw bits of the key represented by the[[handle]] internal slot ofkey.

  3. Letdata be abyte sequence containingbits.

  4. Ifformat is "raw":
    1. Letresult bedata.

    Ifformat is "jwk":
    1. Letjwk be a newJsonWebKey dictionary.

    2. Set thekty attribute ofjwk to the string "oct".

    3. Set thek attribute ofjwk to be a string containingdata, encoded according to Section 6.4 of JSON Web Algorithms [JWA].

    4. Letalgorithm be the[[algorithm]] internal slot ofkey.

    5. Lethash be thehash attribute ofalgorithm.

    6. If thename attribute ofhash is "SHA-1":
      Set thealg attribute ofjwk to the string "HS1".
      If thename attribute ofhash is "SHA-256":
      Set thealg attribute ofjwk to the string "HS256".
      If thename attribute ofhash is "SHA-384":
      Set thealg attribute ofjwk to the string "HS384".
      If thename attribute ofhash is "SHA-512":
      Set thealg attribute ofjwk to the string "HS512".
      Otherwise, thename attribute ofhash is defined inanother applicable specification:
      1. Perform anykey export steps defined byother applicable specifications, passingformat andkey and obtainingalg.

      2. Set thealg attribute ofjwk toalg.

    7. Set thekey_ops attribute ofjwk to equal theusages attribute ofkey.

    8. Set theext attribute ofjwk to equal the[[extractable]] internal slot ofkey.

    9. Letresult bejwk.

    Otherwise:

    throw aNotSupportedError.

  5. Returnresult.

31.6.6Get key length

  1. If thelength member ofnormalizedDerivedKeyAlgorithm is not present:

    Letlength be the block size in bits of the hash function identified by thehash member ofnormalizedDerivedKeyAlgorithm.

    Otherwise, if thelength member ofnormalizedDerivedKeyAlgorithm is non-zero:
    Letlength be equal to thelength member ofnormalizedDerivedKeyAlgorithm.
    Otherwise:
    throw aTypeError.
  2. Returnlength.

32.SHA

32.1Description

This section is non-normative.

This describes the SHA-1 and SHA-2 families, as specified by [FIPS-180-4].

32.2Registration

Therecognized algorithm names are "SHA-1", "SHA-256", "SHA-384", and "SHA-512" for the respective SHA algorithms.

OperationParametersResult
digestNonebyte sequence

32.3Operations

32.3.1Digest

  1. If thename member ofnormalizedAlgorithm is a cases-sensitive string match for "SHA-1":
    Letresult be the result of performing the SHA-1 hash function defined in Section 6.1 of [FIPS-180-4] usingmessage as the input message,M.
    If thename member ofnormalizedAlgorithm is a cases-sensitive string match for "SHA-256":
    Letresult be the result of performing the SHA-256 hash function defined in Section 6.2 of [FIPS-180-4] usingmessage as the input message,M.
    If thename member ofnormalizedAlgorithm is a cases-sensitive string match for "SHA-384":
    Letresult be the result of performing the SHA-384 hash function defined in Section 6.5 of [FIPS-180-4] usingmessage as the input message,M.
    If thename member ofnormalizedAlgorithm is a cases-sensitive string match for "SHA-512":
    Letresult be the result of performing the SHA-512 hash function defined in Section 6.4 of [FIPS-180-4] usingmessage as the input message,M.
  2. If performing the operation results in an error, thenthrow anOperationError.

  3. Returnresult.

33.HKDF

33.1Description

This section is non-normative.

The "HKDF" algorithm identifier is used to perform key derivation using the extraction-then-expansion approach described in [RFC5869] and using the SHA hash functions defined in this specification.

Other specifications may specify the use of additional hash algorithms with HKDF. Such specifications must define the digest operation for the additional hash algorithms.

33.2Registration

Therecognized algorithm name for this algorithm is "HKDF".

OperationParametersResult
deriveBitsHkdfParamsbyte sequence
importKeyNoneCryptoKey
Get key lengthNonenull

33.3HkdfParams dictionary

WebIDLdictionaryHkdfParams :Algorithm {  requiredHashAlgorithmIdentifierhash;  requiredBufferSourcesalt;  requiredBufferSourceinfo;};

Thehash member represents the algorithm to use with HMAC (e.g.: SHA-256).

Thesalt member represents the salt used in the extract step.

Theinfo member represents application specific context for the derived keying material.

33.4Operations

33.4.1Derive Bits

  1. Iflength is null or is not a multiple of 8, thenthrow anOperationError.

  2. LetkeyDerivationKey be the secret represented by the[[handle]] internal slot ofkey.

  3. Letresult be the result of performing the HKDF extract and then the HKDF expand step described in Section 2 of [RFC5869] using:

    • thehash member ofnormalizedAlgorithm asHash,

    • keyDerivationKey as the input keying material,IKM,

    • thesalt member ofnormalizedAlgorithm assalt,

    • theinfo member ofnormalizedAlgorithm asinfo,

    • length divided by 8 as the value ofL,

  4. If the key derivation operation fails, thenthrow anOperationError.

  5. Returnresult.

33.4.2Import key

  1. LetkeyData be the key data to be imported.

  2. Ifformat is "raw":
    1. Ifusages contains a value that is not "deriveKey" or "deriveBits", thenthrow aSyntaxError.

    2. Ifextractable is notfalse, thenthrow aSyntaxError.

    3. Letkey be a newCryptoKey representing the key data provided inkeyData.

    4. Set the[[type]] internal slot ofkey to "secret".

    5. Letalgorithm be a newKeyAlgorithm object.

    6. Set thename attribute ofalgorithm to "HKDF".

    7. Set the[[algorithm]] internal slot ofkey toalgorithm.

    8. Returnkey.

    Otherwise:
    throw aNotSupportedError.

33.4.3Get key length

  1. Return null.

34.PBKDF2

34.1Description

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, as defined in [RFC8018] using HMAC as the pseudo-random function, using the SHA hash functions defined in this specification.

Other specifications may specify the use of additional hash algorithms with PBKDF2. Such specifications must define the digest operation for the additional hash algorithms.

34.2Registration

Therecognized algorithm name for this algorithm is "PBKDF2".

OperationParametersResult
deriveBitsPbkdf2Paramsbyte sequence
importKeyNoneCryptoKey
Get key lengthNonenull

34.3Pbkdf2Params dictionary

WebIDLdictionaryPbkdf2Params :Algorithm {  requiredBufferSourcesalt;  required [EnforceRange]unsigned longiterations;  requiredHashAlgorithmIdentifierhash;};

ThePbkdf2Params dictionary has asalt member, aiterations member, and ahash member.

34.4Operations

34.4.1Derive Bits

  1. Iflength is null or is not a multiple of 8, thenthrow anOperationError.

  2. If theiterations member ofnormalizedAlgorithm is zero, thenthrow anOperationError.

  3. Iflength is zero, return an emptybyte sequence.

  4. Letprf be the MAC Generation function described in Section 4 of [FIPS-198-1] using the hash function described by thehash member ofnormalizedAlgorithm.

  5. Letresult be the result of performing the PBKDF2 operation defined in Section 5.2 of [RFC8018] usingprf as the pseudo-random function,PRF, the password represented by the[[handle]] internal slot ofkey as the password,P, thesalt attribute ofnormalizedAlgorithm as the salt,S, the value of theiterations attribute ofnormalizedAlgorithm as the iteration count,c, andlength divided by 8 as the intended key length,dkLen.

  6. If the key derivation operation fails, thenthrow anOperationError.

  7. Returnresult.

34.4.2Import key

  1. Ifformat is not "raw",throw aNotSupportedError

  2. Ifusages contains a value that is not "deriveKey" or "deriveBits", thenthrow aSyntaxError.

  3. Ifextractable is notfalse, thenthrow aSyntaxError.

  4. Letkey be a newCryptoKey representingkeyData.

  5. Set the[[type]] internal slot ofkey to "secret".

  6. Letalgorithm be a newKeyAlgorithm object.

  7. Set thename attribute ofalgorithm to "PBKDF2".

  8. Set the[[algorithm]] internal slot ofkey toalgorithm.

  9. Returnkey.

34.4.3Get key length

  1. Return null.

35.JavaScript Example Code

35.1Generate two key pairs, derive a shared key, encrypt some data

This example generates two X25519 key pairs, one for Alice and one for Bob, performs a key agreement between them, derives a 256-bit AES-GCM key from the result using HKDF with SHA-256, and encrypts and decrypts some data with it.

Example 1: X25519 key agreement
// Generate a key pair for Alice.const alice_x25519_key =await crypto.subtle.generateKey('X25519',false/* extractable */, ['deriveKey']);const alice_private_key = alice_x25519_key.privateKey;// Normally, the public key would be sent by Bob to Alice in advance over some authenticated channel.// In this example, we'll generate another key pair and use its public key instead.const bob_x25519_key =await crypto.subtle.generateKey('X25519',false/* extractable */, ['deriveKey']);const bob_public_key = bob_x25519_key.publicKey;// Perform the key agreement.const alice_x25519_params = {name:'X25519',public: bob_public_key };const alice_shared_key =await crypto.subtle.deriveKey(alice_x25519_params, alice_private_key,'HKDF',false/* extractable */, ['deriveKey']);// Derive a symmetric key from the result.const salt = crypto.getRandomValues(newUint8Array(32));const info =newTextEncoder().encode('X25519 key agreement for an AES-GCM-256 key');const hkdf_params = {name:'HKDF',hash:'SHA-256', salt, info };const gcm_params = {name:'AES-GCM',length:256 };const alice_symmetric_key =await crypto.subtle.deriveKey(hkdf_params, alice_shared_key, gcm_params,false/* extractable */, ['encrypt','decrypt']);// Encrypt some data with the symmetric key, and send it to Bob. The IV must be passed along as well.const iv = crypto.getRandomValues(newUint8Array(12));const message =newTextEncoder().encode('Hi Bob!');const encrypted =await crypto.subtle.encrypt({ ...gcm_params, iv }, alice_symmetric_key, message);// On Bob's side, Alice's public key and Bob's private key are used, instead.// To get the same result, Alice and Bob must agree on using the same salt and info.const alice_public_key = alice_x25519_key.publicKey;const bob_private_key = bob_x25519_key.privateKey;const bob_x25519_params = {name:'X25519',public: alice_public_key };const bob_shared_key =await crypto.subtle.deriveKey(bob_x25519_params, bob_private_key,'HKDF',false/* extractable */, ['deriveKey']);const bob_symmetric_key =await crypto.subtle.deriveKey(hkdf_params, bob_shared_key, gcm_params,false/* extractable */, ['encrypt','decrypt']);// On Bob's side, the data can be decrypted.const decrypted =await crypto.subtle.decrypt({ ...gcm_params, iv }, bob_symmetric_key, encrypted);const decrypted_message =newTextDecoder().decode(decrypted);

35.2Generate a signing key pair, sign some data

Example 2: Ed25519 signing
const data =newTextEncoder().encode('Hello, world!');const key =await crypto.subtle.generateKey('Ed25519',false, ['sign']);const signature =await crypto.subtle.sign('Ed25519', key.privateKey, data);

35.3Generate a symmetric key, encrypt some data

Example 3: AES-GCM encryption
const data =newTextEncoder().encode('Hello, world!');const aesAlgorithmKeyGen = {name:'AES-GCM',// AesKeyGenParamslength:256};const aesAlgorithmEncrypt = {name:'AES-GCM',// AesGcmParamsiv: crypto.getRandomValues(newUint8Array(16))};const key =await crypto.subtle.generateKey(aesAlgorithmKeyGen,false, ['encrypt']);const encrypted =await crypto.subtle.encrypt(aesAlgorithmEncrypt, key, data);

35.4Generate unique name for download

Example 4: Random UUID generation
const filename =`${crypto.randomUUID()}.txt`;

36.IANA Considerations

36.1JSON 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.

36.2JSON Web Key Parameters Registration

37.Acknowledgments

Thanks are due especially to Ryan Sleevi, the original author and editor, and Mark Watson, the former editor of this document.

Thanks to Adam Barth, Alex Russell, Ali Asad, Arun Ranganathan, Brian Smith, Brian Warner, Channy Yun, Charles Engelke, Eric Roman, Glenn Adams, Jim Schaad, Kai Engert, Michael Hutchinson, Michael B. Jones, Nick Van den Bleeken, Richard Barnes, Ryan Hurst, Tim Taubert, Vijay Bharadwaj, Virginie Galindo, and Wan-Teh Chang for their technical feedback and assistance.

Thanks to theW3C Web Cryptography WG, and to participants on the public-webcrypto@w3.org mailing list.

TheW3C would like to thank theNorthrop Grumman Cybersecurity Research Consortium for supportingW3C/MIT.

ThegetRandomValues method in theCrypto interface was originally proposed by Adam Barth to theWHATWG.

A.Mapping between JSON Web Key / JSON Web Algorithm

This section is non-normative.

Refer to algorithm-specific sections for the normative requirements of importing and exporting JWK.

A.1Algorithm mappings

JSON Web KeyAlgorithmIdentifier
{kty:"RSA",alg:"RS1" }
{name:"RSASSA-PKCS1-v1_5",hash: {name:"SHA-1" }}
{kty:"RSA",alg:"RS256" }
{name:"RSASSA-PKCS1-v1_5",hash: {name:"SHA-256" }}
{kty:"RSA",alg:"RS384" }
{name:"RSASSA-PKCS1-v1_5",hash: {name:"SHA-384" }}
{kty:"RSA",alg:"RS512" }
{name:"RSASSA-PKCS1-v1_5",hash: {name:"SHA-512" }}
{kty:"RSA",alg:"PS256" }
{name:"RSA-PSS",hash: {name:"SHA-256" }}
{kty:"RSA",alg:"PS384" }
{name:"RSA-PSS",hash: {name:"SHA-384" }}
{kty:"RSA",alg:"PS512" }
{name:"RSA-PSS",hash: {name:"SHA-512" }}
{kty:"RSA",alg:"RSA-OAEP" }
{name:"RSA-OAEP",hash: {name:"SHA-1" }}
{kty:"RSA",alg:"RSA-OAEP-256" }
{name:"RSA-OAEP",hash: {name:"SHA-256" }}
{kty:"RSA",alg:"RSA-OAEP-384" }
{name:"RSA-OAEP",hash: {name:"SHA-384" }}
{kty:"RSA",alg:"RSA-OAEP-512" }
{name:"RSA-OAEP",hash: {name:"SHA-512" }}
{kty:"EC",alg:"ES256" }
{name:"ECDSA",namedCurve:"P-256",hash: {name:"SHA-256" }}
{kty:"EC",alg:"ES384" }
{name:"ECDSA",namedCurve:"P-384",hash: {name:"SHA-384" }}
{kty:"EC",alg:"ES512" }
{name:"ECDSA",namedCurve:"P-521",hash: {name:"SHA-512" }}
{kty:"OKP",crv:"Ed25519",alg:"Ed25519" }
{name:"Ed25519" }
{kty:"OKP",crv:"X25519" }
{name:"X25519" }
{kty:"oct",alg:"A128CTR" }
{name:"AES-CTR",length:128 }
{kty:"oct",alg:"A192CTR" }
{name:"AES-CTR",length:192 }
{kty:"oct",alg:"A256CTR" }
{name:"AES-CTR",length:256 }
{kty:"oct",alg:"A128CBC" }
{name:"AES-CBC",length:128 }
{kty:"oct",alg:"A192CBC" }
{name:"AES-CBC",length:192 }
{kty:"oct",alg:"A256CBC" }
{name:"AES-CBC",length:256 }
{kty:"oct",alg:"A128KW" }
{name:"AES-KW",length:128 }
{kty:"oct",alg:"A192KW" }
{name:"AES-KW",length:192 }
{kty:"oct",alg:"A256KW" }
{name:"AES-KW",length:256 }
{kty:"oct",alg:"A128GCM" }
{name:"AES-GCM",length:128 }
{kty:"oct",alg:"A192GCM" }
{name:"AES-GCM",length:192 }
{kty:"oct",alg:"A256GCM" }
{name:"AES-GCM",length:256 }
{kty:"oct",alg:"A128GCMKW" }
{name:"AES-GCM",length:128 }
{kty:"oct",alg:"A192GCMKW" }
{name:"AES-GCM",length:192 }
{kty:"oct",alg:"A256GCMKW" }
{name:"AES-GCM",length:256 }
{kty:"oct",alg:"HS1" }
{name:"HMAC",hash: {name:"SHA-1" }}
{kty:"oct",alg:"HS256" }
{name:"HMAC",hash: {name:"SHA-256" }}
{kty:"oct",alg:"HS384" }
{name:"HMAC",hash: {name:"SHA-384" }}
{kty:"oct",alg:"HS512" }
{name:"HMAC",hash:"SHA-512" }

B.Mapping between Algorithm and SubjectPublicKeyInfo

This section is non-normative.

Refer to algorithm-specific sections for the normative requirements of importing and exporting SPKI.

Algorithm OIDsubjectPublicKey ASN.1 structureAlgorithmIdentifierReference
rsaEncryption (1.2.840.113549.1.1.1)RSAPublicKey "RSASSA-PKCS1-v1_5", "RSA-PSS", or "RSA-OAEP" [RFC3447]
id-ecPublicKey (1.2.840.10045.2.1)ECPoint"ECDH" or "ECDSA"[RFC5480]
id-Ed25519 (1.3.101.112)BIT STRING "Ed25519" [RFC8410]
id-X25519 (1.3.101.110)BIT STRING "X25519" [RFC8410]
Note

The object identifiers used by this specification do not include information about the specific algorithm and hash that the key is intended to be used with. If this is required, it's recommended that the "jwk" key format is used instead.

C.Mapping between Algorithm and PKCS#8 PrivateKeyInfo

This section is non-normative.

Refer to algorithm-specific sections for the normative requirements of importing and exporting PKCS#8 PrivateKeyInfo.

privateKeyAlgorithmprivateKey formatAlgorithmIdentifierReference
rsaEncryption (1.2.840.113549.1.1.1)RSAPrivateKey "RSASSA-PKCS1-v1_5", "RSA-PSS", or "RSA-OAEP" [RFC3447]
id-ecPublicKey (1.2.840.10045.2.1)ECPrivateKey"ECDH" or "ECDSA" [RFC5480]
id-Ed25519 (1.3.101.112)CurvePrivateKey "Ed25519" [RFC8410]
id-X25519 (1.3.101.110)CurvePrivateKey "X25519" [RFC8410]

D.References

D.1Normative references

[DOM]
DOM Standard. Anne van Kesteren. WHATWG. Living Standard. URL:https://dom.spec.whatwg.org/
[ECMA-262]
ECMAScript Language Specification. Ecma International. URL:https://tc39.es/ecma262/multipage/
[encoding]
Encoding Standard. Anne van Kesteren. WHATWG. Living Standard. URL:https://encoding.spec.whatwg.org/
[FIPS-180-4]
FIPS PUB 180-4: Secure Hash Standard (SHS). U.S. Department of Commerce/National Institute of Standards and Technology. August 2015. National Standard. URL:https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf
[FIPS-198-1]
The Keyed-Hash Message Authentication Code (HMAC). NIST. July 2008. URL:http://csrc.nist.gov/publications/fips/fips198-1/FIPS-198-1_final.pdf
[HTML]
HTML Standard. Anne van Kesteren; Domenic Denicola; Dominic Farolino; Ian Hickson; Philip Jägenstedt; Simon Pieters. WHATWG. Living Standard. URL:https://html.spec.whatwg.org/multipage/
[Infra]
Infra Standard. Anne van Kesteren; Domenic Denicola. WHATWG. Living Standard. URL:https://infra.spec.whatwg.org/
[JWA]
JSON Web Algorithms (JWA). M. Jones. IETF. May 2015. Proposed Standard. URL:https://www.rfc-editor.org/rfc/rfc7518
[JWK]
JSON Web Key (JWK). M. Jones. IETF. May 2015. Proposed Standard. URL:https://www.rfc-editor.org/rfc/rfc7517
[NIST-SP800-38A]
NIST Special Publication 800-38A: Recommendation for Block Cipher Modes of Operation, Methods and Techniques. NIST. December 2001. URL:http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf
[NIST-SP800-38D]
NIST Special Publication 800-38D: Recommendation for Block Cipher Modes of Operation: Galois/Counter Mode (GCM) and GMAC. NIST. November 2007. URL:http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf
[RFC2119]
Key words for use in RFCs to Indicate Requirement Levels. S. Bradner. IETF. March 1997. Best Current Practice. URL:https://www.rfc-editor.org/rfc/rfc2119
[RFC2141]
URN Syntax. R. Moats. IETF. May 1997. Proposed Standard. URL:https://www.rfc-editor.org/rfc/rfc2141
[RFC2315]
PKCS #7: Cryptographic Message Syntax Version 1.5. B. Kaliski. IETF. March 1998. Informational. URL:https://www.rfc-editor.org/rfc/rfc2315
[RFC3394]
Advanced Encryption Standard (AES) Key Wrap Algorithm. J. Schaad; R. Housley. IETF. September 2002. Informational. URL:https://www.rfc-editor.org/rfc/rfc3394
[RFC3447]
Public-Key Cryptography Standards (PKCS) #1: RSA Cryptography Specifications Version 2.1. J. Jonsson; B. Kaliski. IETF. February 2003. Informational. URL:https://www.rfc-editor.org/rfc/rfc3447
[RFC4122]
A Universally Unique IDentifier (UUID) URN Namespace. P. Leach; M. Mealling; R. Salz. IETF. July 2005. Proposed Standard. URL:https://www.rfc-editor.org/rfc/rfc4122
[RFC5208]
Public-Key Cryptography Standards (PKCS) #8: Private-Key Information Syntax Specification Version 1.2. B. Kaliski. IETF. May 2008. Informational. URL:https://www.rfc-editor.org/rfc/rfc5208
[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. May 2008. Proposed Standard. URL:https://www.rfc-editor.org/rfc/rfc5280
[RFC5480]
Elliptic Curve Cryptography Subject Public Key Information. S. Turner; D. Brown; K. Yiu; R. Housley; T. Polk. IETF. March 2009. Proposed Standard. URL:https://www.rfc-editor.org/rfc/rfc5480
[RFC5869]
HMAC-based Extract-and-Expand Key Derivation Function (HKDF). H. Krawczyk; P. Eronen. IETF. May 2010. Informational. URL:https://www.rfc-editor.org/rfc/rfc5869
[RFC5915]
Elliptic Curve Private Key Structure. S. Turner; D. Brown. IETF. June 2010. Informational. URL:https://www.rfc-editor.org/rfc/rfc5915
[RFC6090]
Fundamental Elliptic Curve Cryptography Algorithms. D. McGrew; K. Igoe; M. Salter. IETF. February 2011. Informational. URL:https://www.rfc-editor.org/rfc/rfc6090
[RFC7748]
Elliptic Curves for Security. A. Langley; M. Hamburg; S. Turner. IETF. January 2016. Informational. URL:https://www.rfc-editor.org/rfc/rfc7748
[RFC8018]
PKCS #5: Password-Based Cryptography Specification Version 2.1. K. Moriarty, Ed.; B. Kaliski; A. Rusch. IETF. January 2017. Informational. URL:https://www.rfc-editor.org/rfc/rfc8018
[RFC8032]
Edwards-Curve Digital Signature Algorithm (EdDSA). S. Josefsson; I. Liusvaara. IETF. January 2017. Informational. URL:https://www.rfc-editor.org/rfc/rfc8032
[RFC8037]
CFRG Elliptic Curve Diffie-Hellman (ECDH) and Signatures in JSON Object Signing and Encryption (JOSE). I. Liusvaara. IETF. January 2017. Proposed Standard. URL:https://www.rfc-editor.org/rfc/rfc8037
[RFC8174]
Ambiguity of Uppercase vs Lowercase in RFC 2119 Key Words. B. Leiba. IETF. May 2017. Best Current Practice. URL:https://www.rfc-editor.org/rfc/rfc8174
[RFC8410]
Algorithm Identifiers for Ed25519, Ed448, X25519, and X448 for Use in the Internet X.509 Public Key Infrastructure. S. Josefsson; J. Schaad. IETF. August 2018. Proposed Standard. URL:https://www.rfc-editor.org/rfc/rfc8410
[SEC1]
SEC 1: Elliptic Curve Cryptography. Certicom Research. URL:http://www.secg.org/sec1-v2.pdf
[WebIDL]
Web IDL Standard. Edgar Chen; Timothy Gu. WHATWG. Living Standard. URL:https://webidl.spec.whatwg.org/
[X690]
Information technology - ASN.1 encoding rules: Specification of Basic Encoding Rules (BER), Canonical Encoding Rules (CER) and Distinguished Encoding Rules (DER). Justin Uberti; Cullen Jennings; Eric Rescorla. ITU-T. November 2008. ITU-T Recommendation. URL:https://tools.ietf.org/html/draft-ietf-rtcweb-jsep/

D.2Informative references

[INDEXEDDB]
Indexed Database API. Nikunj Mehta; Jonas Sicking; Eliot Graff; Andrei Popescu; Jeremy Orlow; Joshua Bell. W3C. 8 January 2015. W3C Recommendation. URL:https://www.w3.org/TR/IndexedDB/


[8]ページ先頭

©2009-2025 Movatter.jp