rainmaker_components/protocomm/security/
mod.rs

1pub(crate) mod sec0;
2pub(crate) mod sec1;
3pub(crate) trait SecurityTrait: Default {
4    fn security_handler(&self, ep: &str, data: Vec<u8>) -> Vec<u8>;
5    fn encrypt(&self, indata: &mut [u8]); // encryption in-place
6    fn decrypt(&self, indata: &mut [u8]); // decryption in-place
7}
8
9/// Encrypting data in Transit
10///
11/// [ProtocommSecurity] is used for signifying the level of encryption to provide while utilizing
12/// [Protocomm]   
13/// It currently provides 2 levels of security:   
14///     - Sec0: It provides plaintext communication. Similar to `NO ENCRYPTION`   
15///     - Sec1: It provides transport encryption using AES128-CTR cipher with ECDH using Curve25519 for key
16///     exchange. Additionally it is also possible to have a Proof-Of-Possession(PoP) key for added
17///     security. PoP is need to be shared by both devices beforehand and is not shared on the
18///     communication channel
19///
20/// [Protocomm]: crate::protocomm::Protocomm
21pub enum ProtocommSecurity {
22    Sec0(sec0::Sec0),
23    // wrap sec1 in box due to difference in runtime sizes of sec0 and sec1
24    Sec1(Box<sec1::Sec1>),
25}
26
27impl Default for ProtocommSecurity {
28    fn default() -> Self {
29        Self::Sec0(sec0::Sec0)
30    }
31}
32
33impl ProtocommSecurity {
34    pub fn new_sec1(pop: Option<String>) -> Self {
35        let sec1 = sec1::Sec1 {
36            pop,
37            ..Default::default()
38        };
39
40        Self::Sec1(Box::new(sec1))
41    }
42}
43
44impl SecurityTrait for ProtocommSecurity {
45    fn security_handler(&self, ep: &str, data: Vec<u8>) -> Vec<u8> {
46        match self {
47            ProtocommSecurity::Sec0(sec_inner) => sec_inner.security_handler(ep, data),
48            ProtocommSecurity::Sec1(sec_inner) => sec_inner.security_handler(ep, data),
49        }
50    }
51
52    fn encrypt(&self, indata: &mut [u8]) {
53        match self {
54            ProtocommSecurity::Sec0(sec_inner) => sec_inner.encrypt(indata),
55            ProtocommSecurity::Sec1(sec_inner) => sec_inner.encrypt(indata),
56        }
57    }
58
59    fn decrypt(&self, indata: &mut [u8]) {
60        match self {
61            ProtocommSecurity::Sec0(sec_inner) => sec_inner.decrypt(indata),
62            ProtocommSecurity::Sec1(sec_inner) => sec_inner.decrypt(indata),
63        }
64    }
65}