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
#![forbid(unsafe_code)]
use core::{marker::PhantomData, result::Result};
use aranya_buggy::Bug;
use generic_array::GenericArray;
use serde::{Deserialize, Serialize};
use subtle::{Choice, ConstantTimeEq};
use typenum::U64;
use crate::{
aead::{Aead, BufferTooSmallError, KeyData, OpenError, SealError, Tag},
aranya::VerifyingKey,
ciphersuite::SuiteIds,
csprng::{Csprng, Random},
engine::unwrapped,
error::Error,
hash::{tuple_hash, Digest, Hash},
hmac::Hmac,
id::{custom_id, Id, IdError, Identified},
import::Import,
kdf,
zeroize::{Zeroize, ZeroizeOnDrop},
CipherSuite,
};
/// Key material used to derive per-event encryption keys.
pub struct GroupKey<CS> {
seed: [u8; 64],
_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,
_cs: PhantomData,
}
}
}
impl<CS: CipherSuite> GroupKey<CS> {
/// Creates a new, random `GroupKey`.
pub fn new<R: Csprng>(rng: &mut R) -> GroupKey<CS> {
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) -> GroupKeyId {
// ID = HMAC(
// key=GroupKey,
// message="GroupKeyId-v1" || suite_id,
// outputBytes=64,
// )
let mut h = Hmac::<CS::Hash>::new(&self.seed);
h.update(b"GroupKeyId-v1");
h.update(&SuiteIds::from_suite::<CS>().into_bytes());
GroupKeyId(h.tag().into_array().into())
}
/// 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,
/// default::{
/// DefaultCipherSuite,
/// DefaultEngine,
/// },
/// GroupKey,
/// Id,
/// Rng,
/// SigningKey,
/// };
///
/// const MESSAGE: &[u8] = b"hello, world!";
/// const LABEL: &str = "doc test";
/// const PARENT: Id = Id::default();
/// let author = SigningKey::<DefaultCipherSuite>::new(&mut Rng).public().expect("signing key should be valid");
///
/// let key = GroupKey::new(&mut Rng);
///
/// let ciphertext = {
/// let mut dst = vec![0u8; MESSAGE.len() + key.overhead()];
/// key.seal(&mut 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: &mut R,
dst: &mut [u8],
plaintext: &[u8],
ctx: Context<'_, CS>,
) -> Result<(), Error> {
if dst.len() < self.overhead() {
// Not enough room in `dst`.
let required = self
.overhead()
.checked_add(plaintext.len())
.ok_or(Error::Bug(Bug::new(
"overhead + plaintext length must not wrap",
)))?;
return Err(Error::Seal(SealError::BufferTooSmall(BufferTooSmallError(
Some(required),
))));
}
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)?)
}
const EXTRACT_CTX: kdf::Context = kdf::Context {
domain: "kdf-ext-v1",
suite_ids: &SuiteIds::from_suite::<CS>().into_bytes(),
};
const EXPAND_CTX: kdf::Context = kdf::Context {
domain: "kdf-exp-v1",
suite_ids: &SuiteIds::from_suite::<CS>().into_bytes(),
};
/// Derives a key for [`Self::open`] and [`Self::seal`].
fn derive_key(&self, info: &[u8]) -> Result<<CS::Aead as Aead>::Key, Error> {
// GroupKey = KDF(
// key={0,1}^512,
// salt={0}^512,
// info=concat(
// L,
// "kdf-exp-v1",
// suite_id,
// "EventKey_key",
// parent,
// ),
// outputBytes=64,
// )
let prk = Self::EXTRACT_CTX.labeled_extract::<CS::Kdf>(&[], "EventKey_prk", &self.seed);
let key = Self::EXPAND_CTX.labeled_expand::<CS::Kdf, KeyData<CS::Aead>>(
&prk,
"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,
_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> {
Ok(self.id())
}
}
impl<CS: CipherSuite> ConstantTimeEq 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: Id,
/// 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(tuple_hash::<CS::Hash, _>([
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(Debug, Serialize, Deserialize)]
pub struct EncryptedGroupKey<CS: CipherSuite> {
pub(crate) ciphertext: GenericArray<u8, U64>,
pub(crate) tag: Tag<CS::Aead>,
}
impl<CS: CipherSuite> Clone for EncryptedGroupKey<CS> {
#[inline]
fn clone(&self) -> Self {
Self {
ciphertext: self.ciphertext,
tag: self.tag.clone(),
}
}
}