| 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_core::{ |
| 6 |
crypto::{HpkeContextR, HpkeContextS}, |
| 7 |
error::IntoAnyError, |
| 8 |
}; |
| 9 |
use mls_rs_crypto_traits::{AeadType, KdfType}; |
| 10 |
|
| 11 |
use crate::{hpke::HpkeError, kdf::HpkeKdf}; |
| 12 |
|
| 13 |
use alloc::vec::Vec; |
| 14 |
use core::fmt::{self, Debug}; |
| 15 |
|
| 16 |
/// A type representing an HPKE context |
| 17 |
#[derive(Clone)] |
| 18 |
pub(super) struct Context<KDF: KdfType, AEAD: AeadType> { |
| 19 |
exporter_secret: Vec<u8>, |
| 20 |
encryption_context: Option<EncryptionContext<AEAD>>, |
| 21 |
kdf: HpkeKdf<KDF>, |
| 22 |
} |
| 23 |
|
| 24 |
impl<KDF: KdfType + Debug, AEAD: AeadType + Debug> Debug for Context<KDF, AEAD> { |
| 25 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 26 |
f.debug_struct("Context") |
| 27 |
.field( |
| 28 |
"exporter_secret", |
| 29 |
&mls_rs_core::debug::pretty_bytes(&self.exporter_secret), |
| 30 |
) |
| 31 |
.field("encryption_context", &self.encryption_context) |
| 32 |
.field("kdf", &self.kdf) |
| 33 |
.finish() |
| 34 |
} |
| 35 |
} |
| 36 |
|
| 37 |
impl<KDF: KdfType, AEAD: AeadType> Context<KDF, AEAD> { |
| 38 |
#[inline] |
| 39 |
pub(super) fn new( |
| 40 |
encryption_context: Option<EncryptionContext<AEAD>>, |
| 41 |
exporter_secret: Vec<u8>, |
| 42 |
kdf: HpkeKdf<KDF>, |
| 43 |
) -> Self { |
| 44 |
Self { |
| 45 |
exporter_secret, |
| 46 |
encryption_context, |
| 47 |
kdf, |
| 48 |
} |
| 49 |
} |
| 50 |
} |
| 51 |
|
| 52 |
impl<KDF: KdfType, AEAD: AeadType> Context<KDF, AEAD> { |
| 53 |
#[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)] |
| 54 |
async fn seal(&mut self, aad: Option<&[u8]>, data: &[u8]) -> Result<Vec<u8>, HpkeError> { |
| 55 |
self.encryption_context |
| 56 |
.as_mut() |
| 57 |
.ok_or(HpkeError::ExportOnlyMode)? |
| 58 |
.seal(aad, data) |
| 59 |
.await |
| 60 |
} |
| 61 |
|
| 62 |
#[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)] |
| 63 |
async fn open(&mut self, aad: Option<&[u8]>, ciphertext: &[u8]) -> Result<Vec<u8>, HpkeError> { |
| 64 |
self.encryption_context |
| 65 |
.as_mut() |
| 66 |
.ok_or(HpkeError::ExportOnlyMode)? |
| 67 |
.open(aad, ciphertext) |
| 68 |
.await |
| 69 |
} |
| 70 |
|
| 71 |
#[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)] |
| 72 |
async fn export(&self, exporter_context: &[u8], len: usize) -> Result<Vec<u8>, HpkeError> { |
| 73 |
self.kdf |
| 74 |
.labeled_expand(&self.exporter_secret, b"sec", exporter_context, len) |
| 75 |
.await |
| 76 |
.map_err(|e| HpkeError::KdfError(e.into_any_error())) |
| 77 |
} |
| 78 |
} |
| 79 |
|
| 80 |
#[derive(Debug, Clone)] |
| 81 |
pub struct ContextS<KDF: KdfType, AEAD: AeadType>(pub(super) Context<KDF, AEAD>); |
| 82 |
|
| 83 |
#[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)] |
| 84 |
#[cfg_attr(all(target_arch = "wasm32", mls_build_async), maybe_async::must_be_async(?Send))] |
| 85 |
#[cfg_attr( |
| 86 |
all(not(target_arch = "wasm32"), mls_build_async), |
| 87 |
maybe_async::must_be_async |
| 88 |
)] |
| 89 |
impl<KDF: KdfType, AEAD: AeadType> HpkeContextS for ContextS<KDF, AEAD> { |
| 90 |
type Error = HpkeError; |
| 91 |
|
| 92 |
async fn export(&self, exporter_context: &[u8], len: usize) -> Result<Vec<u8>, Self::Error> { |
| 93 |
self.0.export(exporter_context, len).await |
| 94 |
} |
| 95 |
|
| 96 |
/// # Errors |
| 97 |
/// |
| 98 |
/// Returns [SequenceNumberOverflow](HpkeError::SequenceNumberOverflow) |
| 99 |
/// in the event that the sequence number overflows. The sequence number is a u64 and starts |
| 100 |
/// at 0. |
| 101 |
async fn seal(&mut self, aad: Option<&[u8]>, data: &[u8]) -> Result<Vec<u8>, Self::Error> { |
| 102 |
self.0.seal(aad, data).await |
| 103 |
} |
| 104 |
} |
| 105 |
|
| 106 |
#[derive(Debug, Clone)] |
| 107 |
pub struct ContextR<KDF: KdfType, AEAD: AeadType>(pub(super) Context<KDF, AEAD>); |
| 108 |
|
| 109 |
#[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)] |
| 110 |
#[cfg_attr(all(target_arch = "wasm32", mls_build_async), maybe_async::must_be_async(?Send))] |
| 111 |
#[cfg_attr( |
| 112 |
all(not(target_arch = "wasm32"), mls_build_async), |
| 113 |
maybe_async::must_be_async |
| 114 |
)] |
| 115 |
impl<KDF: KdfType, AEAD: AeadType> HpkeContextR for ContextR<KDF, AEAD> { |
| 116 |
type Error = HpkeError; |
| 117 |
|
| 118 |
async fn export(&self, exporter_context: &[u8], len: usize) -> Result<Vec<u8>, Self::Error> { |
| 119 |
self.0.export(exporter_context, len).await |
| 120 |
} |
| 121 |
|
| 122 |
/// # Errors |
| 123 |
/// |
| 124 |
/// Returns [SequenceNumberOverflow](HpkeError::SequenceNumberOverflow) |
| 125 |
/// in the event that the sequence number overflows. The sequence number is a u64 and starts |
| 126 |
/// at 0. |
| 127 |
/// |
| 128 |
/// Returns [AeadError](HpkeError::AeadError) if decryption fails due to either an invalid |
| 129 |
/// `aad` value, or incorrect cipher key. |
| 130 |
async fn open( |
| 131 |
&mut self, |
| 132 |
aad: Option<&[u8]>, |
| 133 |
ciphertext: &[u8], |
| 134 |
) -> Result<Vec<u8>, Self::Error> { |
| 135 |
self.0.open(aad, ciphertext).await |
| 136 |
} |
| 137 |
} |
| 138 |
|
| 139 |
#[derive(PartialEq, Eq, Clone)] |
| 140 |
pub(super) struct EncryptionContext<AEAD: AeadType> { |
| 141 |
base_nonce: Vec<u8>, |
| 142 |
seq_number: u64, |
| 143 |
aead: AEAD, |
| 144 |
aead_key: Vec<u8>, |
| 145 |
} |
| 146 |
|
| 147 |
impl<AEAD: AeadType + Debug> Debug for EncryptionContext<AEAD> { |
| 148 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 149 |
f.debug_struct("EncryptionContext") |
| 150 |
.field( |
| 151 |
"base_nonce", |
| 152 |
&mls_rs_core::debug::pretty_bytes(&self.base_nonce), |
| 153 |
) |
| 154 |
.field("seq_number", &self.seq_number) |
| 155 |
.field("aead", &self.aead) |
| 156 |
.field( |
| 157 |
"aead_key", |
| 158 |
&mls_rs_core::debug::pretty_bytes(&self.aead_key), |
| 159 |
) |
| 160 |
.finish() |
| 161 |
} |
| 162 |
} |
| 163 |
|
| 164 |
impl<AEAD: AeadType> EncryptionContext<AEAD> { |
| 165 |
pub fn new(base_nonce: Vec<u8>, aead: AEAD, aead_key: Vec<u8>) -> Result<Self, HpkeError> { |
| 166 |
(base_nonce.len() == aead.nonce_size()) |
| 167 |
.then_some(()) |
| 168 |
.ok_or(HpkeError::IncorrectNonceLen( |
| 169 |
base_nonce.len(), |
| 170 |
aead.nonce_size(), |
| 171 |
))?; |
| 172 |
|
| 173 |
(aead_key.len() == aead.key_size()) |
| 174 |
.then_some(()) |
| 175 |
.ok_or(HpkeError::IncorrectKeyLen(aead_key.len(), aead.key_size()))?; |
| 176 |
|
| 177 |
Ok(EncryptionContext { |
| 178 |
base_nonce, |
| 179 |
seq_number: 0, |
| 180 |
aead, |
| 181 |
aead_key, |
| 182 |
}) |
| 183 |
} |
| 184 |
} |
| 185 |
|
| 186 |
impl<AEAD: AeadType> EncryptionContext<AEAD> { |
| 187 |
//draft-irtf-cfrg-hpke Section 5.2. Encryption and Decryption |
| 188 |
fn compute_nonce(&self) -> Vec<u8> { |
| 189 |
let mut nonce = self.base_nonce.clone(); |
| 190 |
|
| 191 |
// XOR the sequence number into the last 4 bytes of the nonce |
| 192 |
nonce |
| 193 |
.iter_mut() |
| 194 |
.rev() |
| 195 |
.zip(self.seq_number.to_le_bytes()) |
| 196 |
.for_each(|(n, s)| *n ^= s); |
| 197 |
|
| 198 |
nonce |
| 199 |
} |
| 200 |
|
| 201 |
#[inline] |
| 202 |
fn increment_seq(&mut self) -> Result<(), HpkeError> { |
| 203 |
// If the sequence number is going to roll over just throw an error |
| 204 |
self.seq_number = self |
| 205 |
.seq_number |
| 206 |
.checked_add(1) |
| 207 |
.ok_or(HpkeError::SequenceNumberOverflow)?; |
| 208 |
|
| 209 |
Ok(()) |
| 210 |
} |
| 211 |
|
| 212 |
#[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)] |
| 213 |
pub async fn seal(&mut self, aad: Option<&[u8]>, pt: &[u8]) -> Result<Vec<u8>, HpkeError> { |
| 214 |
let ct = self |
| 215 |
.aead |
| 216 |
.seal(&self.aead_key, pt, aad, &self.compute_nonce()) |
| 217 |
.await |
| 218 |
.map_err(|e| HpkeError::AeadError(e.into_any_error()))?; |
| 219 |
|
| 220 |
self.increment_seq()?; |
| 221 |
|
| 222 |
Ok(ct) |
| 223 |
} |
| 224 |
|
| 225 |
#[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)] |
| 226 |
pub async fn open(&mut self, aad: Option<&[u8]>, ct: &[u8]) -> Result<Vec<u8>, HpkeError> { |
| 227 |
let pt = self |
| 228 |
.aead |
| 229 |
.open(&self.aead_key, ct, aad, &self.compute_nonce()) |
| 230 |
.await |
| 231 |
.map_err(|e| HpkeError::AeadError(e.into_any_error()))?; |
| 232 |
|
| 233 |
self.increment_seq()?; |
| 234 |
|
| 235 |
Ok(pt) |
| 236 |
} |
| 237 |
} |