hpke_dispatch/
base_mode_open.rs

1#[cfg(target_arch = "wasm32")]
2use wasm_bindgen::prelude::*;
3
4use crate::{from_bytes, match_algo, Config, HpkeError};
5
6/**
7`base_mode_open` provides an interface to [`hpke::single_shot_open`]
8that does not require compile time selection of an algorithm. Instead,
9the selected algorithm is provided through the [`Config`] passed as
10the first argument.
11
12Requires the `base-mode-open` crate feature to be enabled.
13
14# Errors
15
16This will return an `Result::Err` variant if:
17
18* we are unable to deserialize the private key or encapsulated key
19* there is an error in key decapsulation
20* there is an error in decryption
21 */
22#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
23#[cfg(feature = "base-mode-open")]
24pub fn base_mode_open(
25    config: &Config,
26    private_key: &[u8],
27    encapped_key: &[u8],
28    info: &[u8],
29    ciphertext: &[u8],
30    aad: &[u8],
31) -> Result<Vec<u8>, HpkeError> {
32    let Config { aead, kdf, kem } = *config;
33    let open = match_algo!(aead, kdf, kem, open);
34    open(private_key, encapped_key, info, ciphertext, aad)
35}
36
37fn open<AeadT, KdfT, KemT>(
38    private_key: &[u8],
39    encapped_key: &[u8],
40    info: &[u8],
41    ciphertext: &[u8],
42    aad: &[u8],
43) -> Result<Vec<u8>, HpkeError>
44where
45    AeadT: hpke::aead::Aead,
46    KdfT: hpke::kdf::Kdf,
47    KemT: hpke::kem::Kem,
48{
49    let result = hpke::single_shot_open::<AeadT, KdfT, KemT>(
50        &hpke::OpModeR::Base,
51        &from_bytes(private_key)?,
52        &from_bytes(encapped_key)?,
53        info,
54        ciphertext,
55        aad,
56    );
57    cfg_if::cfg_if! {
58        if #[cfg(target_arch = "wasm32")] {
59            result.map_err(Into::into)
60        } else {
61            result
62        }
63    }
64}