# The Web Cryptography API: Do not Trust Anybody! [Part 1]

Autor:in
Lesezeit
25 ​​min

IT systems are of central importance in (almost) every area. Particularly in the context of critical infrastructures or sensitive personal data, IT security is of paramount. Furthermore, in order to prevent any interception or misuse of data and to comply with legal requirements, end-to-end encryption is mandatory. Hence, in the context of modern web applications, the encryption needs to be done on the client side. Therefore, the cryptographic operation needs to be done using the Browser and JavaScript. Historically speaking, cryptographic libraries for JavaScript were added as external libraries to projects. The cryptographic operations are executed in the main thread and execution environment, without any protection, incurring performance losses and security gaps.

The goal of this series of blog articles is to evaluate the Web Cryptography specification before analysing the Web Cryptography API. Finally a sample application using the new API is implemented, which extends existing cloud storage services with the option to encrypt all files on the client side by WCA prior upload. This should be a proof of concept for the antitheton of secure public cloud storage. The bachelor thesis discussing this topic was written in German and can be accessed freely (DOI: 10.13140/RG.2.2.11844.14724).

## Motivation

The emerging trend of Single-Page-Applications, which has been spurred by the rapid development and spread of JavaScript and the constant optimization of the JavaScript execution environment [34], is becoming a reality for more and more websites.

Similarly, cloud computing is the means of choice for modern web applications to access different resources such as SaaS, PaaS and IaaS. The figures of the statistics “Umsatz mit Cloud Computing** weltweit von 2009 bis 2018 und Prognose bis 2022 (in Milliarden US-Dollar)” shows that the use of digital media and the storage of data have become an integral part of our daily lives [7]. According to Bitkom, in 2018 73% of the participants used cloud computing in companies and 35% of them used a public cloud provider [1, 2]. The advantages for cloud storage and cloud computing are manyfold: no hardware needs to be bought, networks are configured by software, data is redundantly secured and highly available and in line with the protection goals of information security [28]. Authors Singh and Jangwal argue this in their article „Cost breakdown of Public Cloud Computing and Private Cloud Computing and Security Issues“, but it must always be borne in mind that in the public cloud special attention must be paid to IT security and data protection compliance [30].

Additionally, due to data security breaches in 2019, interest in IT security and data protection is growing even faster [31, 12], especially after Edward Snowden revealed the ubiquitous surveillance by the NSA and governments [9].

The ZDF Politbarometer surveyed 1,159 voters in 2018 whether they believe that internet services such as Google or Facebook comply with legal data protection regulations, which was denied by about 83% of all respondents [118]. Although there is mistrust in various web applications, more and more confidential data is being stored within those applications. Hence, a need for client-side encryption is imperative in order to transparently protect data from third parties. For example, uploading encrypted data to a cloud storage should be intuitive and possible without in-depth technical understanding, so that anyone  can operate the software.

As mentioned above, many web applications are implemented as SPA. For this reason, all cryptographic operations can be implemented in JavaScript, as demonstrated by the Stanford JavaScript Crypto Library or Forge [32, 5]. However, these implementations are exposed to the execution environment of the main JavaScript thread, which can result in performance losses and security vulnerabilities. For example, secure pseudo-random numbers cannot be generated [16]. In addition, the JavaScript execution environment is suboptimal for cryptographic use cases because it cannot be guaranteed that malicious code will be introduced, for example, via XSS. For instance a side-channel attack can extract a key and thus compromise a user’s private data before it is encrypted [10, 29].

To address these problems, the Web Cryptography Working Group of the World Wide Web Consortium convened to perform client-side cryptographic operations in the native implementation of the user agent. Henceforth, the WCA specification was defined, which provides a low-level interface for interaction with cryptographic key material in rich web applications. This asynchronous interface allows the execution of cryptographic operations that previously could only be performed on the server side.

## Goals

The goals of the WCA are described by the official mailing lists [36] of the Web Cryptography Working Group as well as by the presentation „Re-igniting the Crypto Wars on the Web“ by Halpin at the 29th Chaos Communication Congress: [8]

