1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
#![forbid(unsafe_code)]
use core::{cell::OnceCell, iter, marker::PhantomData, result::Result};
use derive_where::derive_where;
use spideroak_crypto::{
aead::{Aead, BufferTooSmallError, KeyData, OpenError, SealError, Tag},
csprng::{Csprng, Random},
ctutils::{Choice, CtEq},
hash::{Digest, Hash},
import::Import,
typenum::U64,
zeroize::{Zeroize as _, ZeroizeOnDrop},
};
use crate::{
aranya::VerifyingKey,
ciphersuite::{CipherSuite, CipherSuiteExt as _},
engine::unwrapped,
error::Error,
hybrid_array::Array,
id::{IdError, Identified, custom_id},
policy::CmdId,
};
/// Key material used to derive per-event encryption keys.
pub struct GroupKey<CS> {
seed: [u8; 64],
id: OnceCell<Result<GroupKeyId, IdError>>,
_cs: PhantomData<CS>,
}
impl<CS> ZeroizeOnDrop for GroupKey<CS> {}
impl<CS> Drop for GroupKey<CS> {
fn drop(&mut self) {
self.seed.zeroize();
}
}
impl<CS> Clone for GroupKey<CS> {
fn clone(&self) -> Self {
Self {
seed: self.seed,
id: OnceCell::new(),
_cs: PhantomData,
}
}
}
impl<CS: CipherSuite> GroupKey<CS> {
/// Creates a new, random `GroupKey`.
pub fn new<R: Csprng>(rng: R) -> Self {
Self::from_seed(Random::random(rng))
}
/// Uniquely identifies the [`GroupKey`].
///
/// Two keys with the same ID are the same key.
#[inline]
pub fn id(&self) -> Result<GroupKeyId, IdError> {
self.id
.get_or_init(|| {
// prk = LabeledExtract(
// "GroupKeyId-v1",
// {0}^n,
// "prk",
// seed,
// )
// GroupKey = LabeledExpand(
// "GroupKeyId-v1",
// prk,
// "id",
// {0}^0,
// )
const DOMAIN: &[u8] = b"GroupKeyId-v1";
let prk = CS::labeled_extract(DOMAIN, &[], b"prk", iter::once::<&[u8]>(&self.seed));
CS::labeled_expand(DOMAIN, &prk, b"id", [])
.map_err(|_| IdError::new("unable to expand PRK"))
.map(GroupKeyId::from_bytes)
})
.clone()
}
/// The size in bytes of the overhead added to plaintexts
/// encrypted with [`seal`][Self::seal].
pub const OVERHEAD: usize = CS::Aead::NONCE_SIZE + CS::Aead::OVERHEAD;
/// Returns the size in bytes of the overhead added to
/// plaintexts encrypted with [`seal`][Self::seal].
///
/// Same as [`OVERHEAD`][Self::OVERHEAD].
pub const fn overhead(&self) -> usize {
Self::OVERHEAD
}
/// Encrypts and authenticates `plaintext` in a particular
/// context.
///
/// The resulting ciphertext is written to `dst`, which must
/// be at least [`overhead`][Self::overhead] bytes longer
/// than `plaintext.len()`.
///
/// # Example
///
/// ```rust
/// # #[cfg(all(feature = "alloc", not(feature = "trng")))]
/// # {
/// use aranya_crypto::{
/// Context, GroupKey, Rng, SigningKey,
/// default::{DefaultCipherSuite, DefaultEngine},
/// policy::CmdId,
/// };
///
/// const MESSAGE: &[u8] = b"hello, world!";
/// const LABEL: &str = "doc test";
/// const PARENT: CmdId = CmdId::default();
/// let author = SigningKey::<DefaultCipherSuite>::new(Rng)
/// .public()
/// .expect("signing key should be valid");
///
/// let key = GroupKey::new(Rng);
///
/// let ciphertext = {
/// let mut dst = vec![0u8; MESSAGE.len() + key.overhead()];
/// key.seal(
/// Rng,
/// &mut dst,
/// MESSAGE,
/// Context {
/// label: LABEL,
/// parent: PARENT,
/// author_sign_pk: &author,
/// },
/// )
/// .expect("should not fail");
/// dst
/// };
/// let plaintext = {
/// let mut dst = vec![0u8; ciphertext.len() - key.overhead()];
/// key.open(
/// &mut dst,
/// &ciphertext,
/// Context {
/// label: LABEL,
/// parent: PARENT,
/// author_sign_pk: &author,
/// },
/// )
/// .expect("should not fail");
/// dst
/// };
/// assert_eq!(&plaintext, MESSAGE);
/// # }
/// ```
pub fn seal<R: Csprng>(
&self,
rng: R,
dst: &mut [u8],
plaintext: &[u8],
ctx: Context<'_, CS>,
) -> Result<(), Error> {
if dst.len() < self.overhead() {
// Not enough room in `dst`.
return Err(Error::Seal(SealError::BufferTooSmall(BufferTooSmallError(
self.overhead().checked_add(plaintext.len()),
))));
}
let (nonce, out) = dst.split_at_mut(CS::Aead::NONCE_SIZE);
rng.fill_bytes(nonce);
let info = ctx.to_bytes()?;
let key = self.derive_key(&info)?;
Ok(CS::Aead::new(&key).seal(out, nonce, plaintext, &info)?)
}
/// Decrypts and authenticates `ciphertext` in a particular
/// context.
///
/// The resulting plaintext is written to `dst`, which must
/// be at least as long as the original plaintext (i.e.,
/// `ciphertext.len()` - [`overhead`][Self::overhead] bytes
/// long).
pub fn open(
&self,
dst: &mut [u8],
ciphertext: &[u8],
ctx: Context<'_, CS>,
) -> Result<(), Error> {
if ciphertext.len() < self.overhead() {
// Can't find the nonce and/or tag, so it's obviously
// invalid.
return Err(OpenError::Authentication.into());
}
let (nonce, ciphertext) = ciphertext.split_at(CS::Aead::NONCE_SIZE);
let info = ctx.to_bytes()?;
let key = self.derive_key(&info)?;
Ok(CS::Aead::new(&key).open(dst, nonce, ciphertext, &info)?)
}
/// Derives a key for [`Self::open`] and [`Self::seal`].
fn derive_key(&self, info: &[u8]) -> Result<<CS::Aead as Aead>::Key, Error> {
// prk = LabeledExtract(
// "kdf-ext-v1",
// {0}^n,
// "EventKey_prk",
// seed,
// )
// GroupKey = LabeledExpand(
// "kdf-exp-v1",
// prk,
// "EventKey_key",
// info,
// )
let prk = CS::labeled_extract(
b"kdf-ext-v1",
&[],
b"EventKey_prk",
iter::once::<&[u8]>(&self.seed),
);
let key: KeyData<CS::Aead> =
CS::labeled_expand(b"kdr-exp-v1", &prk, b"EventKey_key", [info])?;
Ok(<<CS::Aead as Aead>::Key as Import<_>>::import(
key.as_bytes(),
)?)
}
// Utility routines for other modules.
/// Returns the underlying seed.
pub(crate) const fn raw_seed(&self) -> &[u8; 64] {
&self.seed
}
/// Creates itself from the seed.
pub(crate) const fn from_seed(seed: [u8; 64]) -> Self {
Self {
seed,
id: OnceCell::new(),
_cs: PhantomData,
}
}
}
unwrapped! {
name: GroupKey;
type: Seed;
into: |key: Self| { key.seed };
from: |seed: [u8;64] | { Self::from_seed(seed) };
}
impl<CS: CipherSuite> Identified for GroupKey<CS> {
type Id = GroupKeyId;
#[inline]
fn id(&self) -> Result<Self::Id, IdError> {
self.id()
}
}
impl<CS: CipherSuite> CtEq for GroupKey<CS> {
#[inline]
fn ct_eq(&self, other: &Self) -> Choice {
self.seed.ct_eq(&other.seed)
}
}
/// Contextual binding for [`GroupKey::seal`] and
/// [`GroupKey::open`].
pub struct Context<'a, CS: CipherSuite> {
/// Describes what is being encrypted.
///
/// For example, it could be an event name.
pub label: &'a str,
/// The stable ID of the parent event.
pub parent: CmdId,
/// The public key of the author of the encrypted data.
pub author_sign_pk: &'a VerifyingKey<CS>,
}
impl<CS: CipherSuite> Context<'_, CS> {
/// Converts the [`Context`] to its byte representation.
fn to_bytes(&self) -> Result<Digest<<CS::Hash as Hash>::DigestSize>, Error> {
// Ideally, this would simple be the actual concatenation
// of `Context`'s fields. However, we need to be
// `no_alloc` and without `const_generic_exprs` it's
// quite difficult to concatenate the fields into
// a fixed-size buffer.
//
// So, we instead hash the fields into a fixed-size
// buffer. We use `tuple_hash` out of paranoia, but
// a regular hash should also suffice.
Ok(CS::tuple_hash(
b"GroupKey",
[
self.label.as_bytes(),
self.parent.as_ref(),
self.author_sign_pk.id()?.as_bytes(),
],
))
}
}
custom_id! {
/// Uniquely identifies a [`GroupKey`].
pub struct GroupKeyId;
}
/// An encrypted [`GroupKey`].
#[derive_where(Clone, Debug, Serialize, Deserialize)]
pub struct EncryptedGroupKey<CS: CipherSuite> {
pub(crate) ciphertext: Array<u8, U64>,
pub(crate) tag: Tag<CS::Aead>,
}
#[cfg(test)]
mod tests {
#![allow(clippy::arithmetic_side_effects)]
use super::*;
use crate::{Rng, SigningKey, default::DefaultCipherSuite};
type CS = DefaultCipherSuite;
fn author() -> VerifyingKey<CS> {
SigningKey::<CS>::new(Rng)
.public()
.expect("signing key should be valid")
}
fn ctx<'a>(author: &'a VerifyingKey<CS>) -> Context<'a, CS> {
Context {
label: "test",
parent: CmdId::default(),
author_sign_pk: author,
}
}
/// Exercises both the happy path and the "`dst` too small"
/// error path of [`GroupKey::seal`].
#[test]
fn test_seal_dst_too_small() {
let author = author();
let key = GroupKey::<CS>::new(Rng);
const MESSAGE: &[u8] = b"hello, world!";
// Happy path: `dst` is large enough.
let mut dst = vec![0u8; MESSAGE.len() + key.overhead()];
key.seal(Rng, &mut dst, MESSAGE, ctx(&author))
.expect("`seal` should succeed");
// Error path: `dst` is shorter than `overhead()`.
let mut small = [0u8; 1];
let err = key
.seal(Rng, &mut small, MESSAGE, ctx(&author))
.expect_err("`seal` should fail when `dst` is too small");
assert!(matches!(err, Error::Seal(_)), "got {err:?}");
}
/// Exercises both the happy path and the "`ciphertext` too
/// short" error path of [`GroupKey::open`].
#[test]
fn test_open_ciphertext_too_short() {
let author = author();
let key = GroupKey::<CS>::new(Rng);
const MESSAGE: &[u8] = b"hello, world!";
let mut ciphertext = vec![0u8; MESSAGE.len() + key.overhead()];
key.seal(Rng, &mut ciphertext, MESSAGE, ctx(&author))
.expect("`seal` should succeed");
// Happy path: decrypt the full ciphertext.
let mut plaintext = vec![0u8; ciphertext.len() - key.overhead()];
key.open(&mut plaintext, &ciphertext, ctx(&author))
.expect("`open` should succeed");
assert_eq!(plaintext, MESSAGE);
// Error path: `ciphertext` is shorter than `overhead()`.
let err = key
.open(&mut plaintext, b"short", ctx(&author))
.expect_err("`open` should fail when `ciphertext` is too short");
assert!(matches!(err, Error::Open(_)), "got {err:?}");
}
}