Skip to main content

Module hpke

Module hpke 

Source
Expand description

Hybrid Public Key Encryption

HPKE provides public key encryption of arbitrary-length messages. It establishes contexts that produce/consume an ordered sequence of ciphertexts that are both encrypted and authenticated.

See RFC 9180 for more details.

use bssl_crypto::hpke;

let kem = hpke::Kem::X25519HkdfSha256;
let (pub_key, priv_key) = kem.generate_keypair();
// Distribute `pub_key` to people who want to send you messages.

// On the sending side...
let params = hpke::Params::new(kem, hpke::Kdf::HkdfSha256, hpke::Aead::Aes128Gcm);
let info : &[u8] = b"mutual context";
let (mut sender_ctx, encapsulated_key) =
    hpke::SenderContext::new(&params, &pub_key, info).unwrap();
// Transmit the `encapsulated_key` to the receiver, followed by one or
// more ciphertexts...
let aad = b"associated_data";
let plaintext1 : &[u8] = b"plaintext1";
let msg1 = sender_ctx.seal(plaintext1, aad);
let plaintext2 : &[u8] = b"plaintext2";
let msg2 = sender_ctx.seal(plaintext2, aad);

// On the receiving side...
let mut recipient_ctx = hpke::RecipientContext::new(
    &params,
    &priv_key,
    &encapsulated_key,
    info,
).unwrap();

let received_plaintext1 = recipient_ctx.open(&msg1, aad).unwrap();
assert_eq!(plaintext1, &received_plaintext1);
let received_plaintext2 = recipient_ctx.open(&msg2, aad).unwrap();
assert_eq!(plaintext2, &received_plaintext2);

// Messages must be processed in order, so trying to `open` the second
// message first will fail.
let mut recipient_ctx = hpke::RecipientContext::new(
    &params,
    &priv_key,
    &encapsulated_key,
    info,
).unwrap();

let received_plaintext2 = recipient_ctx.open(&msg2, aad);
assert!(received_plaintext2.is_none());

// There is also an interface for exporting secrets from both sender
// and recipient contexts.
let sender_export = sender_ctx.export(b"ctx", 32);
let recipient_export = recipient_ctx.export(b"ctx", 32);
assert_eq!(sender_export, recipient_export);

Structs§

Params
HPKE parameters, including KEM, KDF, and AEAD.
RecipientContext
HPKE recipient context. Callers may use open() to decrypt messages from the sender.
SenderContext
HPKE sender context. Callers may use seal() to encrypt messages for the recipient.

Enums§

Aead
Supported AEAD algorithms with values detailed in RFC 9180.
Kdf
Supported KDF algorithms with values detailed in RFC 9180.
Kem
Supported KEM algorithms with values detailed in RFC 9180.