Web Cryptography API Use Cases

W3C Working Draft 8 January 2013

This Version:
Latest Published Version:
Latest Editor’s Draft:
Arun Ranganathan, Mozilla Corporation <arun@mozilla.com>


This document is NOT a recommendation track document, and should be read as an informative overview of the target use cases for a cryptographic API for the web. These use cases, described as scenarios, represent some of the set of expected functionality that may be achieved by the Web Cryptography API, which provides an API for cryptographic operations such as encryption and decryption, and the Key Discovery API, which specifically covers the ability to access cryptographic keys that have been pre-provisioned. As both APIs are under construction, the reader should consult each specification for changes, and should treat sample code provided here as illustrative only. Presented here are primary use cases, showing what the working group hopes to achieve first. Other use cases are marked as secondary.

Status of this Document

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

This document is the 8 January 2013 First Public Working Draft of the Web Cryptography API Use Cases specification. Please send comments about this document to public-webcrypto@w3.org (archived).

This document is not a recommendation track document, and is presented for information purposes only. Ongoing discussion of this document will be on the public-webcrypto@w3.org mailing list.

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

This document is produced by the Web Cryptography WG in the W3C Interaction Domain.

Web content and browser developers are encouraged to review this draft. Please send comments to public-webcrypto@w3.org, the W3C's public email list for issues related to Web APIs. Archives of the list are available.

This document is produced by the Web Cryptography Working Group, within the W3C Interaction Domain. Changes made to this document can be found in the W3C public Mercurial Repository.

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

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

Table of Contents

1. Introduction

The Web Cryptography API describes a JavaScript API for user agents such as web browsers, and exposes basic cryptographic operations, including: digesting, signature generation and verification, encryption, decryption, cryptographic key generation, key derivation, key import and key export. The Key Discovery API describes a JavaScript API to invoke pre-provisioned keys. This document presents use cases in the form of scenarios that cover the use of both APIs, with each scenario describing a potential web application using these APIs. Where possible, code snippets have been provided to demonstrate what a developer might do when addressing the use case.

2. Requirements

This section presents required features of a cryptographic API. It is possible that there is more than one algorithm and more than one mechanism to accomplish each of these features. The section presents code names for each of the features, which will be used alongside each scenario, illustrating which feature is used.

Additionally, the Web Cryptography WG is actively discussing three other features:

3. Use Case Scenarios

This section collates use case scenarios that leverages the WebCrypto API or the Key Discovery API. Where possible, sample code is provided, and should be considered illustrative only, since the underlying API specifications are changing.

3.1. Banking Transactions

