sare_core/format/
keys.rs

1use secrecy::{ExposeSecret, SecretString, SecretVec};
2use serde::{Deserialize, Serialize};
3
4use super::{EncodablePublic, EncodableSecret};
5
6use crate::format::FormatError;
7use crate::format::encryption::EncryptionMetadataFormat;
8use crate::hybrid_kem::{DHAlgorithm, DHKeyPair, KEMAlgorithm, KEMKeyPair};
9use crate::hybrid_sign::{ECAlgorithm, ECKeyPair, PQAlgorithm, PQKeyPair};
10
11use sha2::{Digest, Sha256};
12
13pub const FULLCHAIN_PUBLIC_KEY_PEM_TAG: &str = "SARE FULLCHAIN PUBLIC KEY";
14pub const SIGNATURE_PUBLIC_KEY_PEM_TAG: &str = "SARE SIGNATURE PUBLIC KEY";
15pub const ENCRYPTION_PUBLIC_KEY_PEM_TAG: &str = "SARE ENCRYPTION PUBLIC KEY";
16pub const MASTER_KEY_PEM_TAG: &str = "SARE MASTER KEY";
17
18#[derive(Serialize, Deserialize, Clone)]
19pub struct SignaturePublicKeyFormat {
20    pub ec_algorithm: ECAlgorithm,
21    pub pq_algorithm: PQAlgorithm,
22    pub ec_public_key: Vec<u8>,
23    pub pq_public_key: Vec<u8>,
24}
25
26impl SignaturePublicKeyFormat {
27    pub fn from_keypairs(ec_keypair: ECKeyPair, pq_keypair: PQKeyPair) -> Self {
28        SignaturePublicKeyFormat {
29            ec_algorithm: ec_keypair.algorithm,
30            pq_algorithm: pq_keypair.algorithm,
31            ec_public_key: ec_keypair.public_key,
32            pq_public_key: pq_keypair.public_key,
33        }
34    }
35}
36
37impl EncodablePublic for SignaturePublicKeyFormat {
38    fn encode_bson(&self) -> Vec<u8> {
39        bson::to_vec(&self).unwrap()
40    }
41
42    fn decode_bson(bson_data: &[u8]) -> Result<Self, FormatError> {
43        let public_key = bson::from_slice::<SignaturePublicKeyFormat>(bson_data).unwrap();
44        Ok(public_key)
45    }
46
47    fn encode_pem(&self) -> String {
48        let pem = pem::Pem::new(SIGNATURE_PUBLIC_KEY_PEM_TAG, self.encode_bson().as_slice());
49        pem::encode(&pem)
50    }
51
52    fn decode_pem(pem_public_key: &str) -> Result<Self, FormatError> {
53        let pem = pem::parse(pem_public_key)?;
54
55        let bson_data = pem.contents();
56        Self::decode_bson(bson_data)
57    }
58}
59
60#[derive(Serialize, Deserialize, Clone)]
61pub struct EncryptionPublicKeyFormat {
62    pub dh_algorithm: DHAlgorithm,
63    pub kem_algorithm: KEMAlgorithm,
64    pub dh_public_key: Vec<u8>,
65    pub kem_public_key: Vec<u8>,
66}
67
68impl EncryptionPublicKeyFormat {
69    pub fn from_keypairs(dh_keypair: DHKeyPair, kem_keypair: KEMKeyPair) -> Self {
70        EncryptionPublicKeyFormat {
71            dh_algorithm: dh_keypair.algorithm,
72            kem_algorithm: kem_keypair.algorithm,
73            dh_public_key: dh_keypair.public_key,
74            kem_public_key: kem_keypair.public_key,
75        }
76    }
77}
78
79impl EncodablePublic for EncryptionPublicKeyFormat {
80    fn encode_bson(&self) -> Vec<u8> {
81        bson::to_vec(&self).unwrap()
82    }
83
84    fn decode_bson(bson_data: &[u8]) -> Result<Self, FormatError> {
85        let public_key = bson::from_slice::<EncryptionPublicKeyFormat>(bson_data).unwrap();
86        Ok(public_key)
87    }
88
89    fn encode_pem(&self) -> String {
90        let pem = pem::Pem::new(ENCRYPTION_PUBLIC_KEY_PEM_TAG, self.encode_bson().as_slice());
91        pem::encode(&pem)
92    }
93
94    fn decode_pem(pem_public_key: &str) -> Result<Self, FormatError> {
95        let pem = pem::parse(pem_public_key)?;
96
97        let bson_data = pem.contents();
98        Self::decode_bson(bson_data)
99    }
100}
101
102#[derive(Serialize, Deserialize, Clone)]
103pub struct FullChainPublicKeyFormat {
104    pub signature_public_key: SignaturePublicKeyFormat,
105    pub encryption_public_key: EncryptionPublicKeyFormat,
106}
107
108impl EncodablePublic for FullChainPublicKeyFormat {
109    fn encode_bson(&self) -> Vec<u8> {
110        bson::to_vec(&self).unwrap()
111    }
112
113    fn decode_bson(bson_data: &[u8]) -> Result<Self, FormatError> {
114        let public_key = bson::from_slice::<FullChainPublicKeyFormat>(bson_data).unwrap();
115        Ok(public_key)
116    }
117
118    fn encode_pem(&self) -> String {
119        let pem = pem::Pem::new(FULLCHAIN_PUBLIC_KEY_PEM_TAG, self.encode_bson().as_slice());
120        pem::encode(&pem)
121    }
122
123    fn decode_pem(pem_public_key: &str) -> Result<Self, FormatError> {
124        let pem = pem::parse(pem_public_key)?;
125
126        let bson_data = pem.contents();
127        Self::decode_bson(bson_data)
128    }
129}
130
131impl FullChainPublicKeyFormat {
132    pub fn calculate_fingerprint(&self) -> [u8; 32] {
133        let mut hasher = Sha256::new();
134        let ec_algorithm = &self.signature_public_key.ec_algorithm.to_string();
135        hasher.update(ec_algorithm.as_bytes());
136        let ec_public_key = &self.signature_public_key.ec_public_key;
137        hasher.update(ec_public_key);
138
139        let pq_algorithm = &self.signature_public_key.pq_algorithm.to_string();
140        hasher.update(pq_algorithm.as_bytes());
141        let pq_public_key = &self.signature_public_key.pq_public_key;
142        hasher.update(pq_public_key);
143
144        let dh_algorithm = &self.encryption_public_key.dh_algorithm.to_string();
145        hasher.update(dh_algorithm.as_bytes());
146        let dh_public_key = &self.encryption_public_key.dh_public_key;
147        hasher.update(dh_public_key);
148
149        let kem_algorithm = &self.encryption_public_key.kem_algorithm.to_string();
150        hasher.update(kem_algorithm.as_bytes());
151        let kem_public_key = &self.encryption_public_key.kem_public_key;
152        hasher.update(kem_public_key);
153
154        let fingerprint: [u8; 32] = hasher.finalize().into();
155
156        fingerprint
157    }
158}
159
160#[derive(Serialize, Deserialize)]
161pub struct SecretKeyFormat {
162    pub ec_algorithm: ECAlgorithm,
163    pub pq_algorithm: PQAlgorithm,
164    pub dh_algorithm: DHAlgorithm,
165    pub kem_algorithm: KEMAlgorithm,
166    #[serde(with = "secret_vec_serde")]
167    pub master_seed: SecretVec<u8>,
168    #[serde(skip_serializing_if = "Option::is_none", flatten)]
169    pub encryption_metadata: Option<EncryptionMetadataFormat>,
170}
171
172impl SecretKeyFormat {
173    pub fn calculate_fingerprint(master_seed: SecretVec<u8>) -> Vec<u8> {
174        let mut hasher = Sha256::new();
175        hasher.update(master_seed.expose_secret());
176
177        let fingerprint: [u8; 32] = hasher.finalize().into();
178
179        fingerprint[..=16].to_vec()
180    }
181}
182
183impl EncodableSecret for SecretKeyFormat {
184    fn encode_bson(&self) -> SecretVec<u8> {
185        SecretVec::from(bson::to_vec(&self).unwrap())
186    }
187
188    fn decode_bson(bson_secretkey: &SecretVec<u8>) -> Result<Self, FormatError> {
189        let secret_key = bson::from_slice::<SecretKeyFormat>(bson_secretkey.expose_secret());
190
191        Ok(secret_key?)
192    }
193
194    fn encode_pem(&self) -> SecretString {
195        let pem = pem::Pem::new(
196            MASTER_KEY_PEM_TAG,
197            self.encode_bson().expose_secret().as_slice(),
198        );
199
200        SecretString::from(pem::encode(&pem))
201    }
202
203    fn decode_pem(pem_master_key: SecretString) -> Result<Self, FormatError> {
204        let pem = pem::parse(pem_master_key.expose_secret())?;
205
206        let bson_data = SecretVec::from(pem.into_contents());
207
208        Self::decode_bson(&bson_data)
209    }
210}
211
212mod secret_vec_serde {
213    use secrecy::{ExposeSecret, SecretVec};
214    use serde::{self, Deserialize, Deserializer, Serializer};
215    use serde_bytes::ByteBuf;
216
217    pub fn serialize<S>(data: &SecretVec<u8>, serializer: S) -> Result<S::Ok, S::Error>
218    where
219        S: Serializer,
220    {
221        serializer.serialize_bytes(data.expose_secret())
222    }
223
224    pub fn deserialize<'de, D>(deserializer: D) -> Result<SecretVec<u8>, D::Error>
225    where
226        D: Deserializer<'de>,
227    {
228        let bytes: ByteBuf = ByteBuf::deserialize(deserializer)?;
229        Ok(SecretVec::new(bytes.into_vec()))
230    }
231}