crypto
The crypto module is available to use in your EdgeWorkers code bundles to support the Javascript crypto API. The JavaScript crypto API is based on the Web Crypto API.
Example 1 - Verify Signatures with a Public Key
These steps demonstrate how to reference public keys locally within your EdgeWorkers code bundle and pass them into the crypto built-in module. To use the crypto module you need to:
- Create a key pair.
- Update your EdgeWorkers function to use the public key and the crypto built-in module.
Using this method, you no longer need to pack crypto libraries into your EdgeWorkers code bundles.
📘 Before you start, you should find out if your organization has any guidelines about the source of key materials. For this example, we’ll assume your organization allows the use of WebCrypto APIs in Chrome.
Create a key pair
This example demonstrates how to create an ECDSA key using SubtleCrypto.generateKey().
- In the Chrome JavaScript console, run this code to generate your keys.
- Here’s an example of output that contains the public and private keys.
📘 Every call to the
generateKey()method creates new keys.
Use the keys in an EdgeWorkers function
You can now add the public key and the crypto built-in module to your EdgeWorkers function. This simple EdgeWorkers function uses the onClientRequest event handler and the request headers to pass the data and signature.
-
Update your EdgeWorkers function so that it performs these operations:
-
Loads the public key using the
importKey()method to verify a signature. -
Converts the two input headers,
verify-dataandverify-sig, from a header-friendly base64 format to a Uint8Array. The built-in encoding module contains a number of helpers that transform common input formats such as, base16, base64, and base64url to JavaScript’s typed arrays. -
Runs the
verify()function on the Uint8Arrays that represent the input headers.
-
Here’s an example of an EdgeWorkers function after you’ve updated it to perform theses functions and added the key and crypto modules.
📘 Make sure that the ext field of the JWK is false so that it agrees with the extractable field of the
importKey()method.
- In addition to updating your EdgeWorkers code you also need to sign some data. To do this, paste the following code snippet into your JavaScript Console.
This snippet gets the ASCII encoding of the string “secret”.
The ASCII encoded string is then converted to an Uint8Array and is passed to the sign() function, along with the private CryptoKey we generated earlier.
- Here’s an example of the console output you should see.
The value after “sig” is the base64 encoded signature.
📘 Each call to the function will result in a different signature.
- Use this curl command to pass the signature and the base64 encoded representation of the string “secret” to the EdgeWorkers function.
You should get a 200 response. This indicates that the EdgeWorkers function properly read and verified the data and signature from the headers. If you change a character in the verify-data header, you will get a 403 response.
Example 2 - Verify a JWT with HMAC
JSON Web Tokens (JWTs) provide a standards-compliant way of sharing verifiable data. The following example verifies a JWT:
The verify_hs256() splits the JWT into its component parts, verifies the signature, and returns the decoded header and claims. In this case, the response status should be a 202 with the following body:
CryptoKey Object
The CryptoKey interface represents a cryptographic key obtained from the importKey() SubtleCrypto method. After you create a key you can use it to verify a signature, encrypt, or decrypt data.
CryptoKey Object Properties
type
The type of key. This is a read-only string value.
extractable
Indicates whether the key can be extracted using exportKey() or wrapKey(). This is a read-only boolean value.
algorithm
Returns an object that contains the supported algorithm for the specified key and any extra parameters. This is a read-only value.
usages
Indicates what can be done with the key. This is a read-only array of strings value.
SubtleCrypto Object
The subtleCrypto interface provides several cryptographic functions. SubtleCrypto features are obtained through the subtle property of the Crypto object you get from the Crypto property.
importKey()
Imports a key from a promise that fulfills with the imported key as a CryptoKey object.
The following example demonstrates the use of importKey(), encrypt(), and decrypt(). It imports an AES-CBC key, using it to encrypt and then decrypt sample text. It verifies that the decrypted value is the same as the encrypted value.
RSASSA-PKCS1-v1_5: jwk example
RSASSA-PKCS1-v1_5: pkcs8 example
RSASSA-PKCS1-v1_5: spki example
RSA-PSS: jwk example
RSA-PSS: pkcs8 example
RSA-PSS: spki example
HMAC: jwk example
HMAC: raw example
AES-CBC: jwk example
AES-CBC: raw example
ECDSA: jwk example
ECDSA: pkcs8 example
ECDSA: raw example
ECDSA: spki example
AES-CTR: jwk example
RSA-OAEP: jwk example
AES-GCM: raw example
encrypt()
Returns a promise that fulfills with an ArrayBuffer containing the encrypted data.
decrypt()
Returns a promise that fulfills with an ArrayBuffer containing the decrypted data.
sign()
Generates a digital signature. Returns a promise that fulfills with an ArrayBuffer containing the signature.
HMAC: sign example
verify()
Verifies a digital signature. Returns a promise that fulfills with a boolean value. The boolean value is true if the signature is valid, if the signature is invalid it returns a value of false.
digest()
Generates a digest of the given data. Returns a promise that fulfills with an ArrayBuffer containing the digest.
The following example computes the SHA-256 hash of a static array buffer. The expected output is Encoded: d87303c776e767aa617e9e5c8a3238a2f7c3e98ea395165786d97322bd731415.
Crypto Object
Represents basic cryptography features available in the current context.
getRandomValues()
Returns cryptographically strong random values. Writes the random values into the passed array.
Crypto Object Properties
subtle
Returns a SubtleCrypto object that provides access to common cryptographic primitives. This is a read-only value.
pem2ab()
Converts a PEM-encoded key string into an ArrayBuffer. This function converts valid text between matching BEGIN and END delimiters, as described in RFC-7468. Throws a TypeError error if matching headers cannot be found, or if illegal characters appear within the delimiters.