hpke-dispatch 0.9.0

Runtime algorithm selection for hybrid public key encryption
Documentation
use hpke::HpkeError;

use crate::{from_bytes, Config};

/// Single-shot HPKE ciphertext opening.
///
/// `base_mode_open` provides an interface to [`hpke::single_shot_open`] that does not require
/// compile time selection of an algorithm. Instead, the selected algorithm is provided through the
/// [`Config`] passed as the first argument.
///
/// # Errors
///
/// This will return a `Result::Err` variant if:
///
/// * we are unable to deserialize the private key or encapsulated key
/// * there is an error in key decapsulation
/// * there is an error in decryption
pub fn base_mode_open(
    config: &Config,
    private_key: &[u8],
    encapped_key: &[u8],
    info: &[u8],
    ciphertext: &[u8],
    aad: &[u8],
) -> Result<Vec<u8>, HpkeError> {
    let Config { aead, kdf, kem } = *config;
    let open = match_algo!(aead, kdf, kem, open);
    open(private_key, encapped_key, info, ciphertext, aad)
}

fn open<AeadT, KdfT, KemT>(
    private_key: &[u8],
    encapped_key: &[u8],
    info: &[u8],
    ciphertext: &[u8],
    aad: &[u8],
) -> Result<Vec<u8>, HpkeError>
where
    AeadT: hpke::aead::Aead,
    KdfT: hpke::kdf::Kdf,
    KemT: hpke::kem::Kem,
{
    hpke::single_shot_open::<AeadT, KdfT, KemT>(
        &hpke::OpModeR::Base,
        &from_bytes(private_key)?,
        &from_bytes(encapped_key)?,
        info,
        ciphertext,
        aad,
    )
}