cas_lib/asymmetric/
cas_rsa.rs

1use rand::rngs::OsRng;
2use rsa::{
3    pkcs1::{DecodeRsaPublicKey, EncodeRsaPublicKey},
4    pkcs8::{DecodePrivateKey, EncodePrivateKey},
5    RsaPublicKey,
6};
7use rsa::{Pkcs1v15Sign, RsaPrivateKey};
8
9use super::types::{CASRSAEncryption, RSAKeyPairResult};
10
11pub struct CASRSA;
12
13impl CASRSAEncryption for CASRSA {
14    /// Generates an RSA key pair of the specified size.
15    /// The key size must be at of a supported kind like 1024, 2048, 4096 bits.
16    fn generate_rsa_keys(key_size: usize) -> RSAKeyPairResult {
17        // TODO: do a check for key_size, if it is too small, return an error
18        let mut rng: OsRng = OsRng;
19        let private_key: RsaPrivateKey =
20            RsaPrivateKey::new(&mut rng, key_size).expect("failed to generate a key");
21        let public_key: RsaPublicKey = private_key.to_public_key();
22        let result = RSAKeyPairResult {
23            public_key: public_key
24                .to_pkcs1_pem(rsa::pkcs1::LineEnding::LF)
25                .unwrap()
26                .to_string(),
27            private_key: private_key
28                .to_pkcs8_pem(rsa::pkcs8::LineEnding::LF)
29                .unwrap()
30                .to_string(),
31        };
32        result
33    }
34
35    /// Sign the given hash with the provided private key of the RSA key pair.
36    /// The parameter `hash` doesn't necessarily have to be a hash, it can be any data that you want to sign.
37    fn sign(private_key: String, hash: Vec<u8>) -> Vec<u8> {
38        let private_key = RsaPrivateKey::from_pkcs8_pem(&private_key).unwrap();
39        let signed_data = private_key
40            .sign(Pkcs1v15Sign::new_unprefixed(), &hash)
41            .unwrap();
42        signed_data
43    }
44
45
46    /// Verify the signature of the given hash with the provided public key of the RSA key pair.
47    /// The parameter `hash` doesn't necessarily have to be a hash, it can be any data that you want to verify.
48    /// Returns true if the signature is valid, false otherwise.
49    fn verify(public_key: String, hash: Vec<u8>, signature: Vec<u8>) -> bool {
50        let public_key = RsaPublicKey::from_pkcs1_pem(&public_key).unwrap();
51        let verified = public_key.verify(Pkcs1v15Sign::new_unprefixed(), &hash, &signature);
52        if verified.is_err() == false {
53            return true;
54        } else {
55            return false;
56        }
57    }
58}