serde_encrypt/
shared_key.rs1use serde::{Deserialize, Serialize};
4
5use crate::{AsSharedKey, random::RngSingletonImpl};
6use crate::traits::SerdeEncryptPublicKey;
7
8#[derive(Clone, Eq, PartialEq, Hash, Debug, Serialize, Deserialize)]
13pub struct SharedKey([u8; 32]);
14
15impl SharedKey {
16 pub const fn new_const(data: [u8; 32]) -> Self {
18 Self(data)
19 }
20
21 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 const SHAREDKEY_CONST_INTERNAL: SharedKey = SharedKey(STATIC_ARRAY);
67
68 const SHARED_KEY_CONST: SharedKey = SharedKey::new_const(STATIC_ARRAY);
70
71 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}