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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
use crate::{
    errcode::{Kind, Origin},
    hex_encoding, Error,
};
use cfg_if::cfg_if;
use core::fmt;
use minicbor::{Decode, Encode};
use serde::{Deserialize, Serialize};
use zeroize::Zeroize;

#[cfg(feature = "tag")]
use crate::TypeTag;

/// Curve25519 private key length.
pub const CURVE25519_SECRET_LENGTH_U32: u32 = 32;
/// Curve25519 private key length.
pub const CURVE25519_SECRET_LENGTH_USIZE: usize = 32;

/// Curve25519 public key length.
pub const CURVE25519_PUBLIC_LENGTH_U32: u32 = 32;
/// Curve25519 public key length.
pub const CURVE25519_PUBLIC_LENGTH_USIZE: usize = 32;

/// AES256 private key length.
pub const AES256_SECRET_LENGTH_U32: u32 = 32;
/// AES256 private key length.
pub const AES256_SECRET_LENGTH_USIZE: usize = 32;

/// AES128 private key length.
pub const AES128_SECRET_LENGTH_U32: u32 = 16;
/// AES128 private key length.
pub const AES128_SECRET_LENGTH_USIZE: usize = 16;

cfg_if! {
    if #[cfg(not(feature = "alloc"))] {
        /// Secret Key Vector. The maximum size is 32 bytes.
        pub type SecretKeyVec = heapless::Vec<u8, 32>;
        /// Public Key Vector. The maximum size is 65 bytes.
        pub type PublicKeyVec = heapless::Vec<u8, 65>;
        /// Buffer for small vectors (e.g. an array of attributes). The maximum length is 4 elements.
        pub type SmallBuffer<T> = heapless::Vec<T, 4>;
        /// Buffer for large binaries (e.g. encrypted data). The maximum length is 512 elements.
        pub type Buffer<T> = heapless::Vec<T, 512>;
        /// Signature Vector. The maximum length is 64 characters.
        pub type KeyId = heapless::String<64>;
        /// Signature Vector. The maximum size is 112 bytes.
        pub type SignatureVec = heapless::Vec<u8, 112>;

        impl From<&str> for KeyId {
            fn from(s: &str) -> Self {
                heapless::String::from(s)
            }
        }
    }
    else {
        use alloc::vec::Vec;
        use alloc::string::String;
        /// Secret Key Vector.
        pub type SecretKeyVec = Vec<u8>;
        /// Public Key Vector.
        pub type PublicKeyVec = Vec<u8>;
        /// Buffer for small vectors. (e.g. an array of attributes)
        pub type SmallBuffer<T> = Vec<T>;
        /// Buffer for large binaries. (e.g. encrypted data)
        pub type Buffer<T> = Vec<T>;
        /// ID of a Key.
        pub type KeyId = String;
        /// Signature Vector.
        pub type SignatureVec = Vec<u8>;
    }
}

/// Binary representation of a Secret.
#[derive(Serialize, Deserialize, Clone, Zeroize, Encode, Decode)]
#[zeroize(drop)]
#[cbor(transparent)]
pub struct SecretKey(
    #[serde(with = "hex_encoding")]
    #[n(0)]
    SecretKeyVec,
);

impl SecretKey {
    /// Create a new secret key.
    pub fn new(data: SecretKeyVec) -> Self {
        Self(data)
    }
}

impl fmt::Debug for SecretKey {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.pad("<secret key omitted>")
    }
}

impl Eq for SecretKey {}
impl PartialEq for SecretKey {
    fn eq(&self, o: &Self) -> bool {
        subtle::ConstantTimeEq::ct_eq(&self.0[..], &o.0[..]).into()
    }
}

impl AsRef<[u8]> for SecretKey {
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

/// A public key.
#[derive(Encode, Decode, Serialize, Deserialize, Clone, Debug, Zeroize)]
#[zeroize(drop)]
#[rustfmt::skip]
#[cbor(map)]
pub struct PublicKey {
    #[cfg(feature = "tag")]
    #[serde(skip)]
    #[n(0)] tag: TypeTag<8922437>,
    #[b(1)] data: PublicKeyVec,
    #[n(2)] stype: SecretType,
}

impl Eq for PublicKey {}
impl PartialEq for PublicKey {
    fn eq(&self, o: &Self) -> bool {
        let choice = subtle::ConstantTimeEq::ct_eq(&self.data[..], &o.data[..]);
        choice.into() && self.stype == o.stype
    }
}

impl PublicKey {
    /// Public Key data.
    pub fn data(&self) -> &[u8] {
        &self.data
    }
    /// Corresponding secret key type.
    pub fn stype(&self) -> SecretType {
        self.stype
    }
}

impl PublicKey {
    /// Create a new public key.
    pub fn new(data: PublicKeyVec, stype: SecretType) -> Self {
        PublicKey {
            #[cfg(feature = "tag")]
            tag: TypeTag,
            data,
            stype,
        }
    }
}

impl fmt::Display for PublicKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?} {}", self.stype(), hex::encode(self.data()))
    }
}

/// Binary representation of Signature.
#[derive(Serialize, Deserialize, Clone, Debug, Zeroize)]
pub struct Signature(SignatureVec);

