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
use chacha20poly1305::aead::{Aead, NewAead, Payload};
use tink_core::{utils::wrap_err, TinkError};
pub const CHA_CHA20_KEY_SIZE: usize = 32;
pub const CHA_CHA20_NONCE_SIZE: usize = 12;
const POLY1305_TAG_SIZE: usize = 16;
#[derive(Clone)]
pub struct ChaCha20Poly1305 {
key: chacha20poly1305::Key,
}
impl ChaCha20Poly1305 {
pub fn new(key: &[u8]) -> Result<ChaCha20Poly1305, TinkError> {
if key.len() != CHA_CHA20_KEY_SIZE {
return Err("ChaCha20Poly1305: bad key length".into());
}
Ok(ChaCha20Poly1305 {
key: chacha20poly1305::Key::clone_from_slice(key),
})
}
}
impl tink_core::Aead for ChaCha20Poly1305 {
fn encrypt(&self, pt: &[u8], aad: &[u8]) -> Result<Vec<u8>, TinkError> {
if pt.len() > (isize::MAX as usize) - CHA_CHA20_NONCE_SIZE - POLY1305_TAG_SIZE {
return Err("ChaCha20Poly1305: plaintext too long".into());
}
let cipher = chacha20poly1305::ChaCha20Poly1305::new(&self.key);
let n = new_nonce();
let ct = cipher
.encrypt(&n, Payload { msg: pt, aad })
.map_err(|e| wrap_err("ChaCha20Poly1305", e))?;
let mut ret = Vec::with_capacity(n.len() + ct.len());
ret.extend_from_slice(&n);
ret.extend_from_slice(&ct);
Ok(ret)
}
fn decrypt(&self, ct: &[u8], aad: &[u8]) -> Result<Vec<u8>, TinkError> {
if ct.len() < CHA_CHA20_NONCE_SIZE + POLY1305_TAG_SIZE {
return Err("ChaCha20pPly1305: ciphertext too short".into());
}
let cipher = chacha20poly1305::ChaCha20Poly1305::new(&self.key);
let n = chacha20poly1305::Nonce::from_slice(&ct[..CHA_CHA20_NONCE_SIZE]);
cipher
.decrypt(
n,
Payload {
msg: &ct[CHA_CHA20_NONCE_SIZE..],
aad,
},
)
.map_err(|e| wrap_err("ChaCha20Poly1305", e))
}
}
fn new_nonce() -> chacha20poly1305::Nonce {
let iv = tink_core::subtle::random::get_random_bytes(CHA_CHA20_NONCE_SIZE);
*chacha20poly1305::Nonce::from_slice(&iv)
}