vpb 0.1.0

key-value proto buffer for veladb
Documentation
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
#[cfg(any(feature = "aes", feature = "aes-std"))]
use aes::cipher::{KeyIvInit, StreamCipher, StreamCipherError};
#[cfg(any(feature = "aes", feature = "aes-std"))]
use aes::{Aes128, Aes192, Aes256};
use kvstructs::bytes::Bytes;

pub const BLOCK_SIZE: usize = 16;

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)]
#[repr(i32)]
pub enum EncryptionAlgorithm {
    None = 0,
    #[cfg(any(feature = "aes", feature = "aes-std"))]
    Aes = 1,
}

impl EncryptionAlgorithm {
    /// String value of the enum field names used in the ProtoBuf definition.
    ///
    /// The values are not transformed in any way and thus are considered stable
    /// (if the ProtoBuf definition does not change) and safe for programmatic use.
    pub fn as_str_name(&self) -> &'static str {
        match self {
            EncryptionAlgorithm::None => "None",
            #[cfg(any(feature = "aes", feature = "aes-std"))]
            EncryptionAlgorithm::Aes => "Aes",
        }
    }
}

impl EncryptionAlgorithm {
    #[inline]
    pub const fn is_none(&self) -> bool {
        match self {
            #[cfg(any(feature = "aes", feature = "aes-std"))]
            EncryptionAlgorithm::Aes => false,
            _ => true,
        }
    }

    #[inline]
    pub const fn is_some(&self) -> bool {
        match self {
            #[cfg(any(feature = "aes", feature = "aes-std"))]
            EncryptionAlgorithm::Aes => true,
            _ => false,
        }
    }
}

#[derive(Debug, Clone)]
pub struct Encryption {
    algo: EncryptionAlgorithm,
    secret: kvstructs::bytes::Bytes,
}

impl Encryption {
    #[inline]
    pub const fn new() -> Self {
        Self {
            algo: EncryptionAlgorithm::None,
            secret: Bytes::new(),
        }
    }

    /// Set the secret used to encrypt/decrypt the encrypted text.
    #[inline]
    pub fn set_secret(mut self, secret: Bytes) -> Self {
        self.secret = secret;
        self
    }

    /// Set the encryption algorithm to use.
    #[inline]
    pub const fn set_algorithm(mut self, algo: EncryptionAlgorithm) -> Self {
        self.algo = algo;
        self
    }

    #[cfg(any(feature = "aes", feature = "aes-std"))]
    #[inline]
    pub fn aes(secret: impl Into<Bytes>) -> Self {
        Self {
            algo: EncryptionAlgorithm::Aes,
            secret: secret.into(),
        }
    }

    #[inline]
    pub const fn algorithm(&self) -> EncryptionAlgorithm {
        self.algo
    }

    #[inline]
    pub const fn is_none(&self) -> bool {
        self.algo.is_none()
    }

    #[inline]
    pub const fn is_some(&self) -> bool {
        self.algo.is_some()
    }

    #[inline]
    pub fn secret(&self) -> &[u8] {
        self.secret.as_ref()
    }

    #[inline]
    pub fn secret_bytes(&self) -> kvstructs::bytes::Bytes {
        self.secret.clone()
    }

    /// The block size for encryption algorithm
    #[inline]
    pub const fn block_size(&self) -> usize {
        block_size(self.algo)
    }
}

