Debian Codegraph @

third_party/rust/mls-rs-crypto-hpke/src/kdf.rs

raw
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // Copyright by contributors to this project.
3 // SPDX-License-Identifier: (Apache-2.0 OR MIT)
4
5 use mls_rs_crypto_traits::KdfType;
6
7 use alloc::vec::Vec;
8 use core::fmt::{self, Debug};
9
10 #[derive(Clone, Eq, PartialEq)]
11 pub(crate) struct HpkeKdf<K: KdfType> {
12 suite_id: Vec<u8>,
13 kdf: K,
14 }
15
16 impl<K: KdfType + Debug> Debug for HpkeKdf<K> {
17 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
18 f.debug_struct("HpkeKdf")
19 .field(
20 "suite_id",
21 &mls_rs_core::debug::pretty_bytes(&self.suite_id),
22 )
23 .field("kdf", &self.kdf)
24 .finish()
25 }
26 }
27
28 impl<K: KdfType> HpkeKdf<K> {
29 pub fn new(suite_id: Vec<u8>, kdf: K) -> Self {
30 Self { suite_id, kdf }
31 }
32
33 pub fn extract_size(&self) -> usize {
34 self.kdf.extract_size()
35 }
36
37 /* draft-irtf-cfrg-hpke-09 section 4 Cryptographic Dependencies */
38 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
39 pub async fn labeled_extract(
40 &self,
41 salt: &[u8],
42 label: &[u8],
43 ikm: &[u8],
44 ) -> Result<Vec<u8>, <K as KdfType>::Error> {
45 self.kdf
46 .extract(
47 salt,
48 &[b"HPKE-v1" as &[u8], &self.suite_id, label, ikm].concat(),
49 )
50 .await
51 }
52
53 /* draft-irtf-cfrg-hpke-09 section 4 Cryptographic Dependencies */
54 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
55 pub async fn labeled_expand(
56 &self,
57 key: &[u8],
58 label: &[u8],
59 info: &[u8],
60 len: usize,
61 ) -> Result<Vec<u8>, <K as KdfType>::Error> {
62 let labeled_info = [
63 &(len as u16).to_be_bytes() as &[u8],
64 b"HPKE-v1",
65 &self.suite_id,
66 label,
67 info,
68 ]
69 .concat();
70
71 self.kdf.expand(key, &labeled_info, len).await
72 }
73
74 /* draft-irtf-cfrg-hpke-09 section 4.1 DH-Based KEM */
75 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
76 pub async fn labeled_extract_then_expand(
77 &self,
78 ikm: &[u8],
79 ctx: &[u8],
80 len: usize,
81 ) -> Result<Vec<u8>, <K as KdfType>::Error> {
82 let eae_prk = self.labeled_extract(&[], b"eae_prk", ikm).await?;
83
84 self.labeled_expand(&eae_prk, b"shared_secret", ctx, len)
85 .await
86 }
87 }