1use crate::artifacts::{deserialize_bin_or_b64, serialize_bin_or_b64};
4use crate::artifacts::{MultiRecipientCiphertext, PublicKey, UserSecretKey};
5use crate::consts::*;
6use crate::error::Error;
7use crate::identity::{EncryptionPolicy, HiddenPolicy, Policy};
8
9use ibe::kem::cgw_kv::CGWKV;
10use ibe::kem::mkem::MultiRecipient;
11use ibe::kem::{SharedSecret, IBKEM};
12
13use ibs::gg::Signature;
14
15use alloc::collections::BTreeMap;
16use alloc::fmt::Debug;
17use alloc::string::String;
18use alloc::vec::Vec;
19
20use rand::{CryptoRng, RngCore};
21use serde::{Deserialize, Serialize};
22
23#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone, Copy)]
25pub enum Mode {
26 Streaming {
28 segment_size: u32,
30
31 size_hint: (u64, Option<u64>),
35 },
36
37 InMemory {
39 size: u32,
41 },
42}
43
44impl Default for Mode {
45 fn default() -> Self {
46 Mode::Streaming {
47 segment_size: SYMMETRIC_CRYPTO_DEFAULT_CHUNK,
48 size_hint: (0, None),
49 }
50 }
51}
52
53#[derive(Debug, Eq, PartialEq, Clone, Copy)]
55pub struct Iv<const N: usize>(pub [u8; N]);
56
57impl<const N: usize> Iv<N> {
58 fn random<R: RngCore + CryptoRng>(r: &mut R) -> Self {
59 let mut buf = [0u8; N];
60 r.fill_bytes(&mut buf);
61 Self(buf)
62 }
63}
64
65impl<const N: usize> Serialize for Iv<N> {
67 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
68 where
69 S: serde::Serializer,
70 {
71 serialize_bin_or_b64(&self.0, serializer)
72 }
73}
74
75impl<'de, const N: usize> Deserialize<'de> for Iv<N> {
76 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
77 where
78 D: serde::Deserializer<'de>,
79 {
80 let mut buf = [0u8; N];
81 deserialize_bin_or_b64(&mut buf, deserializer)?;
82
83 Ok(Self(buf))
84 }
85}
86
87#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone, Copy)]
90pub enum Algorithm {
91 Aes128Gcm(Iv<12>),
94}
95
96impl Algorithm {
97 fn new_aes128_gcm<R: RngCore + CryptoRng>(r: &mut R) -> Self {
98 Self::Aes128Gcm(Iv::random(r))
99 }
100}
101
102#[derive(Debug, Serialize, Deserialize, Clone)]
104pub struct Header {
105 pub recipients: BTreeMap<String, RecipientHeader>,
107
108 pub algo: Algorithm,
110
111 #[serde(default)]
113 pub mode: Mode,
114}
115
116#[derive(Serialize, Deserialize, Clone, Debug)]
118pub struct RecipientHeader {
119 pub policy: HiddenPolicy,
121
122 pub ct: MultiRecipientCiphertext<CGWKV>,
124}
125
126impl RecipientHeader {
127 pub fn decaps(&self, usk: &UserSecretKey<CGWKV>) -> Result<SharedSecret, Error> {
131 CGWKV::multi_decaps(None, &usk.0, &self.ct.0).map_err(|_e| Error::KEM)
132 }
133}
134
135impl Header {
136 pub fn new<R: RngCore + CryptoRng>(
138 pk: &PublicKey<CGWKV>,
139 policies: &EncryptionPolicy,
140 rng: &mut R,
141 ) -> Result<(Self, SharedSecret), Error> {
142 let policies: EncryptionPolicy = policies
148 .iter()
149 .map(|(rid, policy)| (rid.clone(), policy.canonical()))
150 .collect();
151
152 let ids = policies
154 .values()
155 .map(Policy::derive_kem::<CGWKV>)
156 .collect::<Result<Vec<<CGWKV as IBKEM>::Id>, _>>()?;
157
158 let (cts, ss) = CGWKV::multi_encaps(&pk.0, &ids[..], rng);
160
161 let recipient_info: BTreeMap<String, RecipientHeader> = policies
163 .iter()
164 .zip(cts)
165 .map(|((rid, policy), ct)| {
166 (
167 rid.clone(),
168 RecipientHeader {
169 policy: policy.to_hidden(),
170 ct: MultiRecipientCiphertext(ct),
171 },
172 )
173 })
174 .collect();
175
176 Ok((
177 Header {
178 recipients: recipient_info,
179 algo: Algorithm::new_aes128_gcm(rng),
180 mode: Mode::default(),
181 },
182 ss,
183 ))
184 }
185
186 pub fn with_mode(mut self, mode: Mode) -> Self {
188 self.mode = mode;
189 self
190 }
191
192 pub fn with_algo(mut self, algo: Algorithm) -> Self {
194 self.algo = algo;
195 self
196 }
197}
198
199#[derive(Debug, Clone, Serialize, Deserialize)]
201pub struct SignatureExt {
202 pub sig: Signature,
204
205 pub pol: Policy,
207}
208
209#[cfg(test)]
210mod tests {
211 use super::*;
212 use crate::test::TestSetup;
213
214 #[test]
215 fn test_enc_dec_json() {
216 let mut rng = rand::thread_rng();
217 let setup = TestSetup::new(&mut rng);
218
219 let (header, _ss) = Header::new(&setup.ibe_pk, &setup.policy, &mut rng).unwrap();
220 let header2 = header.clone();
221
222 let s = serde_json::to_string(&header).unwrap();
223 let decoded: Header = serde_json::from_str(&s).unwrap();
224
225 assert_eq!(decoded.recipients.len(), 2);
226
227 assert_eq!(
228 &decoded.recipients.get("Bob").unwrap().policy,
229 &setup.policy.get("Bob").unwrap().to_hidden()
230 );
231
232 assert_eq!(&decoded.algo, &header2.algo);
233 assert_eq!(&decoded.mode, &header2.mode);
234 }
235
236 #[test]
237 fn test_enc_dec_binary() {
238 let mut rng = rand::thread_rng();
239 let setup = TestSetup::new(&mut rng);
240
241 let (header, _ss) = Header::new(&setup.ibe_pk, &setup.policy, &mut rng).unwrap();
242 let header2 = header.clone();
243
244 let v = crate::bincode_compat::serialize(&header).unwrap();
245 let decoded: Header = crate::bincode_compat::deserialize(&v).unwrap();
246
247 assert_eq!(decoded.recipients.len(), 2);
248 assert_eq!(
249 &decoded.recipients.get("Charlie").unwrap().policy,
250 &setup.policy.get("Charlie").unwrap().to_hidden()
251 );
252 assert_eq!(&decoded.algo, &header2.algo);
253 assert_eq!(&decoded.mode, &header2.mode);
254 }
255
256 #[test]
257 fn test_round() {
258 let mut rng = rand::thread_rng();
261 let setup = TestSetup::new(&mut rng);
262
263 let test_usk = &setup.usks[2];
265
266 let (header, ss1) = Header::new(&setup.ibe_pk, &setup.policy, &mut rng).unwrap();
267 let header2 = header.clone();
268 let header3 = header.clone();
269
270 let bytes = crate::bincode_compat::serialize(&header).unwrap();
272
273 let json = serde_json::to_string(&header2).unwrap();
275
276 let decoded1: Header = crate::bincode_compat::deserialize(&bytes).unwrap();
277 let ss2 = decoded1
278 .recipients
279 .get("Bob")
280 .unwrap()
281 .decaps(test_usk)
282 .unwrap();
283
284 let decoded2: Header = serde_json::from_str(&json).unwrap();
285 let ss3 = decoded2
286 .recipients
287 .get("Bob")
288 .unwrap()
289 .decaps(test_usk)
290 .unwrap();
291
292 assert_eq!(&decoded1.recipients.len(), &header3.recipients.len());
293 assert_eq!(&decoded1.algo, &header3.algo);
294 assert_eq!(&decoded1.mode, &header3.mode);
295
296 assert_eq!(&ss1, &ss2);
298 assert_eq!(&ss1, &ss3);
299 }
300}