impl prost::Message for Encryption {
    #[allow(unused_variables)]
    fn encode_raw<B>(&self, buf: &mut B)
    where
        B: prost::bytes::BufMut,
    {
        if self.algo != EncryptionAlgorithm::default() {
            prost::encoding::int32::encode(1u32, &(self.algo as i32), buf);
        }
        if self.secret != b"" as &[u8] {
            prost::encoding::bytes::encode(2u32, &self.secret, buf);
        }
    }
    #[allow(unused_variables)]
    fn merge_field<B>(
        &mut self,
        tag: u32,
        wire_type: prost::encoding::WireType,
        buf: &mut B,
        ctx: prost::encoding::DecodeContext,
    ) -> ::core::result::Result<(), prost::DecodeError>
    where
        B: prost::bytes::Buf,
    {
        const STRUCT_NAME: &str = "Encryption";
        match tag {
            1u32 => {
                let value = &mut (self.algo as i32);
                prost::encoding::int32::merge(wire_type, value, buf, ctx).map_err(|mut error| {
                    error.push(STRUCT_NAME, "algo");
                    error
                })
            }
            2u32 => {
                let value = &mut self.secret;
                prost::encoding::bytes::merge(wire_type, value, buf, ctx).map_err(|mut error| {
                    error.push(STRUCT_NAME, "secret");
                    error
                })
            }
            _ => prost::encoding::skip_field(wire_type, tag, buf, ctx),
        }
    }
    #[inline]
    fn encoded_len(&self) -> usize {
        (if self.algo != EncryptionAlgorithm::default() {
            prost::encoding::int32::encoded_len(1u32, &(self.algo as i32))
        } else {
            0
        }) + (if self.secret != b"" as &[u8] {
            prost::encoding::bytes::encoded_len(2u32, &self.secret)
        } else {
            0
        })
    }
    fn clear(&mut self) {
        self.algo = EncryptionAlgorithm::default();
        self.secret.clear();
    }
}

/// AES-128 in CTR mode
#[cfg(any(feature = "aes", feature = "aes-std"))]
pub type Aes128Ctr = ctr::Ctr64BE<Aes128>;

/// AES-192 in CTR mode
#[cfg(any(feature = "aes", feature = "aes-std"))]
pub type Aes192Ctr = ctr::Ctr64BE<Aes192>;

/// AES-256 in CTR mode
#[cfg(any(feature = "aes", feature = "aes-std"))]
pub type Aes256Ctr = ctr::Ctr64BE<Aes256>;

#[cfg(any(feature = "aes", feature = "aes-std"))]
#[derive(Debug, Copy, Clone)]
pub enum AesError {
    InvalidLength(aes::cipher::InvalidLength),
    KeySizeError(usize),
    StreamCipherError(StreamCipherError),
}

#[cfg(any(feature = "aes", feature = "aes-std"))]
impl core::fmt::Display for AesError {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        match self {
            AesError::KeySizeError(size) => write!(
                f,
                "aes: invalid key size {}, only supports 16, 24, 32 length for key",
                size
            ),
            AesError::StreamCipherError(err) => write!(f, "aes: {}", err),
            AesError::InvalidLength(e) => write!(f, "{}", e),
        }
    }
}

#[cfg(all(any(feature = "aes", feature = "aes-std"), feature = "std"))]
impl std::error::Error for AesError {}

#[derive(Debug, Copy, Clone)]
pub enum EncryptError {
    #[cfg(any(feature = "aes", feature = "aes-std"))]
    Aes(AesError),
    LengthMismatch {
        src: usize,
        dst: usize,
    },
    // #[cfg(feature = "std")]
    // IO(std::io::ErrorKind),
}

impl core::fmt::Display for EncryptError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            EncryptError::LengthMismatch { src, dst } => write!(
                f,
                "aes length mismatch: the length of source is {} and the length of destination {}",
                src, dst
            ),
            #[cfg(any(feature = "aes", feature = "aes-std"))]
            EncryptError::Aes(e) => write!(f, "{}", e), // EncryptError::IO(kd) => write!(f, "aes fail to write encrypt stream: {:?}", kd),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for EncryptError {}

/// AES encryption extensions
pub trait Encryptor {
    /// Encrypts self with IV.
    /// Can be used for both encryption and decryption.
    ///
    /// IV:
    ///     - `EncryptionAlgorithm::Aes`: IV is of AES block size.
    ///     - `EncryptionAlgorithm::None`: IV is ignored.
    fn encrypt(
        &mut self,
        key: &[u8],
        iv: &[u8],
        algo: EncryptionAlgorithm,
    ) -> Result<(), EncryptError>
    where
        Self: AsMut<[u8]>,
    {
        let data = self.as_mut();
        encrypt(data, key, iv, algo)
    }