• All basic cryptographic operations should be available.
• Web applications should become more secure, so that authentication is only possible with certificates to web applications. Furthermore, transport encryption can ensure that only the sender and recipient can read the data in plain text.
• Pseudo-random numbers should be generated sufficiently cryptographically randomly.
• Long-life keys allow users to be uniquely identified, but this should be prevented if possible. Different web applications can exchange the personal key of a user to enable tracking, which will be explained in more detail later.

The following applications are also explicitly excluded: [8, 35]

• Fundamental security problems, such as unencrypted connections, broken cryptographic procedures, non-standard behavior or the behavior of the user agent are not solved by this specification.
• The WCA does not replace parts of transport encryption. The use of TLS or Secure Sockets Layer (SSL) is strongly recommended for all security-critical applications.
• No problems that occur when using JavaScript will be solved.
• Web applications that use WCA do not become secure, but only more secure.
• This standard does not provide protection against attacks such as XSS or CSRF.
• The specification does not implement cryptographic operations, but the API methods only trigger functions that are executed by the user-agent.

The following use cases can be implemented using the WCA. However, one should always remember that the API only specifies operations within the user agent on the client: [35]

• Classical authentication schemes, such as username and password, can be extended with proofs in which the user needs access to secret key material. Furthermore, the web application can achieve authentication within the application itself instead of using TLS client certificates. For example, the application can use the key already stored in the localStorage to automatically log the user on when the affected applications are called.
• Sensitive or personal documents can be exchanged in a protected manner. Here, the document is first encrypted with a secret symmetric key, in order to be able to exchange this key asymmetrically encrypted with the communication partner. Alternatively, the key can also be agreed upon via Diffie-Hellman key exchange.
• The cloud storage providers process uploaded data in plain text. If these providers cannot be trusted, the sensitive data can first be symmetrically encrypted before uploading. As a result, all advantages of cloud providers can be used with maximum data protection.
• Use digital signatures on documents instead of physical signatures.
• In principle, data can be cached locally. The WCA can also ensure that the data has not been altered in an offline attack.
• The security of the message layer through schemes such as Off-the-Record Messaging can be used, even though these messages were received unsecurely.
• The WCA can read and import keys that are stored in JWK format. In addition, JWS and MAC can be validated or encrypted messages can be decrypted JWE.

## Requirements and Concepts

The authors define various safety measures as prerequisites for the WCA to work as specified. The required specifications or RFC are not explained in detail. If, however, special concepts are required to understand how the WCA works, they are described in the appropriate place [8].

The following prerequisites must be observed when using the API: The server and the web application should fulfill all IT security protection goals. In addition, all web applications should communicate securely, i.e. allow transport encryption of all data via TLS/SSL between user agent and server. Furthermore, the cryptographic operations are implemented within the browser, so that no influence on the processing of the data is possible outside the browser [8].

Consequently, this WCA specification focuses on common functionalities between different standardized cryptographic libraries. Therefore, the developer does not have to worry about the underlying implementation of the keystore to generate, manage, or exchange keys. The CryptoKey object is the bridge between the user-agent, which manages the cryptographic raw material in isolation, and the abstraction level. Accordingly, a web application can manipulate the keys without the web application having to be aware of the nature of the underlying key store. In this way, the CryptoKey object is the conceptual equivalent of the JavaScript execution environment [35].

Similarly, the underlying cryptographic implementations may vary between compliant user agents and be subject to local policies. Therefore, the WCA does not prescribe any binding sets of algorithms that must be implemented. Instead, the specification defines a set of conformance requirements, for example to verify that a user agent supports the underlying algorithm [35].

In addition, the WCA can generate, manipulate, and retrieve key material, even though the specification does not deal with the provision of keys to certain types of keystores, such as smart cards or secure elements. Specifically, the specification does not include new storage mechanisms for the CryptoKey objects because any existing or future online or offline web store can be used. For example, an Indexed Database API can be used to provide full flexibility to store additional metadata with CryptoKey objects [35].