impl Signature {
    /// Create a new signature.
    pub fn new(data: SignatureVec) -> Self {
        Self(data)
    }
}

impl AsRef<[u8]> for Signature {
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

impl Eq for Signature {}

impl PartialEq for Signature {
    fn eq(&self, o: &Self) -> bool {
        subtle::ConstantTimeEq::ct_eq(&self.0[..], &o.0[..]).into()
    }
}

impl From<Signature> for SignatureVec {
    fn from(sig: Signature) -> Self {
        sig.0
    }
}

/// All possible [`SecretType`]s
#[derive(Serialize, Deserialize, Copy, Clone, Debug, Encode, Decode, Eq, PartialEq, Zeroize)]
#[rustfmt::skip]
#[cbor(index_only)]
pub enum SecretType {
    /// Secret buffer
    #[n(1)] Buffer,
    /// AES key
    #[n(2)] Aes,
    /// Curve 22519 key
    #[n(3)] X25519,
    /// Ed 22519 key
    #[n(4)] Ed25519,
    /// NIST P-256 key
    #[n(5)] NistP256
}

/// All possible [`SecretKey`] persistence types
#[derive(Serialize, Deserialize, Copy, Clone, Encode, Decode, Debug, Eq, PartialEq)]
#[rustfmt::skip]
#[cbor(index_only)]
pub enum SecretPersistence {
    /// An ephemeral/temporary secret
    #[n(1)] Ephemeral,
    /// A persistent secret
    #[n(2)] Persistent,
}

/// Attributes for a specific vault.
#[derive(Serialize, Deserialize, Copy, Encode, Decode, Clone, Debug, Eq, PartialEq)]
#[rustfmt::skip]
pub struct SecretAttributes {
    #[n(1)] stype: SecretType,
    #[n(2)] persistence: SecretPersistence,
    #[n(3)] length: u32,
}

impl SecretAttributes {
    /// Return the type of the secret.
    pub fn stype(&self) -> SecretType {
        self.stype
    }
    /// Return the persistence of the secret.
    pub fn persistence(&self) -> SecretPersistence {
        self.persistence
    }
    /// Return the length of the secret.
    pub fn length(&self) -> u32 {
        self.length
    }
}

impl SecretAttributes {
    /// Create a new secret attribute.
    pub fn new(stype: SecretType, persistence: SecretPersistence, length: u32) -> Self {
        SecretAttributes {
            stype,
            persistence,
            length,
        }
    }
}

impl fmt::Display for SecretAttributes {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{:?}({:?}) len:{}",
            self.stype(),
            self.persistence(),
            self.length()
        )
    }
}

/// A public key
#[derive(Clone, Debug, Zeroize)]
#[zeroize(drop)]
pub struct KeyPair {
    secret: KeyId,
    public: PublicKey,
}

impl KeyPair {
    /// Secret key
    pub fn secret(&self) -> &KeyId {
        &self.secret
    }
    /// Public Key
    pub fn public(&self) -> &PublicKey {
        &self.public
    }
}

impl KeyPair {
    /// Create a new key pair
    pub fn new(secret: KeyId, public: PublicKey) -> Self {
        Self { secret, public }
    }
}

/// Secret stored in a Vault Storage
#[derive(Debug, Eq, PartialEq, Clone)]
pub struct VaultEntry {
    key_attributes: SecretAttributes,
    secret: Secret,
}

/// A secret key or reference.
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize, Encode, Decode)]
#[rustfmt::skip]
pub enum Secret {
    /// A secret key.
    #[n(0)] Key(#[n(0)] SecretKey),
    /// Reference to an unmanaged, external secret key of AWS KMS.
    #[n(1)] Aws(#[n(1)] KeyId)
}

impl Secret {
    /// Treat this secret as a secret key and pull the key out.
    ///
    /// # Panics
    ///
    /// If the secret does not hold a key.
    pub fn cast_as_key(&self) -> &SecretKey {
        self.try_as_key().expect("`Secret` holds a key")
    }

    /// Treat this secret as a secret key and try to pull the key out.
    pub fn try_as_key(&self) -> Result<&SecretKey, Error> {
        if let Secret::Key(k) = self {
            Ok(k)
        } else {
            Err(Error::new(
                Origin::Other,
                Kind::Misuse,
                "`Secret` does not hold a key",
            ))
        }
    }
}

impl VaultEntry {
    /// Secret's Attributes
    pub fn key_attributes(&self) -> SecretAttributes {
        self.key_attributes
    }

    /// Get the secret part of this vault entry.
    pub fn secret(&self) -> &Secret {
        &self.secret
    }
}

impl VaultEntry {
    /// Create a new vault entry.
    pub fn new(key_attributes: SecretAttributes, secret: Secret) -> Self {
        VaultEntry {
            key_attributes,
            secret,
        }
    }

    /// Create a new vault entry with a secret key.
    pub fn new_key(key_attributes: SecretAttributes, key: SecretKey) -> Self {
        VaultEntry {
            key_attributes,
            secret: Secret::Key(key),
        }
    }

    /// Create a new vault entry with an external secret key from AWS KMS.
    pub fn new_aws(key_attributes: SecretAttributes, kid: KeyId) -> Self {
        VaultEntry {
            key_attributes,
            secret: Secret::Aws(kid),
        }
    }
}