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
use core::fmt::{self, Debug, Formatter};
use aead::{Aead, AeadInPlace, NewAead};
use chacha20poly1305::{ChaCha20Poly1305, XChaCha20Poly1305};
use serde::{Deserialize, Serialize};
use zeroize::Zeroize;
use super::{Chacha20Types, HasKeyAlg, KeyAlg};
use crate::{
buffer::{ArrayKey, ResizeBuffer, Writer},
encrypt::{KeyAeadInPlace, KeyAeadMeta, KeyAeadParams},
error::Error,
generic_array::{typenum::Unsigned, GenericArray},
jwk::{JwkEncoder, ToJwk},
kdf::{FromKeyDerivation, FromKeyExchange, KeyDerivation, KeyExchange},
random::fill_random_deterministic,
repr::{KeyGen, KeyMeta, KeySecretBytes, Seed, SeedMethod},
};
pub static JWK_KEY_TYPE: &'static str = "oct";
pub trait Chacha20Type: 'static {
type Aead: NewAead + Aead + AeadInPlace;
const ALG_TYPE: Chacha20Types;
const JWK_ALG: &'static str;
}
#[derive(Debug)]
pub struct C20P;
impl Chacha20Type for C20P {
type Aead = ChaCha20Poly1305;
const ALG_TYPE: Chacha20Types = Chacha20Types::C20P;
const JWK_ALG: &'static str = "C20P";
}
#[derive(Debug)]
pub struct XC20P;
impl Chacha20Type for XC20P {
type Aead = XChaCha20Poly1305;
const ALG_TYPE: Chacha20Types = Chacha20Types::XC20P;
const JWK_ALG: &'static str = "XC20P";
}
type KeyType<A> = ArrayKey<<<A as Chacha20Type>::Aead as NewAead>::KeySize>;
type NonceSize<A> = <<A as Chacha20Type>::Aead as Aead>::NonceSize;
type TagSize<A> = <<A as Chacha20Type>::Aead as Aead>::TagSize;
#[derive(Serialize, Deserialize, Zeroize)]
#[serde(
transparent,
bound(
deserialize = "KeyType<T>: for<'a> Deserialize<'a>",
serialize = "KeyType<T>: Serialize"
)
)]
pub struct Chacha20Key<T: Chacha20Type>(KeyType<T>);
impl<T: Chacha20Type> Chacha20Key<T> {
pub const KEY_LENGTH: usize = KeyType::<T>::SIZE;
pub const NONCE_LENGTH: usize = NonceSize::<T>::USIZE;
pub const TAG_LENGTH: usize = TagSize::<T>::USIZE;
}
impl<T: Chacha20Type> Clone for Chacha20Key<T> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
impl<T: Chacha20Type> Debug for Chacha20Key<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("Chacha20Key")
.field("alg", &T::JWK_ALG)
.field("key", &self.0)
.finish()
}
}
impl<T: Chacha20Type> PartialEq for Chacha20Key<T> {
fn eq(&self, other: &Self) -> bool {
other.0 == self.0
}
}
impl<T: Chacha20Type> Eq for Chacha20Key<T> {}
impl<T: Chacha20Type> HasKeyAlg for Chacha20Key<T> {
fn algorithm(&self) -> KeyAlg {
KeyAlg::Chacha20(T::ALG_TYPE)
}
}
impl<T: Chacha20Type> KeyMeta for Chacha20Key<T> {
type KeySize = <T::Aead as NewAead>::KeySize;
}
impl<T: Chacha20Type> KeyGen for Chacha20Key<T> {
fn generate() -> Result<Self, Error> {
Ok(Chacha20Key(KeyType::<T>::random()))
}
fn from_seed(seed: Seed<'_>) -> Result<Self, Error>
where
Self: Sized,
{
match seed {
Seed::Bytes(ikm, SeedMethod::Preferred) | Seed::Bytes(ikm, SeedMethod::RandomDet) => {
Ok(Self(KeyType::<T>::try_new_with(|arr| {
fill_random_deterministic(ikm, arr)
})?))
}
#[allow(unreachable_patterns)]
_ => Err(err_msg!(Unsupported)),
}
}
}
impl<T: Chacha20Type> KeySecretBytes for Chacha20Key<T> {
fn from_secret_bytes(key: &[u8]) -> Result<Self, Error> {
if key.len() != KeyType::<T>::SIZE {
return Err(err_msg!(InvalidKeyData));
}
Ok(Self(KeyType::<T>::from_slice(key)))
}
fn with_secret_bytes<O>(&self, f: impl FnOnce(Option<&[u8]>) -> O) -> O {
f(Some(self.0.as_ref()))
}
}
impl<T: Chacha20Type> FromKeyDerivation for Chacha20Key<T> {
fn from_key_derivation<D: KeyDerivation>(mut derive: D) -> Result<Self, Error>
where
Self: Sized,
{
Ok(Self(KeyType::<T>::try_new_with(|arr| {
derive.derive_key_bytes(arr)
})?))
}
}
impl<T: Chacha20Type> KeyAeadMeta for Chacha20Key<T> {
type NonceSize = NonceSize<T>;
type TagSize = TagSize<T>;
}
impl<T: Chacha20Type> KeyAeadInPlace for Chacha20Key<T> {
fn encrypt_in_place(
&self,
buffer: &mut dyn ResizeBuffer,
nonce: &[u8],
aad: &[u8],
) -> Result<usize, Error> {
if nonce.len() != NonceSize::<T>::USIZE {
return Err(err_msg!(InvalidNonce));
}
let nonce = GenericArray::from_slice(nonce);
let chacha = T::Aead::new(self.0.as_ref());
let tag = chacha
.encrypt_in_place_detached(nonce, aad, buffer.as_mut())
.map_err(|_| err_msg!(Encryption, "AEAD encryption error"))?;
let ctext_len = buffer.as_ref().len();
buffer.buffer_write(&tag[..])?;
Ok(ctext_len)
}
fn decrypt_in_place(
&self,
buffer: &mut dyn ResizeBuffer,
nonce: &[u8],
aad: &[u8],
) -> Result<(), Error> {
if nonce.len() != NonceSize::<T>::USIZE {
return Err(err_msg!(InvalidNonce));
}
let nonce = GenericArray::from_slice(nonce);
let buf_len = buffer.as_ref().len();
if buf_len < TagSize::<T>::USIZE {
return Err(err_msg!(InvalidData, "Invalid size for encrypted data"));
}
let tag_start = buf_len - TagSize::<T>::USIZE;
let mut tag = GenericArray::default();
tag.clone_from_slice(&buffer.as_ref()[tag_start..]);
let chacha = T::Aead::new(self.0.as_ref());
chacha
.decrypt_in_place_detached(nonce, aad, &mut buffer.as_mut()[..tag_start], &tag)
.map_err(|_| err_msg!(Encryption, "AEAD decryption error"))?;
buffer.buffer_resize(tag_start)?;
Ok(())
}
fn aead_params(&self) -> KeyAeadParams {
KeyAeadParams {
nonce_length: NonceSize::<T>::USIZE,
tag_length: TagSize::<T>::USIZE,
}
}
}
impl<T: Chacha20Type> ToJwk for Chacha20Key<T> {
fn encode_jwk(&self, enc: &mut JwkEncoder<'_>) -> Result<(), Error> {
if enc.is_public() {
return Err(err_msg!(Unsupported, "Cannot export as a public key"));
}
if !enc.is_thumbprint() {
enc.add_str("alg", T::JWK_ALG)?;
}
enc.add_as_base64("k", self.0.as_ref())?;
enc.add_str("kty", JWK_KEY_TYPE)?;
Ok(())
}
}
impl<Lhs, Rhs, T> FromKeyExchange<Lhs, Rhs> for Chacha20Key<T>
where
Lhs: KeyExchange<Rhs> + ?Sized,
Rhs: ?Sized,
T: Chacha20Type,
{
fn from_key_exchange(lhs: &Lhs, rhs: &Rhs) -> Result<Self, Error> {
Ok(Self(KeyType::<T>::try_new_with(|arr| {
let mut buf = Writer::from_slice(arr);
lhs.write_key_exchange(rhs, &mut buf)?;
if buf.position() != Self::KEY_LENGTH {
return Err(err_msg!(Usage, "Invalid length for key exchange output"));
}
Ok(())
})?))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::buffer::SecretBytes;
use crate::repr::ToSecretBytes;
#[test]
fn encrypt_round_trip() {
fn test_encrypt<T: Chacha20Type>() {
let input = b"hello";
let key = Chacha20Key::<T>::generate().unwrap();
let mut buffer = SecretBytes::from_slice(input);
let nonce = Chacha20Key::<T>::random_nonce();
key.encrypt_in_place(&mut buffer, &nonce, &[]).unwrap();
assert_eq!(buffer.len(), input.len() + Chacha20Key::<T>::TAG_LENGTH);
assert_ne!(&buffer[..], input);
key.decrypt_in_place(&mut buffer, &nonce, &[]).unwrap();
assert_eq!(&buffer[..], input);
}
test_encrypt::<C20P>();
test_encrypt::<XC20P>();
}
#[test]
fn serialize_round_trip() {
fn test_serialize<T: Chacha20Type>() {
let key = Chacha20Key::<T>::generate().unwrap();
let sk = key.to_secret_bytes().unwrap();
let bytes = serde_cbor::to_vec(&key).unwrap();
let deser: &[u8] = serde_cbor::from_slice(bytes.as_ref()).unwrap();
assert_eq!(deser, sk.as_ref());
}
test_serialize::<C20P>();
test_serialize::<XC20P>();
}
}