Finally, the API does not deal with the discovery of cryptographic modules because they are dependent on the underlying user agent and are not compatible between operating systems or cryptographic implementations [35].

## Functionality

The following section describes the functioning of the WCA. First, the sequence of a simple cryptographic operation is shown schematically in the sequence diagram in order to be able to explain the individual components in detail later on. At no time is there a key in plain text within the JavaScript engine and all cryptographic operations take place in the User-Agent. First, all resources of the SPA are downloaded from the server to the client and executed by the JavaScript runtime. When a cryptographic operation is performed, the JavaScript engine calls the appropriate interface of the WCA and then accesses the keystore to search for and provide the key. Finally, the operations are executed and the result is returned as a promise.

### Components

• Crypto Interface: This component forms the central interface of the WCA, which is accessible via the objects window[80] or Worker [81] in the runtime environment of the browser. The Crypto.subtle property within this object grants access to the SubtleCrypto object, which is responsible for the basic cryptographic operations. Furthermore, the synchronous method Crypto.getRandomValues() generates cryptographically secure pseudo-random numbers based on the interface RandomSource [13, 14].
• RandomSource Interface: The WCA specification does not define a lower limit for the information-theoretical entropy of random values. However, browser implementations should generate cryptographic random values using established cryptographic pseudo-random number generators populated with high quality entropy, such as /dev/urandom [35].
• SubtleCrypto Interface: This interface provides access to basic cryptographic operations and management of the key material. A key is represented as a CryptoKey or CryptoKeyPair object. In the following, all possible methods of the SubtleCrypto object are listed and the supported algorithms are explained in more detail: [35]
• Encrypt and decrypt symmetrical or asymmetrical cryptosystems via the functions crypt bzw. decrypt
• Sign and verify digital signatures with sign and verify
• Generate  a hash value with the hash function digest
• Generate  symmetric or asymmetric keys with the generateKey method with the return values of a symmetric key CryptoKey or an asymmetric key pair CryptoKeyPair
• Derive keys
• Wrap or reveal given key material with other keys using the methods wrapKey and unwrapKey
• Import a key in JWK or PKCS#8 format with the importKey function from key materials with the exportKey method in plain text
• Algorithm Dictionary Interface: The assignment of an algorithm to the corresponding cryptographic operations is realized by the Algorithm Dictionary. The algorithm table clearly maps the algorithms already specified to the corresponding operations. Finally, you can develop your own cryptographic algorithms  and register them in this Algorithm Dictionary after successful normalization [35].

### Cryptographic Methods with Parameterizations

As already explained, the SubtleCrypto interface defines all cryptographic operations. These can be implemented by those algorithms which are compactly represented in the table (LINK). In particular, this table should not be regarded as a recommendation for the use of certain algorithms. Instead, it merely documents which methods are supported. For this reason, it is essential to follow the algorithm section when selecting an algorithm so that all risks and concerns that may arise when using certain algorithms can be understood [35].

However, first the algorithm object and the cryptographic operations, i.e. the functions within the SubtleCrypto Interface, are specified in more detail.

