serde_encrypt/
shared_key.rs

1//! serde-serializable shared key.
2
3use serde::{Deserialize, Serialize};
4
5use crate::{AsSharedKey, random::RngSingletonImpl};
6use crate::traits::SerdeEncryptPublicKey;
7
8/// 32-byte key shared among sender and receiver secretly.
9///
10/// It is a good practice to use [SerdeEncryptPublicKey](crate::traits::SerdeEncryptPublicKey)
11/// to exchange this shared key.
12#[derive(Clone, Eq, PartialEq, Hash, Debug, Serialize, Deserialize)]
13pub struct SharedKey([u8; 32]);
14
15impl SharedKey {
16    /// Build SharedKey from static `[u8; 32]` data at compile time.
17    pub const fn new_const(data: [u8; 32]) -> Self {
18        Self(data)
19    }
20
21    /// Build SharedKey from `[u8; 32]` data.
22    pub fn new(data: [u8; 32]) -> Self {
23        Self(data)
24    }
25}
26
27impl AsSharedKey for SharedKey {
28    type R = RngSingletonImpl;
29
30    fn from_array(key: [u8; 32]) -> Self {
31        Self(key)
32    }
33
34    fn as_slice(&self) -> &[u8] {
35        &self.0
36    }
37}
38
39cfg_if::cfg_if! {
40    if #[cfg(feature = "std")] {
41        use crate::serialize::impls::BincodeSerializer;
42        impl SerdeEncryptPublicKey for SharedKey {
43            type S = BincodeSerializer<Self>;
44        }
45    } else {
46        use crate::serialize::impls::PostcardSerializer;
47        impl SerdeEncryptPublicKey for SharedKey {
48            type S = PostcardSerializer<Self>;
49        }
50    }
51}
52
53#[cfg(test)]
54mod test {
55    use std::convert::TryInto;
56    use super::*;
57
58    #[test]
59    fn build_sharedkey_from_array() {
60        const STATIC_ARRAY: [u8; 32] = [1, 1, 4, 5, 1, 4,
61            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
62
63        let runtime_array: [u8; 32] = Vec::from(STATIC_ARRAY).try_into().unwrap();
64
65        // Building SharedKey directly from static_array only works in the same mod.
66        const SHAREDKEY_CONST_INTERNAL: SharedKey = SharedKey(STATIC_ARRAY);
67
68        // Test `const fn new`, which build SharedKey in compile time
69        const SHARED_KEY_CONST: SharedKey = SharedKey::new_const(STATIC_ARRAY);
70
71        // Test `fn new`, which build SharedKey in runtime.
72        let shared_key = SharedKey::new(runtime_array);
73
74        assert_eq!(shared_key, SHAREDKEY_CONST_INTERNAL);
75        assert_eq!(SHARED_KEY_CONST, SHAREDKEY_CONST_INTERNAL);
76    }
77}