    /// Encrypts self with IV to a new `Vec`.
    /// Can be used for both encryption and decryption.
    ///
    /// IV:
    ///     - `EncryptionAlgorithm::Aes`: IV is of AES block size.
    ///     - `EncryptionAlgorithm::None`: IV is ignored.
    fn encrypt_to_vec(
        &self,
        key: &[u8],
        iv: &[u8],
        algo: EncryptionAlgorithm,
    ) -> Result<Vec<u8>, EncryptError>
    where
        Self: AsRef<[u8]>,
    {
        let src = self.as_ref();
        encrypt_to_vec(src, key, iv, algo)
    }

    /// Encrypts self with IV to `dst`.
    /// Can be used for both encryption and decryption.
    ///
    /// IV:
    ///     - `EncryptionAlgorithm::Aes`: IV is of AES block size.
    ///     - `EncryptionAlgorithm::None`: IV is ignored.
    fn encrypt_to(
        &self,
        dst: &mut [u8],
        key: &[u8],
        iv: &[u8],
        algo: EncryptionAlgorithm,
    ) -> Result<(), EncryptError>
    where
        Self: AsRef<[u8]>,
    {
        let src = self.as_ref();
        encrypt_to(dst, src, key, iv, algo)
    }
}

impl<T> Encryptor for T {}

/// Returns the block size of the encryption algorithm
#[inline(always)]
pub const fn block_size(algo: EncryptionAlgorithm) -> usize {
    match algo {
        EncryptionAlgorithm::None => 0,
        #[cfg(any(feature = "aes", feature = "aes-std"))]
        EncryptionAlgorithm::Aes => BLOCK_SIZE,
    }
}

/// Encrypts data with IV.
/// Can be used for both encryption and decryption.
///
/// IV:
///     - `EncryptionAlgorithm::Aes`: IV is of AES block size.
///     - `EncryptionAlgorithm::None`: IV is ignored.
#[inline]
pub fn encrypt(
    _data: &mut [u8],
    _key: &[u8],
    _iv: &[u8],
    algo: EncryptionAlgorithm,
) -> Result<(), EncryptError> {
    match algo {
        #[cfg(any(feature = "aes", feature = "aes-std"))]
        EncryptionAlgorithm::Aes => aes_encrypt_in(_data, _key, _iv),
        _ => Ok(()),
    }
}

/// Encrypts src with IV to a new `Vec`.
/// Can be used for both encryption and decryption.
///
/// IV:
///     - `EncryptionAlgorithm::Aes`: IV is of AES block size.
///     - `EncryptionAlgorithm::None`: IV is ignored.
#[inline]
pub fn encrypt_to_vec(
    src: &[u8],
    _key: &[u8],
    _iv: &[u8],
    algo: EncryptionAlgorithm,
) -> Result<Vec<u8>, EncryptError> {
    let mut dst = src.to_vec();
    match algo {
        #[cfg(any(feature = "aes", feature = "aes-std"))]
        EncryptionAlgorithm::Aes => aes_encrypt_in(dst.as_mut(), _key, _iv).map(|_| dst),
        _ => Ok(dst),
    }
}

/// Encrypts `src` with IV to `dst`.
/// Can be used for both encryption and decryption.
///
/// IV:
///     - `EncryptionAlgorithm::Aes`: IV is of AES block size.
///     - `EncryptionAlgorithm::None`: IV is ignored.
#[inline]
pub fn encrypt_to(
    dst: &mut [u8],
    src: &[u8],
    _key: &[u8],
    _iv: &[u8],
    algo: EncryptionAlgorithm,
) -> Result<(), EncryptError> {
    if dst.len() != src.len() {
        return Err(EncryptError::LengthMismatch {
            src: src.len(),
            dst: dst.len(),
        });
    }
    dst.copy_from_slice(src);
    match algo {
        #[cfg(any(feature = "aes", feature = "aes-std"))]
        EncryptionAlgorithm::Aes => aes_encrypt_in(dst, _key, _iv),
        _ => Ok(()),
    }
}