• Algorithm object: The algorithm object is an entry of the Algorithm Dictionary, i.e. an injective assignment of an algorithm to cryptographic operations [35].
• Encryption and decryption: The methods encrypt and decrypt a text buffer source with a symmetric CryptoKey using a given symmetric or asymmetric algorithm. If successful, both functions return a fulfilled promise, which contains either the plaintext $$x$$ or the ciphertext $$y$$ [20, 17].
• Creation and verification of a digital signature: According to the definition, the tuple $$(X; Y; K; E; D)$$ is required to create and verify a digital signature. The key pair $$K= (K_{public}; K_{private})$$ is a CryptoKey object. Furthermore, the signature algorithm $$E$$ and the verification algorithm $$D$$ are combined as an algorithm object. Finally, the function sign can create the digital signature and the function verify can verify the signed message [25, 23].
• Generating a hash value: The method digest transforms a text $$x$$ with the help of a hash function, which is defined as an algorithm object, to a hash value $$z$$ [19].
• Generating and deriving a symmetric or asymmetric key: The generateKey function creates new CryptoKey or CryptoKeyPair objects for symmetric or asymmetric encryption. The parameter extractable specifies whether the key may be exported or derived.  Furthermore, a list of intended uses must be specified so that only the specified cryptographic operations can access the key material [73].In addition to the existing parameters, when deriving a key by deriveKey function, the key to be derived and the derivation function must be specified [18].
• Importing or exporting keys: Cryptographic key material can be easily exported from or into different formats.  The WCA supports the convenient formats JWK, Privacy Enhanced Mail (PEM),PKCS#8 or also the processing in a byte array. For the importKey function, the format described above must be specified in addition to the key to be imported. In addition, the same properties (parameter extractable and the list of uses) must be specified as when generating a key [22]. If a key has been declared exportable, it can be exported using the exportKey method, specifying the format [21].
• Hiding and unveiling given key material: The wrapKey function first exports a given key into the external format described in the previous section, so that it can be encrypted afterwards.  Wrapping a key helps to protect it in untrusted environments, such as an unprotected data store or when transmitting over an unsecured medium.This implementation requires an exportable key, the specification of a format and a key that is to be used to wrap the actual key [26]. In contrast, the inverse function unwrapKey expects the specification of additional parameters, such as when creating or importing a key: purpose, algorithm and the parameter extractable [24].

### Correlation of Cryptographic Operations with Algorithms

In the following table the connection between cryptographic operation and the corresponding algorithm is clearly shown.

## The Key Storage

At the heart of the WCA specification is the CryptoKey interface for many different types of key materials managed by the user agent. This unified API can contain keys generated by one user-agent and derived from another. The term key material is used as a general data structure that is typically kept secret, such as the actual key or a nonce [35].

This interface limits any interaction of the user with the key materials to the User Agent, so that the CryptoKey object only has a reference to the underlying raw keys. The cryptographic operations are performed either directly or indirectly, depending on the implementation of the User Agent [35]; if there is no explicit connection between the User Agent and the keystore, the raw keys can be stored in a Trusted Platform Module, for example. In contrast to a software implementation, the keystores allow explicit measures to be taken within a microprocessor on the hardware [6, p. 414]. The Secure Enclave Processor of the Apple A7 SoC is such an example because it prevents an attacker from being able to recover cryptographic keys from an otherwise compromised device [11, p. 1].

In this respect, the WCA specification does not state any concrete requirements regarding the storage mechanism, but the storage medium must support the structured clone algorithm. The WCA particularly recommends associative storage with the Indexed Database API. In this case, the CryptoKey objects are not exposed to the complete JavaScript runtime, so that only web applications of the same origin can use the respective keys [35].

Each CryptoKey object implements the key interface and also stores whether the respective key is exportable: [35]

• Key Interface: The two attributes keyType and keyUsage specify the type of a key (public, private or symmetric key) and the cryptographic operations which can be performed with this CryptoKey object [63].
• CryptoKeyPair object: The combination of a public and private CryptoKey object is called CryptoKeyPair object [15].
• structured clone algorithm: The structured clone algorithm allows the copying of complex JavaScript objects. For example, workers‘ data can be copied with the function postMessage or files can be stored in an IndexedDB [27]. Above all, when serializing a CryptoKey object, no other object may be deserialized simultaneously. If this is possible, the internal data structure of the CryptoKey object is exposed and mutual key access is possible. This must be avoided to guarantee maximum data protection. Above all, a true copy of the JavaScript object – i.e. a reference – prevents complete access to the modified object after its transformation [35].

## Browser Support

The specification of the WCA was published on 26.01.2017 by the WCWG of the W3C, and all browser manufacturers should make this API available. Furthermore, the WCA does not prescribe which algorithms must be supported. This is especially useful if an algorithm is considered unsafe in the future or new algorithms are to be supported [35].

