ppaass_v3_common/crypto/
rsa.rs1use crate::error::CommonError;
2use hyper::body::Bytes;
3pub use rsa::pkcs8::EncodePrivateKey;
4pub use rsa::pkcs8::EncodePublicKey;
5pub use rsa::pkcs8::LineEnding;
6pub use rsa::rand_core::OsRng;
7use rsa::{
8 Pkcs1v15Encrypt,
9 pkcs8::{DecodePrivateKey, DecodePublicKey},
10};
11pub use rsa::{RsaPrivateKey, RsaPublicKey};
12use std::fmt::Debug;
13pub const DEFAULT_AGENT_PRIVATE_KEY_PATH: &str = "AgentPrivateKey.pem";
14pub const DEFAULT_AGENT_PUBLIC_KEY_PATH: &str = "AgentPublicKey.pem";
15pub const DEFAULT_PROXY_PRIVATE_KEY_PATH: &str = "ProxyPrivateKey.pem";
16pub const DEFAULT_PROXY_PUBLIC_KEY_PATH: &str = "ProxyPublicKey.pem";
17
18#[derive(Debug)]
20pub struct RsaCrypto {
21 private_key: RsaPrivateKey,
23 public_key: RsaPublicKey,
25}
26impl RsaCrypto {
27 pub fn new(
28 public_key_content: String,
29 private_key_read_content: String,
30 ) -> Result<Self, CommonError> {
31 let public_key = RsaPublicKey::from_public_key_pem(&public_key_content).map_err(|e| {
32 CommonError::Rsa(format!("Fail to create agent_user public key: {e:?}"))
33 })?;
34 let private_key =
35 RsaPrivateKey::from_pkcs8_pem(&private_key_read_content).map_err(|e| {
36 CommonError::Rsa(format!("Fail to create agent_user private key: {e:?}"))
37 })?;
38 Ok(Self {
39 public_key,
40 private_key,
41 })
42 }
43
44 pub fn encrypt(&self, target: &[u8]) -> Result<Bytes, CommonError> {
46 let result = self
47 .public_key
48 .encrypt(&mut OsRng, Pkcs1v15Encrypt, target.as_ref())
49 .map_err(|e| CommonError::Rsa(format!("Fail to encrypt with agent_user: {e:?}")))?;
50 Ok(result.into())
51 }
52
53 pub fn decrypt(&self, target: &[u8]) -> Result<Bytes, CommonError> {
55 let result = self
56 .private_key
57 .decrypt(Pkcs1v15Encrypt, target.as_ref())
58 .map_err(|e| CommonError::Rsa(format!("Fail to decrypt with agent_user: {e:?}")))?;
59 Ok(result.into())
60 }
61}