Skip to main content

Module hkdf

Module hkdf 

Source
Expand description

Implements the HMAC-based Key Derivation Function from https://datatracker.ietf.org/doc/html/rfc5869.

One-shot operation:

use bssl_crypto::{hkdf, hkdf::HkdfSha256};

let key: [u8; 32] = HkdfSha256::derive(b"secret", hkdf::Salt::NonEmpty(b"salt"),
                                       b"info");

If deriving several keys that vary only in the info parameter, then part of the computation can be shared by calculating the “pseudo-random key”. This is purely a performance optimisation.

use bssl_crypto::{hkdf, hkdf::HkdfSha256};

let prk = HkdfSha256::extract(b"secret", hkdf::Salt::NonEmpty(b"salt"));
let key1 : [u8; 32] = prk.expand(b"info1");
let key2 : [u8; 32] = prk.expand(b"info2");

assert_eq!(key1, HkdfSha256::derive(b"secret", hkdf::Salt::NonEmpty(b"salt"),
                                    b"info1"));
assert_eq!(key2, HkdfSha256::derive(b"secret", hkdf::Salt::NonEmpty(b"salt"),
                                    b"info2"));

The above examples assume that the size of the outputs is known at compile time. (And only output lengths less than 256 bytes are supported.)

use bssl_crypto::{hkdf, hkdf::HkdfSha256};

let key: [u8; 256] = HkdfSha256::derive(b"secret", hkdf::Salt::None, b"info");

To use HKDF with longer, or run-time, lengths, use derive_into and extract_into:

use bssl_crypto::{hkdf, hkdf::HkdfSha256};

let mut out = [0u8; 50];
HkdfSha256::derive_into(b"secret", hkdf::Salt::None, b"info", &mut out).expect(
   "HKDF can't produce that much");

assert_eq!(out, HkdfSha256::derive(b"secret", hkdf::Salt::None, b"info"));

To expand output from the explicit bytes of a PRK, use Prk::new:

use bssl_crypto::{digest::Sha256, digest::Algorithm, hkdf};

let prk: [u8; Sha256::OUTPUT_LEN] = bssl_crypto::rand_array();
// unwrap: only fails if the input is not equal to the digest length, which
// cannot happen here.
let prk = hkdf::Prk::new::<Sha256>(&prk).unwrap();
let mut out = vec![0u8; 42];
prk.expand_into(b"info", &mut out)?;

Structs§

Hkdf
HKDF for any of the implemented hash functions. The aliases HkdfSha256 and HkdfSha512 are provided for the most common cases.
Prk
A pseudo-random key, an intermediate value in the HKDF computation.
TooLong
Error type returned when too much output is requested from an HKDF operation.

Enums§

Salt
HKDF’s optional salt values. See https://datatracker.ietf.org/doc/html/rfc5869#section-3.1

Type Aliases§

HkdfSha256
Implementation of HKDF-SHA-256
HkdfSha512
Implementation of HKDF-SHA-512