Securely Creating and Storing Cryptographic Keys in the Browser
The WebCrypto API’s CryptoKey interface allows developers to securely create public and private keys in the browser. These keys can be used to sign and validate JWTs, or to perform other cryptographic tasks, such as encryption and decryption. Importantly, the private key can be kept opaque and is not revealed to the end-user or the JavaScript runtime. This means that developers can work with the CryptoKey interface without having to handle the underlying keys directly.
One neat application of this is the ability to store the CryptoKey object in IndexedDB for later use. This allows developers to continuously sign JWTs with the same private key over multiple browser sessions, until the browser storage is cleared. This can be useful in scenarios like OAuth2’s Dynamic Client Registration Protocol. Overall, the WebCrypto API’s CryptoKey interface provides a convenient and secure way to work with public and private keys in the browser.
Demo
In this demo, you should see a JWT being signed and validated using public/private keys generated with the WebCrypto API as you click on the buttons below. The generated CryptoKey is stored in IndexedDB so we can reuse the same key pair over multiple browser sessions.
Note: WebCrypto requires a secure context (HTTPS or localhost).
1) Generate CryptoKey Key Pair
The following button will check to see if a CryptoKey key pair already exists in IndexedDB. If it does, it will just return the existing CryptoKey object. If not, it will generate a new one and store it in IndexedDB.