#[cfg(any(feature = "aes", feature = "aes-std"))]
#[inline(always)]
fn aes_encrypt_in(dst: &mut [u8], key: &[u8], iv: &[u8]) -> Result<(), EncryptError> {
    let kl = key.len();
    match kl {
        16 => Aes128Ctr::new_from_slices(key, iv)
            .map_err(|e| EncryptError::Aes(AesError::InvalidLength(e)))?
            .try_apply_keystream(dst)
            .map_err(|e| EncryptError::Aes(AesError::StreamCipherError(e))),
        24 => Aes192Ctr::new_from_slices(key, iv)
            .map_err(|e| EncryptError::Aes(AesError::InvalidLength(e)))?
            .try_apply_keystream(dst)
            .map_err(|e| EncryptError::Aes(AesError::StreamCipherError(e))),
        32 => Aes256Ctr::new_from_slices(key, iv)
            .map_err(|e| EncryptError::Aes(AesError::InvalidLength(e)))?
            .try_apply_keystream(dst)
            .map_err(|e| EncryptError::Aes(AesError::StreamCipherError(e))),
        _ => Err(EncryptError::Aes(AesError::KeySizeError(kl))),
    }
}

/// generates IV.
pub fn random_iv() -> [u8; BLOCK_SIZE] {
    #[cfg(feature = "std")]
    {
        use rand::{thread_rng, Rng};
        let mut rng = thread_rng();
        rng.gen::<[u8; BLOCK_SIZE]>()
    }

    #[cfg(not(feature = "std"))]
    {
        use rand::{rngs::OsRng, RngCore};
        let mut key = [0u8; BLOCK_SIZE];
        OsRng.fill_bytes(&mut key);
        key
    }
}

macro_rules! impl_encryption_algo_converter {
        ($($ty:ty),+ $(,)?) => {
            $(
                impl From<$ty> for EncryptionAlgorithm {
                    fn from(val: $ty) -> EncryptionAlgorithm {
                        match val {
                            #[cfg(any(feature = "aes", feature = "aes-std"))]
                            1 => EncryptionAlgorithm::Aes,
                            _ => EncryptionAlgorithm::None,
                        }
                    }
                }
            )*
        };
    }

impl_encryption_algo_converter!(i8, i16, i32, i64, isize, i128, u8, u16, u32, u64, usize, u128);

#[cfg(test)]
mod test {
    use super::*;
    use rand::{thread_rng, Rng};

    #[test]
    fn test_encrypt() {
        let mut rng = thread_rng();
        let key = rng.gen::<[u8; 32]>();
        let iv = random_iv();

        let mut src = [0u8; 1024];
        rng.fill(&mut src);

        let mut dst = vec![0u8; 1024];
        encrypt_to(
            dst.as_mut_slice(),
            &src,
            &key,
            &iv,
            EncryptionAlgorithm::Aes,
        )
        .unwrap();

        let act = encrypt_to_vec(dst.as_slice(), &key, &iv, EncryptionAlgorithm::Aes).unwrap();
        assert_eq!(src.clone().to_vec(), act);

        let mut dst = vec![0u8; 1024];
        encrypt_to(
            dst.as_mut_slice(),
            &src,
            &key,
            &iv,
            EncryptionAlgorithm::None,
        )
        .unwrap();
        assert_eq!(dst.as_slice(), src.as_ref());

        let act = encrypt_to_vec(dst.as_slice(), &key, &iv, EncryptionAlgorithm::None).unwrap();
        assert_eq!(src.clone().to_vec(), act);
    }
}