The support of the WCA can be found on the pages of the browser manufacturers. In addition, the website https://caniuse.com/ provides a summary in the form of browser support tables of web technologies on desktop and mobile devices [3]. According to Deveria, the WCA can be used without problems in 94.17% of all browsers. However, this assumption is too short, because not all users always use the latest software version [33]. For this reason, Figure 3.4 shows the actual market share of all browsers including their versions on all devices. The note must also be taken into account: The support in Internet Explorer 11 is based on an older WCA specification [4].

## Sources

[1] Bitkom. Nutzung von Cloud Computing in Unternehmen in Deutschland in den Jahren 2011 bis 2018. Tech. Rep. Hamburg: Statista, June 2019. URL: https://de.statista.com/statistik/daten/studie/177484/umfrage/einsatz-von-cloud-computing-in-deutschen-unternehmen-2011/ .

[2] Bitkom. Nutzung von Public-Cloud-Computing in Unternehmen in Deutschland in den Jahren 2011 bis 2018. Tech. Rep. Hamburg: Statista, June 2019. URL: https://de.statista.com/statistik/daten/studie/305642/umfrage/einsatz-von-public-cloud-computing-in-deutschen-unternehmen/ .

[4] Alexis Deveria. Web Cryptography.  2020. URL: https://caniuse.com/%7B%5C#%7Dfeat=cryptography (visited 05. 02. 2020).

[5] Digital Bazaar. Forge. 2019. URL: https://github.com/digitalbazaar/forge/ (visited 06. 11. 2019)

[6] Claudia Eckert. IT-Sicherheit. 10. Ed. Berlin/Boston: Walter de Gruyter, 2018. DOI: 10.1515/9783110563900

[7]  Gartner. Umsatz mit Cloud Computing** weltweit von 2009 bis 2018 und Prognose bis 2022 (in Milliarden US-Dollar). Tech. Rep. Hamburg: Statista, Nov. 2019. URL: https://de.statista.com/statistik/daten/studie/195760/umfrage/umsatz-mit-cloud-computing-weltweit/ .

[8] Harry Halpin. „Re-igniting the Crypto Wars on the Web“. In:29th Chaos Communication Congress. Hamburg: Chaos Computer Club, 2012. URL: https://media.ccc.de/v/29c3-5374-en-re_igniting_the_crypto_wars_on_the_web_h264

[9] S Landau. „Making Sense from Snowden: What’s Significant in the NSA Surveillance Revelations“. In: IEEE Security & Privacy 11.4 (Aug. 2013), S. 54–63. DOI: 10.1109/MSP.2013.90.

[10] N Lawson. „Side-Channel Attacks on Cryptographic Software“. In: IEEE Security & Privacy 7.6 (Nov. 2009), p. 65–68. DOI: 10.1109/MSP.2009.165.

[11] Tarjei Mandt, Mathew Solnik and David Wang. „Demystifying the Secure Enclave Processor“. In: Black Hat USA. Las Vegas, 2016. URL: https://www.blackhat.com/docs/us-16/materials/us-16-Mandt-Demystifying-The-Secure-Enclave- Processor.pdf.

[12] Rob McLean. A hacker gained access to 100 million Capital One credit card applications and accounts. Atlanta, Juli 2019. URL: https://edition.cnn.com/2019/07/29/business/capital-one-data-breach/index.html.

[13] MDN Web Docs. Crypto. 2019. URL: https://developer.mozilla.org/en-US/docs/Web/API/Crypto (visited 18. 11. 2019).

[14] MDN Web Docs. Crypto.getRandomValues(). 2019. URL: https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues (visited 18. 11. 2019).

[15] MDN Web Docs. CryptoKeyPair. 2019. URL: https://developer.mozilla.org/en-US/docs/Web/API/CryptoKeyPair (visited 27.11. 2019).

[16] MDN Web Docs. Math.random(). 2020. URL: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random (visited 04. 02. 2020).

