use aes_gcm::aead::Aead;
use aes_gcm::{Aes256Gcm, KeyInit, Nonce};
use hmac::{Hmac, Mac};
use rand::Rng;
use sha2::{Digest, Sha256};
type HmacSha256 = Hmac<Sha256>;
const AES_NONCE_LEN: usize = 12;
const AES_MAX_CIPHERTEXT_LEN: usize = 1024 * 1024;
const B64_STD_CHARS: [u8; 64] = *b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const B64_URL_CHARS: [u8; 64] = *b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
const B64_INVALID: u8 = 0xFF;
const fn b64_decode_table(chars: &[u8; 64]) -> [u8; 256] {
let mut t = [B64_INVALID; 256];
let mut i = 0;
while i < 64 {
t[chars[i] as usize] = i as u8;
i += 1;
}
t
}
static B64_STD_DECODE: [u8; 256] = b64_decode_table(&B64_STD_CHARS);
static B64_URL_DECODE: [u8; 256] = b64_decode_table(&B64_URL_CHARS);
pub struct Crypto;
impl Crypto {
pub fn encode_hex(data: &[u8]) -> String {
const HEX: &[u8; 16] = b"0123456789abcdef";
let mut out = String::with_capacity(data.len() * 2);
for &b in data {
out.push(HEX[(b >> 4) as usize] as char);
out.push(HEX[(b & 0x0f) as usize] as char);
}
out
}
pub fn decode_hex(s: &str) -> Option<Vec<u8>> {
fn hex_val(c: u8) -> Option<u8> {
match c {
b'0'..=b'9' => Some(c - b'0'),
b'a'..=b'f' => Some(c - b'a' + 10),
b'A'..=b'F' => Some(c - b'A' + 10),
_ => None,
}
}
let bytes = s.as_bytes();
if bytes.len() % 2 != 0 {
return None;
}
let mut out = Vec::with_capacity(bytes.len() / 2);
for chunk in bytes.chunks_exact(2) {
out.push((hex_val(chunk[0])? << 4) | hex_val(chunk[1])?);
}
Some(out)
}
pub fn encode_base64(data: &[u8]) -> String {
Self::encode_base64_with(data, &B64_STD_CHARS, true)
}
pub fn encode_base64_url(data: &[u8]) -> String {
Self::encode_base64_with(data, &B64_URL_CHARS, false)
}
fn encode_base64_with(data: &[u8], chars: &[u8; 64], pad: bool) -> String {
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
for chunk in data.chunks(3) {
let b0 = chunk[0];
let b1 = chunk.get(1).copied().unwrap_or(0);
let b2 = chunk.get(2).copied().unwrap_or(0);
out.push(chars[(b0 >> 2) as usize] as char);
out.push(chars[(((b0 & 0x03) << 4) | (b1 >> 4)) as usize] as char);
out.push(if chunk.len() > 1 {
chars[(((b1 & 0x0f) << 2) | (b2 >> 6)) as usize] as char
} else {
'='
});
out.push(if chunk.len() > 2 {
chars[(b2 & 0x3f) as usize] as char
} else {
'='
});
}
if !pad {
while out.ends_with('=') {
out.pop();
}
}
out
}
pub fn decode_base64(s: &str) -> Option<Vec<u8>> {
Self::decode_base64_with(s, &B64_STD_DECODE, true)
}
pub fn decode_base64_url(s: &str) -> Option<Vec<u8>> {
Self::decode_base64_with(s, &B64_URL_DECODE, false)
}
fn decode_base64_with(s: &str, table: &[u8; 256], require_pad: bool) -> Option<Vec<u8>> {
let bytes = s.as_bytes();
if require_pad {
if bytes.len() % 4 != 0 {
return None;
}
let pad = bytes.iter().rev().take_while(|&&b| b == b'=').count();
if pad > 2 || bytes[..bytes.len() - pad].contains(&b'=') {
return None;
}
}
let mut out = Vec::with_capacity(bytes.len() / 4 * 3 + 3);
let mut acc: u32 = 0;
let mut bits: u32 = 0;
for (i, &b) in bytes.iter().enumerate() {
if b == b'=' {
if bytes[i..].iter().all(|&x| x == b'=') {
break;
}
return None;
}
let v = table[b as usize];
if v == B64_INVALID {
return None;
}
acc = (acc << 6) | v as u32;
bits += 6;
if bits >= 8 {
bits -= 8;
out.push((acc >> bits) as u8);
}
}
if bits >= 6 {
return None;
}
if bits > 0 && (acc & ((1u32 << bits) - 1)) != 0 {
return None;
}
Some(out)
}
pub fn sha256(data: &str) -> String {
let mut hasher = Sha256::new();
hasher.update(data.as_bytes());
Self::encode_hex(&hasher.finalize())
}
pub fn sha256_parts(parts: &[&[u8]]) -> String {
let mut hasher = Sha256::new();
for part in parts {
hasher.update(part);
}
Self::encode_hex(&hasher.finalize())
}
pub fn hmac_sha256(key: &[u8], data: &str) -> String {
let mut mac = <HmacSha256 as hmac::digest::KeyInit>::new_from_slice(key)
.expect("HMAC key size error");
mac.update(data.as_bytes());
Self::encode_hex(&mac.finalize().into_bytes())
}
pub fn aes_encrypt(key: &[u8], plaintext: &str) -> Option<(String, String)> {
if key.len() != 32 {
return None;
}
let cipher = Aes256Gcm::new_from_slice(key).ok()?;
let mut nonce_bytes = [0u8; 12];
rand::thread_rng().fill(&mut nonce_bytes);
let nonce = Nonce::from_slice(&nonce_bytes);
let ciphertext = cipher.encrypt(nonce, plaintext.as_bytes()).ok()?;
Some((
Self::encode_base64(&ciphertext),
Self::encode_base64(&nonce_bytes),
))
}
pub fn aes_decrypt(key: &[u8], ciphertext_b64: &str, nonce_b64: &str) -> Option<String> {
if key.len() != 32 {
return None;
}
let cipher = Aes256Gcm::new_from_slice(key).ok()?;
let ciphertext = Self::decode_base64(ciphertext_b64)?;
if ciphertext.len() > AES_MAX_CIPHERTEXT_LEN {
return None;
}
let nonce_vec = Self::decode_base64(nonce_b64)?;
if nonce_vec.len() != AES_NONCE_LEN {
return None;
}
let nonce = Nonce::from_slice(&nonce_vec);
let plaintext = cipher.decrypt(nonce, ciphertext.as_ref()).ok()?;
String::from_utf8(plaintext).ok()
}
pub fn hash_password(password: &str) -> Result<String, argon2::password_hash::Error> {
use argon2::{Argon2, PasswordHasher};
let salt = argon2::password_hash::SaltString::generate(&mut rand::thread_rng());
let argon2 = Argon2::default();
let hash = argon2.hash_password(password.as_bytes(), &salt)?;
Ok(hash.to_string())
}
pub fn verify_password(
password: &str,
hash: &str,
) -> Result<bool, argon2::password_hash::Error> {
use argon2::{Argon2, PasswordHash, PasswordVerifier};
let parsed = PasswordHash::new(hash)?;
let argon2 = Argon2::default();
Ok(argon2.verify_password(password.as_bytes(), &parsed).is_ok())
}
pub fn base64_url_encode(data: &[u8]) -> String {
Self::encode_base64_url(data)
}
pub fn base64_url_decode(s: &str) -> Option<Vec<u8>> {
Self::decode_base64_url(s)
}
pub fn random_key() -> Vec<u8> {
let mut key = vec![0u8; 32];
rand::thread_rng().fill(&mut key[..]);
key
}
pub fn random_token(len: usize) -> String {
let mut bytes = vec![0u8; len];
rand::thread_rng().fill(&mut bytes[..]);
Self::encode_hex(&bytes)
}
pub fn validate_rsa_ciphertext(encrypted_b64: &str) -> bool {
if encrypted_b64.len() != 344 {
return false;
}
Self::decode_base64(encrypted_b64)
.map(|b| b.len() == 256)
.unwrap_or(false)
}
pub fn rsa_decrypt(encrypted_b64: &str) -> Result<String, String> {
Self::rsa_decrypt_oaep(encrypted_b64)
}
pub fn rsa_decrypt_v15(encrypted_b64: &str) -> Result<String, String> {
Self::rsa_decrypt_pkcs1v15(encrypted_b64)
}
fn rsa_decrypt_oaep(encrypted_b64: &str) -> Result<String, String> {
Self::rsa_decrypt_inner(encrypted_b64, true)
}
fn rsa_decrypt_pkcs1v15(encrypted_b64: &str) -> Result<String, String> {
Self::rsa_decrypt_inner(encrypted_b64, false)
}
fn rsa_decrypt_inner(encrypted_b64: &str, oaep: bool) -> Result<String, String> {
use rsa::pkcs8::DecodePrivateKey;
let pem = std::env::var("RSA_PRIVATE_KEY").unwrap_or_else(|_| {
let paths = ["config/rsa_priv.pem", "rsa_priv.pem"];
for path in &paths {
if let Ok(content) = std::fs::read_to_string(path) {
return content;
}
}
String::new()
});
if pem.is_empty() {
return Err(
"RSA 私钥未配置(设置 RSA_PRIVATE_KEY 或创建 config/rsa_priv.pem)".to_string(),
);
}
let private_key =
rsa::RsaPrivateKey::from_pkcs8_pem(&pem).map_err(|e| format!("私钥解析失败: {}", e))?;
let ciphertext =
Self::decode_base64(encrypted_b64).ok_or_else(|| "Base64 解码失败".to_string())?;
let plaintext = if oaep {
private_key
.decrypt(rsa::Oaep::new::<Sha256>(), &ciphertext)
.map_err(|e| format!("RSA(OAEP) 解密失败: {}", e))?
} else {
private_key
.decrypt(rsa::pkcs1v15::Pkcs1v15Encrypt {}, &ciphertext)
.map_err(|e| format!("RSA(PKCS1v15) 解密失败: {}", e))?
};
String::from_utf8(plaintext).map_err(|_| "解密结果不是有效 UTF-8".to_string())
}
pub fn rsa_encrypt(public_key_pem: &str, plaintext: &str) -> Result<String, String> {
Self::rsa_encrypt_oaep(public_key_pem, plaintext)
}
pub fn rsa_encrypt_v15(public_key_pem: &str, plaintext: &str) -> Result<String, String> {
Self::rsa_encrypt_pkcs1v15(public_key_pem, plaintext)
}
fn rsa_encrypt_oaep(public_key_pem: &str, plaintext: &str) -> Result<String, String> {
Self::rsa_encrypt_inner(public_key_pem, plaintext, true)
}
fn rsa_encrypt_pkcs1v15(public_key_pem: &str, plaintext: &str) -> Result<String, String> {
Self::rsa_encrypt_inner(public_key_pem, plaintext, false)
}
fn rsa_encrypt_inner(
public_key_pem: &str,
plaintext: &str,
oaep: bool,
) -> Result<String, String> {
use rsa::pkcs8::DecodePublicKey;
let public_key = rsa::RsaPublicKey::from_public_key_pem(public_key_pem)
.map_err(|e| format!("公钥解析失败: {}", e))?;
let ciphertext = if oaep {
public_key
.encrypt(
&mut rand::thread_rng(),
rsa::Oaep::new::<Sha256>(),
plaintext.as_bytes(),
)
.map_err(|e| format!("RSA(OAEP) 加密失败: {}", e))?
} else {
public_key
.encrypt(
&mut rand::thread_rng(),
rsa::pkcs1v15::Pkcs1v15Encrypt {},
plaintext.as_bytes(),
)
.map_err(|e| format!("RSA(PKCS1v15) 加密失败: {}", e))?
};
Ok(Self::encode_base64(&ciphertext))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_sha256() {
assert_eq!(Crypto::sha256("hello").len(), 64);
}
#[test]
fn test_sha256_parts_concat_equivalence() {
assert_eq!(
Crypto::sha256_parts(&[b"POST".as_slice(), b":", b"/api/orders", b":", b"{\"id\":1}"]),
Crypto::sha256("POST:/api/orders:{\"id\":1}")
);
assert_eq!(Crypto::sha256_parts(&[b"abc"]), Crypto::sha256("abc"));
assert_eq!(Crypto::sha256_parts(&[]), Crypto::sha256(""));
}
#[test]
fn test_hex_roundtrip() {
let data = [0x00u8, 0x0f, 0x10, 0xff, 0xab, 0xcd];
let enc = Crypto::encode_hex(&data);
assert_eq!(enc, "000f10ffabcd");
assert_eq!(Crypto::decode_hex(&enc).unwrap(), data);
assert!(Crypto::decode_hex("ABC").is_none()); assert!(Crypto::decode_hex("0g").is_none()); assert_eq!(Crypto::decode_hex("").unwrap(), Vec::<u8>::new());
}
#[test]
fn test_base64_roundtrip() {
for data in [
b"".as_slice(),
b"f",
b"fo",
b"foo",
b"foob",
b"fooba",
b"foobar",
&[0x00u8, 0x01, 0xfe, 0xff],
] {
let enc = Crypto::encode_base64(data);
assert_eq!(
Crypto::decode_base64(&enc).unwrap(),
data,
"roundtrip {enc}"
);
}
assert_eq!(Crypto::encode_base64(b"foo"), "Zm9v"); assert_eq!(Crypto::encode_base64(b"foob"), "Zm9vYg==");
let enc = Crypto::encode_base64_url(&[0xfb, 0xff, 0x3f]);
assert!(!enc.contains('+'));
assert!(!enc.contains('/'));
assert!(!enc.contains('='));
assert_eq!(Crypto::decode_base64_url(&enc).unwrap(), [0xfb, 0xff, 0x3f]);
assert!(Crypto::decode_base64("a").is_none());
assert!(Crypto::decode_base64("ab===").is_none());
assert!(Crypto::decode_base64("a=bc").is_none());
}
#[test]
fn test_encrypt_decrypt() {
let key = vec![0u8; 32];
let (ct, nonce64) = Crypto::aes_encrypt(&key, "test-data").unwrap();
let pt = Crypto::aes_decrypt(&key, &ct, &nonce64).unwrap();
assert_eq!(pt, "test-data");
}
#[test]
fn test_decrypt_rejects_bad_inputs() {
let key = vec![0u8; 32];
let (ct, nonce64) = Crypto::aes_encrypt(&key, "test-data").unwrap();
assert!(Crypto::aes_decrypt(&key, &ct, "").is_none());
assert!(Crypto::aes_decrypt(&key, &ct, "AAAA").is_none());
let bad_ct = format!("{}A", &ct[..ct.len() - 2]);
assert!(Crypto::aes_decrypt(&key, &bad_ct, &nonce64).is_none());
assert!(Crypto::aes_decrypt(&key, "!!!", &nonce64).is_none());
assert!(Crypto::aes_decrypt(&[0u8; 16], &ct, &nonce64).is_none());
}
#[test]
fn test_password() {
let hash = Crypto::hash_password("Wordval@2024").unwrap();
assert!(Crypto::verify_password("Wordval@2024", &hash).unwrap());
}
#[test]
fn test_random_key() {
assert_eq!(Crypto::random_key().len(), 32);
}
#[test]
fn test_hmac_and_misc() {
let a = Crypto::hmac_sha256(b"k1", "msg");
let b = Crypto::hmac_sha256(b"k2", "msg");
assert_eq!(a.len(), 64);
assert_eq!(a, Crypto::hmac_sha256(b"k1", "msg"), "同 key 确定性");
assert_ne!(a, b, "不同 key 应不同签名");
assert_ne!(a, Crypto::sha256("msg"));
let t = Crypto::random_token(8);
assert_eq!(t.len(), 16);
assert!(Crypto::decode_hex(&t).is_some());
let enc = Crypto::base64_url_encode(&[0xfb, 0xff, 0xbf]);
assert_eq!(Crypto::base64_url_decode(&enc).unwrap(), [0xfb, 0xff, 0xbf]);
assert_eq!(Crypto::decode_base64_url("Zm9v==").unwrap(), b"foo");
assert!(Crypto::decode_base64("AB==").is_none());
assert!(Crypto::aes_encrypt(&[0u8; 16], "x").is_none());
assert!(Crypto::aes_decrypt(&[0u8; 31], "AAA=", "AAA=").is_none());
}
#[test]
fn test_rsa_validate_and_roundtrip() {
use rsa::pkcs8::{EncodePrivateKey, EncodePublicKey};
assert!(!Crypto::validate_rsa_ciphertext("short"));
assert!(!Crypto::validate_rsa_ciphertext(&"A".repeat(344)));
let ok_ct = Crypto::encode_base64(&[0xA5u8; 256]);
assert_eq!(ok_ct.len(), 344);
assert!(Crypto::validate_rsa_ciphertext(&ok_ct));
std::env::remove_var("RSA_PRIVATE_KEY");
if std::path::Path::new("config/rsa_priv.pem").exists() {
} else {
let e = Crypto::rsa_decrypt(&ok_ct).unwrap_err();
assert!(e.contains("RSA 私钥未配置"), "{}", e);
}
let mut rng = rand::thread_rng();
let priv_key = rsa::RsaPrivateKey::new(&mut rng, 2048).expect("keygen");
let priv_pem = priv_key.to_pkcs8_pem(rsa::pkcs8::LineEnding::LF).unwrap();
let pub_pem = priv_key.to_public_key().to_public_key_pem(rsa::pkcs8::LineEnding::LF).unwrap();
std::env::set_var("RSA_PRIVATE_KEY", priv_pem.as_str());
let ct = Crypto::rsa_encrypt(&pub_pem, "你好-RSA").unwrap();
assert!(Crypto::validate_rsa_ciphertext(&ct));
assert_eq!(Crypto::rsa_decrypt(&ct).unwrap(), "你好-RSA");
assert!(Crypto::rsa_decrypt_v15(&ct).is_err());
let ct15 = Crypto::rsa_encrypt_v15(&pub_pem, "v15").unwrap();
assert_eq!(Crypto::rsa_decrypt_v15(&ct15).unwrap(), "v15");
assert!(Crypto::rsa_encrypt("not a pem", "x").unwrap_err().contains("公钥解析失败"));
assert!(Crypto::rsa_decrypt("!!!").unwrap_err().contains("Base64 解码失败"));
assert!(Crypto::rsa_decrypt(&Crypto::encode_base64(b"short")).is_err());
let mut bad = ct.clone();
bad.remove(0);
bad.insert(0, if ct.starts_with('A') { 'B' } else { 'A' });
assert!(Crypto::rsa_decrypt(&bad).is_err());
std::env::remove_var("RSA_PRIVATE_KEY");
}
}