1use crate::{memory, ArxKW, ArxKwError, SecretBytes, Zeroize, Zeroizing};
2use hmac::{Hmac, KeyInit, Mac};
3use sha2::Sha256;
4use std::convert::TryFrom;
5
6pub const ENVELOPE_HEADER_LENGTH: usize = 8;
8pub const MAX_CONTEXT_LENGTH: usize = 4096;
10const SALT: &[u8] = b"ARX-KW/context/v1";
11
12const fn header<V: ArxKW + ?Sized>() -> [u8; ENVELOPE_HEADER_LENGTH] {
13 [b'A', b'R', b'X', b'K', 1, V::VARIANT_ID, 0, 0]
14}
15
16fn derive<V: ArxKW + ?Sized>(
17 key: &V::Key,
18 context: &[u8],
19) -> Result<Zeroizing<V::Key>, ArxKwError> {
20 if context.len() > MAX_CONTEXT_LENGTH {
21 return Err(ArxKwError::ContextTooLong);
22 }
23 let mut derived = Zeroizing::new(*key);
24 derive_bytes(
25 key.as_ref(),
26 SALT,
27 &[&header::<V>(), context],
28 derived.as_mut(),
29 )?;
30 Ok(derived)
31}
32
33pub fn encrypt<V: ArxKW + ?Sized>(
34 key: &V::Key,
35 plaintext: &[u8],
36 context: &[u8],
37) -> Result<Vec<u8>, ArxKwError> {
38 memory::check_length(plaintext.len(), V::MAX_INPUT_LENGTH)?;
39 let key = derive::<V>(key, context)?;
40 let blob = V::encrypt_blob(&key, plaintext)?;
41 let length = blob
42 .len()
43 .checked_add(ENVELOPE_HEADER_LENGTH)
44 .ok_or(ArxKwError::AllocationFailed)?;
45 let mut output = memory::allocate(length)?;
46 output.extend_from_slice(&header::<V>());
47 output.extend_from_slice(&blob);
48 Ok(output)
49}
50
51pub fn decrypt<V: ArxKW + ?Sized>(
52 key: &V::Key,
53 input: &[u8],
54 context: &[u8],
55) -> Result<SecretBytes, ArxKwError> {
56 if input.len() < ENVELOPE_HEADER_LENGTH + 16 || input[..ENVELOPE_HEADER_LENGTH] != header::<V>()
57 {
58 return Err(ArxKwError::InvalidEnvelope);
59 }
60 memory::check_length(
61 input.len() - ENVELOPE_HEADER_LENGTH - 16,
62 V::MAX_INPUT_LENGTH,
63 )?;
64 let key = derive::<V>(key, context)?;
65 V::decrypt_secret(&key, &input[ENVELOPE_HEADER_LENGTH..])
66}
67
68fn derive_bytes(
71 ikm: &[u8],
72 salt: &[u8],
73 info: &[&[u8]],
74 output: &mut [u8],
75) -> Result<(), ArxKwError> {
76 if output.len() > 255 * 32 {
77 return Err(ArxKwError::KeyDerivationFailed);
78 }
79 let mut extract =
80 Hmac::<Sha256>::new_from_slice(salt).map_err(|_| ArxKwError::KeyDerivationFailed)?;
81 extract.update(ikm);
82 let mut raw = extract.finalize().into_bytes();
83 let prk: Zeroizing<[u8; 32]> = Zeroizing::new(*raw.as_ref());
84 raw.as_mut_slice().zeroize();
85 let mut previous = Zeroizing::new([0u8; 32]);
86 for (index, chunk) in output.chunks_mut(32).enumerate() {
87 let mut mac =
88 Hmac::<Sha256>::new_from_slice(&*prk).map_err(|_| ArxKwError::KeyDerivationFailed)?;
89 if index != 0 {
90 mac.update(&*previous);
91 }
92 for part in info {
93 mac.update(part);
94 }
95 mac.update(&[u8::try_from(index + 1).map_err(|_| ArxKwError::KeyDerivationFailed)?]);
96 let mut raw = mac.finalize().into_bytes();
97 previous.copy_from_slice(&raw);
98 raw.as_mut_slice().zeroize();
99 chunk.copy_from_slice(&previous[..chunk.len()]);
100 }
101 Ok(())
102}
103
104#[cfg(test)]
105mod tests {
106 use super::*;
107 #[test]
108 fn rfc5869_case_one_and_provider_agree() {
109 let ikm = [0x0b; 22];
110 let salt: Vec<u8> = (0..=12).collect();
111 let info: Vec<u8> = (0xf0..=0xf9).collect();
112 let mut output = [0u8; 42];
113 derive_bytes(&ikm, &salt, &[&info], &mut output).unwrap();
114 assert_eq!(
115 hex::encode(output),
116 "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865"
117 );
118 let reference = hkdf::Hkdf::<Sha256>::new(Some(&salt), &ikm);
119 let mut expected = [0u8; 42];
120 reference.expand(&info, &mut expected).unwrap();
121 assert_eq!(output, expected);
122 }
123}