[17] MDN Web Docs. SubtleCrypto.decrypt(). 2019. URL: https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/decrypt (visited am 19. 11. 2019).

[18] MDN Web Docs. SubtleCrypto.deriveKey(). 2019. URL: https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/deriveKey (visited 19.11.2019).

[19] MDN Web Docs. SubtleCrypto.digest(). 2019. URL: https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest (visited 19. 11. 2019).

[20] MDN Web Docs. SubtleCrypto.encrypt(). 2019. URL: https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/encrypt (visited 19. 11. 2019).

[21] MDN Web Docs. SubtleCrypto.exportKey(). 2019. URL: https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/exportKey (visited 19. 11. 2019).

[22] MDN Web Docs. SubtleCrypto.importKey(). 2019. URL: https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey (visited 19. 11. 2019).

[23] MDN Web Docs. SubtleCrypto.sign(). 2019. URL: https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/sign (visited 19. 11. 2019).

[24] MDN Web Docs. SubtleCrypto.unwrapKey(). 2019. URL: https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/unwrapKey (visited 19. 11. 2019).

[25] MDN Web Docs. SubtleCrypto.verify(). 2019. URL: https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/verify (visited 19. 11. 2019).

[26] MDN Web Docs. SubtleCrypto.wrapKey(). 2019. URL: https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/wrapKey (visited 19. 11. 2019).

[27] MDN Web Docs. The structured clone algorithm. 2019. URL: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm (visited 27. 11. 2019).

[28] Christof Paar and Jan Pelzl. Understanding Cryptography. 2. Ed. Heidelberg: Springer, 2010. DOI: 10.1007/978-3-642-04101-3.

[29] Thomas Ptacek. Javascript Cryptography Considered Harmful. 2011. URL: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2011/august/javascript-cryptography-considered-harmful/ (visited 30.01. 2020).

[30] Swarnpreet Singh and Tarun Jangwal. „Cost breakdown of Public Cloud Computing and Private Cloud Computing and Security Issues“. In: International Journal of Computer Science and Information Technology 4.2 (Apr. 2012), pp. 17–31. DOI: 10.5121/ijcsit.2012.4202.

[31] Victoria Song. Mother of All Breaches Exposes 773 Million Emails, 21 Million Passwords. New York, Jan. 2019. URL: https://gizmodo.com/mother-of-all-breaches-exposes-773-million-emails-21-m-1831833456.

[32] Stanford Computer Security Lab. Stanford Javascript Crypto Library (SJCL). 2019. URL: http://bitwiseshiftleft.github.io/sjcl/ (visited am 06. 11. 2019).

[33] tatCounter. Market share of the most used browser versions in Germany in December 2019. Tech. Rep. Hamburg: Statista, Jan. 2019. URL: https://www.statista.com/statistics/462158/browsers-most-used-versions-germany/.

[34] W3Techs. Usage statistics of JavaScript as client-side programming language on websites. 2020. URL: https://w3techs.com/technologies/details/cp- javascript (visited 30. 01. 2020).

[35] Mark Watson. Web Cryptography API. Tech. Rep. Cambridge: W3C, Jan. 2017. URL: https://www.w3.org/TR/WebCryptoAPI/.

[36] Web Cryptography Working Group. public-webcrypto@w3.org Mail Archives. 2017. URL: http://lists.w3.org/Archives/Public/public-webcrypto/ (visited 12. 11. 2019).

## Ähnliche Artikel

#### Deep Learning for Mobile Devices with TensorFlow Lite: Create an AI-Powered Android Application

This is the third article of our blog post series about Deep Learning for mobile devices. The

MEHR ERFAHREN

#### Android Studio 1.3: Neue Features im Überblick

Android Studio ist die offizielle IDE, um Android Applikationen zu entwickeln, und hat sich seit der überraschenden

MEHR ERFAHREN

#### Speed up Your Android Espresso Tests With Firebase TestLab and Flank

Executing Android Espresso Tests on a CI Server has always been a problem. Emulators are slow to

MEHR ERFAHREN