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
use prost::Message;
use tink_core::{utils::wrap_err, TinkError};
pub const KMS_ENVELOPE_AEAD_KEY_VERSION: u32 = 0;
pub const KMS_ENVELOPE_AEAD_TYPE_URL: &str =
"type.googleapis.com/google.crypto.tink.KmsEnvelopeAeadKey";
#[derive(Default)]
pub(crate) struct KmsEnvelopeAeadKeyManager {}
impl tink_core::registry::KeyManager for KmsEnvelopeAeadKeyManager {
fn primitive(&self, serialized_key: &[u8]) -> Result<tink_core::Primitive, TinkError> {
if serialized_key.is_empty() {
return Err("KmsEnvelopeAeadKeyManager: empty key".into());
}
let key = tink_proto::KmsEnvelopeAeadKey::decode(serialized_key)
.map_err(|e| wrap_err("KmsEnvelopeAeadKeyManager: invalid key", e))?;
validate_key(&key)?;
let key_params = key
.params
.ok_or_else(|| TinkError::new("KmsEnvelopeAeadKeyManager: missing URI"))?;
let uri = key_params.kek_uri;
let kms_client = tink_core::registry::get_kms_client(&uri)?;
let backend = kms_client
.get_aead(&uri)
.map_err(|e| wrap_err("KmsEnvelopeAeadKeyManager: invalid aead backend", e))?;
Ok(tink_core::Primitive::Aead(Box::new(
crate::KmsEnvelopeAead::new(
key_params.dek_template.ok_or_else(|| {
TinkError::new("KmsEnvelopeAeadKeyManager: missing DEK template")
})?,
backend,
),
)))
}
fn new_key(&self, serialized_key_format: &[u8]) -> Result<Vec<u8>, TinkError> {
if serialized_key_format.is_empty() {
return Err("KmsEnvelopeAeadKeyManager: invalid key format".into());
}
let key_format = tink_proto::KmsEnvelopeAeadKeyFormat::decode(serialized_key_format)
.map_err(|e| wrap_err("KmsEnvelopeAeadKeyManager: invalid key format", e))?;
let key = tink_proto::KmsEnvelopeAeadKey {
version: KMS_ENVELOPE_AEAD_KEY_VERSION,
params: Some(key_format),
};
let mut sk = Vec::new();
key.encode(&mut sk)
.map_err(|e| wrap_err("KmsEnvelopeAeadKeyManager: failed to encode new key", e))?;
Ok(sk)
}
fn type_url(&self) -> &'static str {
KMS_ENVELOPE_AEAD_TYPE_URL
}
fn key_material_type(&self) -> tink_proto::key_data::KeyMaterialType {
tink_proto::key_data::KeyMaterialType::Remote
}
}
fn validate_key(key: &tink_proto::KmsEnvelopeAeadKey) -> Result<(), TinkError> {
tink_core::keyset::validate_key_version(key.version, KMS_ENVELOPE_AEAD_KEY_VERSION)
.map_err(|e| wrap_err("KmsEnvelopeAeadKeyManager", e))
}