Skip to main content

steel_crypto/
key_store.rs

1//! This module contains the `KeyStore` struct, which is used to store the server's encryption keys.
2use rsa::{RsaPrivateKey, RsaPublicKey};
3
4/// A struct that stores the server's encryption keys.
5pub struct KeyStore {
6    /// The server's private key.
7    pub private_key: RsaPrivateKey,
8    /// The server's public key in DER format.
9    pub public_key_der: Vec<u8>,
10}
11
12impl KeyStore {
13    /// Creates a new `KeyStore`.
14    #[must_use]
15    pub fn create() -> Self {
16        log::debug!("Creating encryption keys...");
17        let private_key = Self::generate_private_key();
18
19        let public_key = RsaPublicKey::from(&private_key);
20        let public_key_der =
21            crate::public_key_to_bytes(&public_key).expect("Failed to encode public key");
22
23        Self {
24            private_key,
25            public_key_der,
26        }
27    }
28
29    fn generate_private_key() -> RsaPrivateKey {
30        // Found out that OsRng is faster than rand::thread_rng here
31        let mut rng = rand::rng();
32
33        RsaPrivateKey::new(&mut rng, 1024).expect("Failed to generate a key")
34    }
35}
36
37#[cfg(test)]
38mod tests {
39    use super::*;
40
41    #[test]
42    fn public_key_der_round_trips() {
43        let ks = KeyStore::create();
44        let decoded = crate::public_key_from_bytes(&ks.public_key_der).unwrap();
45        assert_eq!(decoded, RsaPublicKey::from(&ks.private_key));
46    }
47}