1use hkdf::Hkdf;
4use hmac::{Hmac, KeyInit, Mac};
5use sha2::{Digest, Sha256};
6use zeroize::{Zeroize, Zeroizing};
7
8use crate::{cipher, AuthorshipHasher, CryptoError};
9
10pub(crate) const ENCRYPTION: &[u8] = b"coven/encryption/v1";
11pub(crate) const JOIN_REQUEST: &[u8] = b"coven/join-request/v1";
12pub(crate) const CONFIRMATION_NUMBER: &[u8] = b"coven/confirmation-number/v1";
13pub(crate) const SEALED_BOX: &[u8] = b"coven/sealed-box/v1";
14pub(crate) const HANDOVER: &[u8] = b"coven/handover/v1";
15pub(crate) const OWN_COPY: &[u8] = b"coven/own-copy/v1";
16pub(crate) const AUTHORSHIP: &[u8] = b"coven/row-authorship/v1";
17pub(crate) const KEPT_VALUE: &[u8] = b"coven/kept-value/v1";
18
19pub(crate) fn derive(key: &[u8; 32], context: &[u8]) -> Zeroizing<[u8; 32]> {
20 let mut output = Zeroizing::new([0; 32]);
21 let (mut extracted, hkdf) = Hkdf::<Sha256>::extract(None, key);
22 extracted.as_mut_slice().zeroize();
23 hkdf.expand(context, output.as_mut())
24 .expect("32-byte derived keys fit HKDF-SHA256's output limit");
25 output
26}
27
28pub(crate) fn derive_label(key: &[u8; 32], label: &[u8]) -> Zeroizing<[u8; 32]> {
29 derive(key, &cipher::context(&[label]))
30}
31
32pub(crate) fn mac(key: &[u8; 32]) -> Hmac<Sha256> {
33 Hmac::<Sha256>::new_from_slice(key).expect("HMAC-SHA256 accepts a 32-byte key")
34}
35
36pub struct EncryptionKey(pub(crate) Zeroizing<[u8; 32]>);
38
39impl EncryptionKey {
40 pub fn seal_object_chunk(
45 &self,
46 path: &str,
47 prefix: &[u8],
48 section: u64,
49 index: u64,
50 plaintext: &[u8],
51 ) -> Result<Vec<u8>, CryptoError> {
52 cipher::seal_random(&self.0, &object_chunk_aad(path, prefix, section, index), plaintext)
53 }
54
55 pub fn open_object_chunk(
58 &self,
59 path: &str,
60 prefix: &[u8],
61 section: u64,
62 index: u64,
63 sealed: &[u8],
64 ) -> Result<Vec<u8>, CryptoError> {
65 cipher::open_random(&self.0, &object_chunk_aad(path, prefix, section, index), sealed)
66 }
67}
68
69impl std::fmt::Debug for EncryptionKey {
70 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71 f.write_str("EncryptionKey([REDACTED])")
72 }
73}
74
75pub struct DerivedKeys {
77 encryption: EncryptionKey,
78 authorship: Zeroizing<[u8; 32]>,
79}
80
81impl DerivedKeys {
82 pub(crate) fn new(key: &[u8; 32]) -> Self {
83 Self {
84 encryption: EncryptionKey(derive_label(key, ENCRYPTION)),
85 authorship: derive_label(key, AUTHORSHIP),
86 }
87 }
88
89 pub fn authorship_hasher(&self) -> AuthorshipHasher {
92 AuthorshipHasher::new(&self.authorship)
93 }
94
95 pub fn seal_object_chunk(
98 &self,
99 path: &str,
100 prefix: &[u8],
101 section: u64,
102 index: u64,
103 plaintext: &[u8],
104 ) -> Result<Vec<u8>, CryptoError> {
105 self.encryption.seal_object_chunk(path, prefix, section, index, plaintext)
106 }
107
108 pub fn reseal_object_chunk(
116 &self,
117 path: &str,
118 prefix: &[u8],
119 section: u64,
120 index: u64,
121 plaintext: &[u8],
122 ) -> Vec<u8> {
123 let key = &self.encryption.0;
124 let mut nonce = mac(key);
125 nonce.update(&cipher::context(&[
126 b"coven/object-nonce/v2",
127 cipher::storage_path(path),
128 prefix,
129 §ion.to_be_bytes(),
130 &index.to_be_bytes(),
131 &Sha256::digest(plaintext),
132 ]));
133 let nonce = nonce.finalize().into_bytes();
134 let nonce: &[u8; 24] = nonce[..24].try_into().expect("24-byte nonce");
135 let mut sealed = nonce.to_vec();
136 sealed.extend(cipher::seal(
137 key,
138 nonce,
139 &object_chunk_aad(path, prefix, section, index),
140 plaintext,
141 ));
142 sealed
143 }
144
145 pub fn open_object_chunk(
148 &self,
149 path: &str,
150 prefix: &[u8],
151 section: u64,
152 index: u64,
153 sealed: &[u8],
154 ) -> Result<Vec<u8>, CryptoError> {
155 self.encryption.open_object_chunk(path, prefix, section, index, sealed)
156 }
157
158 pub fn open_identified_header<const N: usize>(
168 &self,
169 prefix: &[u8],
170 sealed: &[u8],
171 identity: impl FnOnce(&[u8; N]) -> Result<String, CryptoError>,
172 ) -> Result<Vec<u8>, CryptoError> {
173 use chacha20::{
174 cipher::{StreamCipher, StreamCipherSeek},
175 KeyIvInit, XChaCha20,
176 };
177 let (nonce, ciphertext) = sealed.split_at_checked(24).ok_or(CryptoError::Malformed)?;
178 if ciphertext.len().checked_sub(cipher::FILE_CHUNK_TAG_LEN).is_none_or(|length| length < N)
179 {
180 return Err(CryptoError::Malformed);
181 }
182 let mut tentative = Zeroizing::new([0; N]);
183 tentative.copy_from_slice(&ciphertext[..N]);
184 let key: &[u8; 32] = &self.encryption.0;
185 let nonce: &[u8; 24] = nonce.try_into().expect("24-byte split");
186 let mut stream = XChaCha20::new(key.into(), nonce.into());
187 stream.seek(64u64);
189 stream.apply_keystream(tentative.as_mut());
190 let path = identity(&tentative)?;
191 self.open_object_chunk(&path, prefix, 0, 0, sealed)
192 }
193}
194
195impl std::fmt::Debug for DerivedKeys {
196 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
197 f.write_str("DerivedKeys([REDACTED])")
198 }
199}
200
201fn object_chunk_aad(path: &str, prefix: &[u8], section: u64, index: u64) -> Vec<u8> {
202 cipher::context(&[
203 b"coven/object-chunk/v1",
204 cipher::storage_path(path),
205 prefix,
206 §ion.to_be_bytes(),
207 &index.to_be_bytes(),
208 ])
209}
210
211#[cfg(test)]
212#[path = "derivation_tests.rs"]
213mod tests;