//! iCenter MSA 信封:RSA-OAEP(SHA-256) 保护一次性 AES-256-GCM 密钥。 use aes_gcm::aead::{Aead, KeyInit}; use aes_gcm::{Aes256Gcm, Nonce}; use base64::engine::general_purpose::STANDARD; use base64::Engine; use rand::rngs::OsRng; use rand::Rng; use rsa::pkcs8::{DecodePublicKey, EncodePublicKey}; use rsa::{Oaep, RsaPrivateKey, RsaPublicKey}; use sha2::Sha256; use crate::error::{Error, Result}; const RSA_ENC_CHUNK: usize = 245; const RSA_DEC_CHUNK: usize = 256; const SPLIT: &str = "$$"; pub struct RsaKeyPair { private: RsaPrivateKey, pub public_b64: String, } impl RsaKeyPair { pub fn generate() -> Result { let private = RsaPrivateKey::new(&mut OsRng, 2048).map_err(crypto)?; let public = RsaPublicKey::from(&private); let public_b64 = STANDARD.encode( public .to_public_key_der() .map_err(crypto)? .as_bytes(), ); Ok(Self { private, public_b64 }) } pub fn decrypt(&self, encrypted_b64: &str) -> Result { let data = STANDARD.decode(encrypted_b64.trim()).map_err(crypto)?; let mut out = Vec::new(); for chunk in data.chunks(RSA_DEC_CHUNK) { out.extend( self.private .decrypt(Oaep::new::(), chunk) .map_err(crypto)?, ); } String::from_utf8(out).map_err(|e| Error::Crypto(e.to_string())) } } /// 32 个随机大写字母,再做 base64。这 32 个 ASCII 字节本身就是 AES 密钥。 pub fn local_key_string() -> String { let raw: String = (0..32) .map(|_| { let n = OsRng.gen_range(0..26); char::from(b'A' + n) }) .collect(); STANDARD.encode(raw.as_bytes()) } pub fn encrypt_rsa(server_pub_b64: &str, plaintext: &str) -> Result { let der = STANDARD.decode(server_pub_b64.trim()).map_err(crypto)?; let public = RsaPublicKey::from_public_key_der(&der).map_err(crypto)?; let data = plaintext.as_bytes(); let mut out = Vec::new(); for chunk in data.chunks(RSA_ENC_CHUNK) { out.extend( public .encrypt(&mut OsRng, Oaep::new::(), chunk) .map_err(crypto)?, ); } Ok(STANDARD.encode(out)) } pub fn encrypt_aes_gcm(plaintext: &str, local_key_string: &str) -> Result { let key = STANDARD.decode(local_key_string).map_err(crypto)?; let cipher = Aes256Gcm::new_from_slice(&key).map_err(crypto)?; let mut iv = [0u8; 12]; OsRng.fill(&mut iv); let ct = cipher .encrypt(Nonce::from_slice(&iv), plaintext.as_bytes()) .map_err(crypto)?; Ok(format!("{}{SPLIT}{}", STANDARD.encode(ct), STANDARD.encode(iv))) } pub fn decrypt_aes_gcm(encrypted_text: &str, data_key_plain: &str) -> Result { let (ct_b64, iv_b64) = encrypted_text .split_once(SPLIT) .ok_or_else(|| Error::Crypto("密文缺少 $$ 分隔".into()))?; let ct = STANDARD.decode(ct_b64.trim()).map_err(crypto)?; let iv = STANDARD.decode(iv_b64.trim()).map_err(crypto)?; let key = STANDARD.decode(data_key_plain.trim()).map_err(crypto)?; let cipher = Aes256Gcm::new_from_slice(&key).map_err(crypto)?; let plain = cipher .decrypt(Nonce::from_slice(&iv), ct.as_ref()) .map_err(crypto)?; String::from_utf8(plain).map_err(|e| Error::Crypto(e.to_string())) } fn crypto(err: impl ToString) -> Error { Error::Crypto(err.to_string()) } #[cfg(test)] mod tests { use super::*; #[test] fn aes_roundtrip() { let key = local_key_string(); let enc = encrypt_aes_gcm("打卡", &key).unwrap(); assert_eq!(decrypt_aes_gcm(&enc, &key).unwrap(), "打卡"); } }