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
use std::convert::TryInto;
use tink_core::{utils::wrap_err, TinkError};
const LEN_DEK: usize = 4;
pub struct KmsEnvelopeAead {
dek_template: tink_proto::KeyTemplate,
remote: Box<dyn tink_core::Aead>,
}
impl Clone for KmsEnvelopeAead {
fn clone(&self) -> Self {
Self {
dek_template: self.dek_template.clone(),
remote: self.remote.box_clone(),
}
}
}
impl KmsEnvelopeAead {
pub fn new(kt: tink_proto::KeyTemplate, remote: Box<dyn tink_core::Aead>) -> KmsEnvelopeAead {
KmsEnvelopeAead {
dek_template: kt,
remote,
}
}
}
impl tink_core::Aead for KmsEnvelopeAead {
fn encrypt(&self, pt: &[u8], aad: &[u8]) -> Result<Vec<u8>, TinkError> {
let dek = tink_core::registry::new_key(&self.dek_template)?;
let encrypted_dek = self.remote.encrypt(&dek, &[])?;
let primitive = match tink_core::registry::primitive(&self.dek_template.type_url, &dek)? {
tink_core::Primitive::Aead(p) => p,
_ => return Err("KmsEnvelopeAead: failed to convert AEAD primitive".into()),
};
let payload = primitive.encrypt(pt, aad)?;
build_cipher_text(&encrypted_dek, &payload)
}
fn decrypt(&self, ct: &[u8], aad: &[u8]) -> Result<Vec<u8>, TinkError> {
if ct.len() <= LEN_DEK {
return Err("KmsEnvelopeAead: invalid ciphertext".into());
}
let ed = u32::from_be_bytes(ct[..LEN_DEK].try_into().unwrap()) as usize;
let ct = &ct[LEN_DEK..];
if ed == 0 || ct.len() < ed {
return Err("KmsEnvelopeAead: invalid ciphertext".into());
}
let encrypted_dek = &ct[..ed];
let payload = &ct[ed..];
let dek = self.remote.decrypt(encrypted_dek, &[])?;
let p = tink_core::registry::primitive(&self.dek_template.type_url, &dek)
.map_err(|e| wrap_err("KmsEnvelopeAead", e))?;
let primitive = match p {
tink_core::Primitive::Aead(p) => p,
_ => return Err("KmsEnvelopeAead: failed to convert AEAD primitive".into()),
};
primitive.decrypt(payload, aad)
}
}
fn build_cipher_text(encrypted_dek: &[u8], payload: &[u8]) -> Result<Vec<u8>, TinkError> {
let mut b = Vec::with_capacity(LEN_DEK + encrypted_dek.len() + payload.len());
b.extend_from_slice(&(encrypted_dek.len() as u32).to_be_bytes());
b.extend_from_slice(encrypted_dek);
b.extend_from_slice(payload);
Ok(b)
}