数据安全与加密
原理
加密基本原则:不发明加密算法。使用经过审计的库(ring、aes-gcm、chacha20poly1305)。
对称加密:AES-256-GCM(带认证的加密)同时提供机密性和完整性。Nonce(一次性数字)必须是唯一但不能是秘密的。ChaCha20-Poly1305 适用于无 AES-NI 指令集的平台。
非对称加密:X25519 密钥交换 + Ed25519 数字签名。Curve25519 系列因其安全性、性能和简单性优于传统的 RSA 和 ECDSA。
密钥管理:使用 zeroize crate 确保密钥在不再需要时从内存中安全擦除(避免被 swap 或核心转储泄漏)。硬件安全模块(HSM)和 TPM 提供硬件级密钥保护。
哈希函数:SHA-256 用于一般哈希,Argon2id 用于密码存储(抵抗 ASIC/GPU 暴力破解)。
语法
use aes_gcm::{Aes256Gcm, Nonce, KeyInit};
use aes_gcm::aead::{Aead, OsRng};
use zeroize::Zeroize;
// AES-256-GCM 加密
fn encrypt(key: &[u8; 32], plaintext: &[u8]) -> Vec<u8> {
let cipher = Aes256Gcm::new_from_slice(key).unwrap();
let nonce = Aes256Gcm::generate_nonce(&mut OsRng);
let ciphertext = cipher.encrypt(&nonce, plaintext).unwrap();
[nonce.as_slice(), &ciphertext].concat()
}
// 密钥安全擦除
let mut key = [0u8; 32];
// ... 生成密钥 ...
key.zeroize(); // 覆盖为全零// Argon2id 密码哈希
use argon2::Argon2;
use password_hash::{SaltString, PasswordHasher, rand_core::OsRng};
fn hash_password(password: &[u8]) -> String {
let salt = SaltString::generate(&mut OsRng);
Argon2::default().hash_password(password, &salt).unwrap().to_string()
}加密算法速查
| 用途 | 算法 | 安全级别 |
|---|---|---|
| 对称加密 | AES-256-GCM | 高(128-bit security) |
| 对称加密(嵌入式) | ChaCha20-Poly1305 | 高 |
| 密钥交换 | X25519 | 高 |
| 数字签名 | Ed25519 | 高 |
| 密码哈希 | Argon2id | 高 |
| 通用哈希 | SHA-256 | 中等 |
实践
AI 自检
- AES-GCM 的 nonce 为什么必须唯一?nonce 重用导致什么安全后果?
zeroize如何在 LLVM 优化下保证内存覆盖不被优化掉?