Park Jae-sang opens up a bank account with Gangnam Bank, and wishes to log-in and engage in online transactions, including account balance checking, online payments (with some automated scheduled payments), and account transfers between domestic and investment accounts. The first time Park logs in to the Gangnam Bank website (Gangnam Bank's website from now on will be abbreviated "GB") with a temporary verification code sent to his cell phone, the bank asks him to ascertain if the browser he is using is not at a kiosk; moreover, he is asked if it is a web browser and machine configuration he will use often.

He confirms that it is. The GB web site then asks him to generate a public key/private key pair. Park consents, and the web page creates the key pair, storing his private key in the browser's designated key store, along with a one-time key escrow by the bank. Additionally, Jae-sang is presented with the bank's public key, such that documents issued by the bank can be verified and decrypted; Jae-sang presents the derived public key to GB. Jae-sang is also presented with a user guide that explains the validity period of the key pair, and for how long they will persist. [DERIVE | KEYEX-DH].


GB may first generate some key pairs for Jae-sang. These include the public key/private key pair which will be used for digital signatures.


  // Algorithm Object
var algorithmKeyGen = {
name: "RSASSA-PKCS1-v1_5",
// RsaKeyGenParams
  params: {
    modulusLength: 2048,
    publicExponent: new Uint8Array([0x01, 0x00, 0x01]),  // Equivalent to 65537

var keyGen = window.crypto.generateKey(algorithmKeyGen,
                                       false, // extractable

keyGen.oncomplete = function(event) {

  // Store the key pair in IndexedDB
  // Perform a signing operation

GB may then use a key exchange mechanism to exchange keys with the server over TLS. This includes making sure that the client (Jae-sang) obtains a copy of GB's public key, and that GB obtains a copy of Jae-sang's public key, which were generated in the preceding step.


          TODO add some Diffie-Hellman key exchange code which results in
          1. Jae-sang having GB's public key
          2. GB having Jae-sang's public key

Subsequent access to the GB website -- always over TLS -- is triggered via use of the key that Jae-sang generated when he first accessed the website. JavaScript initially loaded by GB contains a message that only Jae-sang can decipher, since it is encrypted with his public key; moreover, that message is signed by GB, which gives the client confidence that the message originates from GB. The message is deciphered, and the deciphered message is then digitally signed and sent back to the GB server. This establishes identity with non-repudiation. [KEYCALL | VERIFY | DECRYPT-ASSYM | SIGN].


In the example below, an encrypted message is signed by GB. The signature is verified, and upon successful verfication, is decrypted. The decrypted message is then signed and sent to GB. This example should be seen as a simplification for illustrative purposes only, since assymetric encryption and decryption isn't recommended, and techniques such as key wrapping should be used [+UNWRAP].


        // Message generated by GB... the ellipsis are added. 
        var cat = "qANQR1DBw04Dk2uPpEjcJT8QD/0VCfFK2XDM5Cg4iTRwmXrB+Pp8SMK5x09WkYqc... ";

          1. Generate an ArrayBufferView of the overall message.
          2. Bit-manipulate this with the ArrayBufferView API to obtain the portion of bytes 
          constituting the signature as an ArrayBufferView, and the message as an ArrayBufferView.
          3. Obtain the public key of GB from IndexedDB -- pubGBKeySign -- a step not shown here.
          4. Verify the signature ... assume GB provides a method getSignature() to obtain a signature
             from the server against which the message's signature can be verified.

        var data = createArrayBufferView(cat);
        var signature = extractSignature(data);
        var pMessage = extractMessage(data);
        var mRSARFC3447 = {
          name: "RSASSA-PKCS1-v1_5", params: {
                            hash: "SHA-256"
        verifier = window.crypto.verify(mRSARFC3447, pubGBKeySign, signature);
        verifier.oncomplete = function(e){
          If verified, obtain a prvKeyEncrypt from IndexedDB representing Jae-sang's private key and:
          1. Decrypt the message.  Note that here, typically the encryption key might be symmetric
             and wrapped.  This sample simplifies this by not demonstrating key wrapping.
          2. Sign it
          3. Send it back
          Else the signature is invalid -- abort
          if (e.target.result == true)
            var decrypter = window.crypto.decrypt("RSAES-PKCS1-v1_5", prvKeyEncrypt);
            decrypter.onprogress = function(e){e.target.finish()};
            decrypter.oncomplete = function(evt)

            // If successfully decrypted send a signed version back

            message = evt.target.result;

            /* Assume key retrieval code from IndexedDB that results in pubKeySign */
            var signer = window.crypto.sign(mRSARFC3447, pubKeySign, message);
            signer.onprogress = function(e){e.target.finish();}
            signer.oncomplete = function(evt)
                                     Combine signature and signed data into an ArrayBuffer
                                     Use XHR to send signed data back...
                                     Wait for auth token...
          // Unverified signature -- ABORT 

His browser presents this key every time he accesses the website and enters his password, which effectively binds his username and password to the generated private key. Additionally, Jae-sang can digitally sign online checks, authorize payments, and sign tax forms that he submits to the bank site using this generated key [SIGN]. He can also perform the following tasks, following an authentication cycle such as the one described above:

  1. Receive encrypted documents from GB via HTTP that only he can read, with the assurance that they have come from GB and only GB. These include his private bank statements and tax documents, which are signed with his public key, already obtained in a previous step. [VERIFY | UNWRAP| DECRYPT-SYM ].

  2. Submit documents to GB that only GB can read, with the assurance that these have come from Jae-sang. Such documents include confidential financial information, and may be encrypted at submission. [SIGN | DERIVE-SYM | ENCRYPT-SYM | WRAP]

If GB wishes to "cache" aspects of reusuable authentication code, but cannot avail of a code signing system, GB can employ a similar data integrity mechanism that the social networking site uses. Moreover, Jae-sang or GB may at any time reinitiate a key generation operation for subsequent transactions; GB will determine the validity of the keys in question.

3.2. Video Services

A Video Service Provider wishes to distribute high quality commercial video to users of web-enabled TVs and Set Top Boxes. The video in question can only be delivered to devices with certain capabilities that meet the service provider's security requirements, which may vary based on the content and content quality to be delivered. In order to determine whether the device is indeed approved to be used with the video service, the service provider arranges for suitable devices to each be pre-provisioned with a cryptographic key and associated identifier by the device manufacture, which are made known to the service provider.

Ryan has just bought a new TV and wishes to watch video content from the service provider. He connects the TV to the Internet, and navigates to the video provider's website. The video provider's site establishes a secure communication channel between the video provider's page on the TV and the video provider's servers, proving to the servers that Ryan's TV is indeed one of those that meets the security requirements by use of the cryptographic key and identifier pre-provisioned on the TV. The video provider's page on the TV likewise verifies that it is talking to a genuine server, preventing the hijacking of Ryan's video watching by a malicious third party. To ensure the highest security, the pre-provisoned key is used minimally in this process to deliver session keys.



The Key Discovery API describes the provides a mechanism for an application in JavaScript to detect the presence of a pre-provisioned key using the name of a disclosed identifier.

Editorial note

While KeyOperation is asynchronous and event driven, the key retrieval mechanism is synchronous; this might change in subsequent drafts.


var keys = window.getKeysByName("VetFlxL33t_Device.p1a.b11");
keys.onerror = function(e){
  fail("This device is not authorized for Video Service Provider videos.");
keys.oncomplete = function(e){
  if(e.target.result.name == "VetFlxL33t_Device.p1a.b11"){
  // Perform further crypto operations

Ryan creates an account with the service provider and signs up for the lowest level of service, which enables him to connect five devices to the service at any one time. Ryan's account creation involved the creation of a specific key pair to uniquely identify him. [DERIVE-ASSYM | KEYEX | KEYCALL | NAMEDKEY | SIGN ]

The video service provider is able to track the number of devices Ryan has connected to the service by virtue of the pre-provisioned keys and identifiers, so that when he attempts to connect a sixth device, the service can prompt him to upgrade his service level or deactivate one of the existing devices. [KEYCALL | NAMEDKEY]

Ryan finally attempts to play some video through the service. By virtue of the secure connection, the video service provider is able to make content authorization decisions that are tailored to the security capabilities of the exact make, model and version of TV that Ryan has purchased, thereby ensuring that the content providers security requirements are met in respect of the specific content requested. Ryan's devices send encrypted messages about quality of service and watching behavior to the video service provider. [NAMEDKEY | KEYCALL | SIGN | VERIFY | MAC | WRAP | ENCRYPT]

3.3. Code Sanctity and Bandwidth Saver

A major social networking site wishes to optimize website performance by storing JavaScript and other resources in local storage, preventing a needless server roundrip. The social network site wishes to verify that these resources have not been tampered with; the service uses localStorage and IndexedDB to store assets for their web pages, notably JavaScript. Their threat model is such that the social networking site implicitly trusts the HTTP connection (which uses TLS), the browser, and the HTTP cache, but cannot vouch for localStorage or IndexedDB. Let us take the case of a couple who have gone from being "In a Relationship" to "It's Complicated." John Doe uses the social networking site often, while Jane Doe, a JavaScript programmer, packs her bags to move out of the apartment.


This illustrates a worst case scenario, in which localStorage is compromised by a malicious user. Normally, the social networking site deploys code of the sort below, which John Doe's browser runs everytime he logs into the social networking site.


      function init() {
      var src = window.localStorage.getItem('src');
      // up until now env is safe
      if (src) {
        // now whatever code was in src will be executed
      } else {
        // fetch the code using xhr, populate localStorage
        // with it. Execute it.

But at some point in time, a malicious user -- Jane Doe -- with access to the JavaScript console of John Doe's browser does something of the sort:

      window.localStorage.setItem('src', evil_code);
      // evil_code makes requests to Jane Doe's server with data about John Doe

John Doe's use of the social network is thus compromised by Jane Doe's script injection, since the next time he logs in, and init() is called, evil_code is run, which may make requests to Jane's server with query strings that reveal who John chats with, and even the contents of these messages. To mitigate against situations like this, the social networking site might do something like this:


      // Synchronously retrieve a SHA-256 digest of the pristine version of the code
      // This is retrieved from the server
        var src_hash = getHashFromServer();
        function init()
          var src = window.localStorage.getItem('src');

          /*  Create a Digester and compare 

            1. Assume utility function createArrayBufferView that creates an ArrayBufferView of the src
            (and note that the comparison does depend on this being consistent on client and server).

            2. Compare the two values after hashing is successfully completed.

            In practice including an onprogress handler and onerror handler is recommended - the code here
            is terse for readability.


          bufferData = createArrayBufferView(src);
          var digest = window.crypto.digest("SHA-256", bufferData);
          digest.oncomplete = function(e)
            if(e.target.result === src_hash)
                // Fetch the code using XHR and repopulate localStorage


In this case, getHashFromServer() is guaranteed to be untampered with, since it connects to the server or the HTTP cache, which are above suspicion in this threat model.


The conversion to an ArrayBufferView must be consistent with the conversion to bits on the server side, so that the SHA-256 digests can be compared acurately.

Since their threat model trusts the network layer (which includes TLS, and a distributed web cache not entirely on their own servers) but mistrusts the user's machine to store code via localStorage and IndexedDB the WebCrypto API offers mitigations:

  1. As in the example above, the social network can generate a digest of the material extracted from the client storage, and compare this to a pristine version of the digest that the social networking site makes available to the client. If the two digests match, the code is deemed safe. [DIGEST]

  2. They can improve on the model above by "signing with an HMAC" (or "signed hash") and then verifying the HMAC. This model offers one level more robustness, since the verification occurs within the WebCrypto API, as opposed to within the application. [SIGN | HMAC | VERIFY]

3.4. Encrypted Communications via Webmail

Tantek wishes to communicate with Ryan securely. Moreover, Tantek wishes to use an email web application (EWA) provided by a third party, which is a web site that allows users who have accounts to set up email accounts of their own choosing -- that is, users can enter in existing POP/IMAP/SMTP username and password credentials, or simply use an email address provided by the EWA at its own address. The EWA serves to send messages, as well as provide a message store available from anywhere. It allows for the possibility of sending encrypted messages.

Ryan provides a PGP key on his website, encoded in the relevant conventions. For instance, he follows the common practice of including a Base64 text string that represents his public key.


Ryan uses the hCard format to encapsulate contact information with some semantic annotation within the markup of his webpage. Within the hCard, he does something like this:


<span class="key">
Version: GnuPG/MacGPG2 v2.0.17 (Darwin)
Comment: GPGTools - http://gpgtools.org

The ellipsis have been added for brevity.

Logging on to EWA, Tantek is prompted to import Ryan's contact information from his web page, and is notified that Ryan's public key will also be imported. EWA then begins the process of importing Ryan's PGP key, since it understands how to parse public keys within hCard content (see also key examples). In order to import the key for storage under EWA's origin, it must first "scrub" the key format to be in one of the accepted import formats of the WebCrypto API.


Here, the Contacts API [cf. Mozilla][cf. Google][cf. DAP] could be used to procure Ryan's contact information, and can be one way of importing the key for use by an application such as EWA. Due the same origin policy [cf. HTML], EWA must import the key, so that operations conducted with it fall under the domain of EWA. Convert the key to JSON Web Key format, which the WebCrypto API accepts if converted to octets, and then import it for use within the web application.


  1. First convert the PGP key format into an "importable" format by the WebCrypto API; assume "keyString" is the PGP format
     Utility functions are assumed here as well.
  2. Import the key using the WebCrypto API

var alg = "RSA";

var jwkKey = convertToJWK(keyString, alg);

var jwkKeyObject = JSON.parse(jwkKey);

// Convert to ArrayBufferView
var octetsKey = mByteArray(jwkKey);

var importer = window.crypto.importKey("jwk", octetsKey, "RSAES-PKCS1-v1_5", false, ["encrypt", "verify"]);

importer.oncomplete() = function(evt){
  var keyImported = evt.target.result;

    1. Store the new object keyImported in IndexedDB
    2. The Key ID used to store the public key may be Ryan's contact
    3. Or it could be jkwKeyObject.kid

Following the key import and storage sequence, the key now serves as a key within the origin of EWA. EWA can then offer Tantek the option of encrypting messages to Ryan, which may follow the pattern below:

  1. Tantek composes a message that he wishes to send only to Ryan.
  2. EWA generates a symmetric key on Tantek's behalf, and uses Ryan's public key, just imported, to wrap that key. [DERIVE-SYM | KEYCALL | WRAP].
  3. EWA then signs the encrypted message and wrapped key, and sends them from Tantek's email account on Tantek's behalf [SIGN | ENCRYPT-SYM].
  4. Ryan also logs into EWA. Separately, he has also imported Tantek's public key to EWA using a similar mechanism that Ryan did. In this case, as long as Ryan has Tantek's public key, he does not strictly need to log into the same EWA as Tantek does; instead, Ryan may choose another email web application with a different origin, but with similar functionality, such that the public key is imported to be used within the origin of the web application. Ryan receives the message, verifies that it is indeed from Tantek, decrypts and reads the message using his corresponding private key. [KEYCALL | VERIFY | UNWRAP | DECRYPT-SYM].

The use case above contains some risk; unless the source and provenance of keys are understood and trusted, the model above for "across the web" key importing lends itself to abuse by malicious users.

3.5. Off The Record Real Time Messaging

David and Nadim wish to have an "Off The Record" chat in real time, completely between them, primarily using text, as well as the ability to share digital data such as photographs. They log on to a chat server, and connect to each other's machines directly. The server merely serves up the UI for the chat client, and does not log their conversation (and in fact, cannot). The respective web pages on David and Nadim's browsers may use the WebCrypto API to do the following things:

  1. Generate assymetric keys for David and Nadim respectively, such that both get public and private keys. [DERIVE]

  2. Engage in a key exchange, so that David and Nadim get each other's public keys. It is conceivable that using the WebCrypto API the chat application can enable David and Nadim to use a Diffie-Hellman key exchange, or a mechanism such as SIGMA [cf.OTR] over WebSockets [cf. HTML]. The key exchange which accompanies message exchanges involves the generation of cryptographically secure random numbers. [RANDOM | KEYEX | KEYEX-DH]

  3. David or Nadim may now compose a message to each other. Each message exchange involves authentication, message authentication codes, further key derivation, and further key exchanges. [SIGN | VERIFY | MAC | RANDOM | DERIVE | KEYEX | KEYEX-DH]

Editorial note

This use case needs additional details.

3.6. Documents In the Cloud

Vijay wishes to confidentially store certain documents of various file types using a web service that he pays a monthly subscription to for such confidential storage. The confidential storage web application (abbreviated "SWA") makes the claim that all storage is encrypted, and that even it cannot access the contents of what a user stores. He can drag and drop content from his laptop onto a web page of the service, and it automatically encrypts it and stores it in an encrypted manner. Vijay can do the following:

  1. Log on to the service using his credentials; after the service determines that Vijay is using his primary browser, which he will use to access the service subsequently, it generates both signature and encryption key pairs. Derivation may be similar to the banking use case. [DERIVE-ASSYM | KEYEX-DH | VERIFY | UNWRAP | DECRYPT-SYM | SIGN]

  2. Drag over content from his underlying file system that he wishes to store. The SWA encrypts the content, and uploads it. It may make multipart cryptographic operations on a given file, and it may also "chunk upload" large content, depending on file-size. [SIGN | HMAC | DERIVE-SYM | ENCRYPT-SYM | KEYCALL | WRAP]


    Multipart cryptographic operations can be performed with the same key.

    // TODO: Demonstrate multi-part cryptographic operations
  3. Store that content on the server, with the assurance that it is stored there in a way that is virtually undecipherable to third-parties, including those running the SWA.

  4. Later, Vijay can retrieve the content, and save it back to his local file system. He has the assurance that the content has not been tampered with since it was stored, and that it in fact is from SWA. [KEYCALL | VERIFY | HMAC | UNWRAP | DECRYPT-SYM]

4. References

Web Cryptography API
Web Cryptography API, D. Dahl, R. Sleevi. W3C
WebCrypto Key Discovery API
WebCrypto Key Discovery, M. Watson. W3C
Web Storage
Web Storage, I. Hickson. W3C
Indexed Database API, N. Mehta, J. Sicking, E. Graff, A. Popescu, J. Orlow. W3C
Typed Array Specification
Typed Array Specification, Editor's Draft, D. Herman, K. Russell. W3C
The Transport Layer Security (TLS) Protocol, T. Dierks, E. Rescorla. W3C
Off-the-Record Messaging Protocol version 3, cypherpunks.ca
hCard, T. Celik, B. Suda. microformats.org
Microformats Key Examples
Key Examples, T. Celik. microformats.org
JSON Web Key
JSON Web Key (JWK) draft-ietf-jose-json-web-key-07, M. Jones. IETF
Google Contacts API
Google Contacts API v. 3.0, Google
Mozilla Contacts API
Mozilla Proposed Contacts API, Mozilla
Pick Contacts Intent
Pick Contacts IntentR. Tibbett, R. Berjon. W3C
HTML Living Standard, I. Hickson. WHATWG