simple-hpke
v0.2.0
Published
Hybrid Public Key Encryption
Readme
Simple HPKE
Hybrid Public Key Encryption (RFC 9180)
1 dependency -- uint8arrays.
On every create/encrypt call, we generate a fresh ephemeral X25519 keypair,
do Diffie-Hellman against the recipient public key, and the key schedule derives
an AES-256-GCM key from that shared secret.
That DH-derived key is the wrapping key. The AES key the API hands back is a second, independently random key, and the wrapping key encrypts its raw bytes. Key wrapping here just means "HPKE seal where the plaintext happens to be 16 or 32 bytes of key material." The RFC doesn't care what the plaintext is.
Install
npm i -S simple-hpkeExamples
Create an AES key, or encrypt a message.
Key Wrapping
Encrypt an AES key, then recover it later.
import { create, encryptKey, open } from 'simple-hpke'
// An X25519 keypair. (asymmetric keypair).
// The private key can be non-extractable.
// HPKE only needs `deriveBits`.
const keypair = await crypto.subtle.generateKey(
{ name: 'X25519' },
false, // not extractable
['deriveBits']
)
// Create a new AES key and encrypt it to your public key.
// `key` is the unencrypted new AES key
// `enc` is the AES key encrypted to the given public key
const { enc, key } = await create(keypair.publicKey) // or a buffer or string
//
// Or wrap an existing AES key. The supplied AES key must be extractable.
//
const aesKey = await crypto.subtle.generateKey(
{ name: 'AES-GCM', length: 256 },
true, // not extractable
['encrypt', 'decrypt']
)
// Wrap the existing key.
const { enc: wrappedKey } = await encryptKey(keypair, aesKey)
// or pass in just a public key
// Later, recover the same key with your private key.
const recoveredKey = await open(keypair, wrappedKey)
// `recoveredKey` is equal to `aesKey`Hybrid Encryption
Encrypt a message with AES-GCM, then encrypt the AES key to a given public key. The encrypted key is concattenated with the cipher text, along with the IV. The recipient uses their private key to open the AES key and decrypt the message.
import { create, open } from 'simple-hpke'
const recipient = await crypto.subtle.generateKey(
{ name: 'X25519' },
false, // not extractable
['deriveBits']
)
// Create a fresh AES-GCM key, and encrypt a message with it.
const { enc, key } = await create(recipient)
const iv = crypto.getRandomValues(new Uint8Array(12))
const ciphertextBuffer = await crypto.subtle.encrypt(
{ name: 'AES-GCM', iv },
key,
new TextEncoder().encode('attack at dawn')
)
// Send `enc`, `iv`, and `ciphertext` together. `create(...)` defaults to a
// 256-bit AES key, so `enc.length` is 80 bytes in this example.
//
// If your protocol allows different wrapped-key sizes, prefix `enc.length`
// (or otherwise transmit it) so the recipient can split the payload safely.
const ciphertext = new Uint8Array(ciphertextBuffer)
const encLength = enc.length
const message = new Uint8Array(encLength + iv.length + ciphertext.length)
message.set(enc, 0)
message.set(iv, encLength)
message.set(ciphertext, encLength + iv.length)
// On the other side, split the payload back into its parts.
const enc2 = message.subarray(0, encLength)
const iv2 = message.subarray(encLength, encLength + 12)
const ciphertext2 = message.subarray(encLength + 12)
// Recover the key, then decrypt the message.
const recovered = await open(recipient, enc2)
const plaintext = await crypto.subtle.decrypt(
{ name: 'AES-GCM', iv: iv2 },
recovered,
ciphertext2
)
new TextDecoder().decode(plaintext) // => 'attack at dawn'Encrypt / Decrypt
So that was a lot of code to encrypt and decrypt a message...
This package exposes functions encrypt and decrypt that do the same thing.
encrypt wraps an AES key to the recipient, encrypts the message under
that key, and returns a single envelope:
wrappedLen + wrappedKey + iv + ciphertext
(a 2-byte length prefix, the wrapped key, the 12-byte AES-GCM IV, and the
cipher text). decrypt reverses it, returning the plaintext bytes.
[!NOTE]
Seedecrypt.asString&decrypt.fromStringbelow for a convenient way to decrypt from a string.See
encrypt.asStringfor encrypting and encoding to a string.
import { toString } from 'uint8arrays'
import { encrypt, decrypt } from 'simple-hpke'
// ----------------------
// Encrypt
// ----------------------
// need a public key for the recipient
const recipient = await crypto.subtle.generateKey(
{ name: 'X25519' },
false, // not extractable
['deriveBits']
)
// create a new AES key, encrypt a message, and get back an "envelope"
const encryptedMessage = await encrypt(recipient.publicKey, 'hello encryption')
// encrypt to a public key as Uint8Array
const publicBytes = new Uint8Array(
await subtle.exportKey('raw', recipient.publicKey)
)
const envelope = await encrypt(publicBytes, 'hello again')
// encrypt to a stringified public key
// create a string with `uint8arrays.toString`
const publicString = toString(publicBytes, 'base64url')
const envelopeAgain = await encrypt({
publicKey: publicString,
encoding: 'base64url' // <-- this is the default
}, 'hello again, string version')
//
// encrypt with an existing AES key
// (a key not generated by this module)
//
const existingKey = await crypto.subtle.generateKey(
{ name: 'AES-GCM', length: 256 },
true, // extractable
['encrypt', 'decrypt']
)
const anotherEncryptedMsg = await encrypt(
recipient,
'hello again',
existingKey
)
// ----------------------
// Decrypt
// ----------------------
// the recipient recovers the message with their private key
const text = await decrypt.asString(recipient, encryptedMessage)
// use `decrypt` to get a Uint8Array
const bytes = await decrypt(recipient, encryptedMessage)
// get a string
const plaintext = await decrypt.asString(recipient, envelope)encrypt
The recipient can be a crypto key, a Uint8Array, or a string public key.
type RecipientKey =
| CryptoKey
| CryptoKeyPair
| Uint8Array
| { publicKey:string; encoding?:Uint8ArrayEncodings }
async function encrypt (
recipient:RecipientKey,
message:Uint8Array|string,
aesKey?:CryptoKey|Uint8Array|null,
opts?:{
size?:128|256
info?:Uint8Array|string
}
):Promise<Uint8Array>encrypt.asString
encrypt.asString is encrypt with the envelope encoded to a string, useful
for transports that carry text (JSON, URLs, headers). opts.encoding sets the
string encoding. Default encoding is base64url.
import { encrypt, decrypt } from 'simple-hpke'
import { fromString } from 'uint8arrays'
// recipient is any RecipientKey; keypair holds the matching private key
const encryptedString = await encrypt.asString(
recipient,
'message for them',
null, // an AES key if you want
{ encoding: 'base64url' }
)
// Decode it back to bytes before decrypting.
const message = fromString(encryptedString, 'base64url')
const plaintext = await decrypt.asString(keypair, message)
// 'message for them'The returned string encodes the same envelope encrypt returns, so the
recipient decodes it with a matching decoder (here fromString) and passes the
bytes to decrypt / decrypt.asString.
decrypt
Decrypt the given data, return a Uint8Array.
async function decrypt (
keypair:CryptoKeyPair,
message:Uint8Array,
opts?:{ info?:Uint8Array|string }
):Promise<Uint8Array>decrypt.asString
Take a Uint8Array, return a string.
decrypt.asString = async function decryptToString (
keypair:CryptoKeyPair,
message:Uint8Array,
opts?:{ info?:Uint8Array|string }
):Promise<string>decrypt.fromString
Take a string as input. Return either a string, or if opts.buffer is true,
aUint8Array.
decrypt.fromString = async function decryptFromString (
keypair:CryptoKeyPair,
message:string,
opts?:{ info?:Uint8Array|string, buffer?:boolean }
):Promise<string|Uint8Array>Modules
This exposes ESM and common JS via
package.json exports field.
ESM
import { create, encryptKey, open, encrypt, decrypt } from 'simple-hpke'Common JS
require('simple-hpke')pre-built JS
This package exposes minified JS files too. Copy them to a location that is accessible to your web server, then link to them in HTML.
copy
cp ./node_modules/simple-hpke/dist/index.min.js ./public/hpke.min.jsHTML
<script type="module" src="./hpke.min.js"></script>