feat: cipher 与 cipher.ts 逐字节等价(含上游检验向量)
This commit is contained in:
1 parent
0de161ddef
commit
a7308afbfc
1 file changed
+140
-1
+140
-1
@@ -1,3 +1,142 @@
|
||||
//! cipher —— md5 + AES-256-ECB(与 react 版 cipher.ts 逐字节等价)。
|
||||
//!
|
||||
//! TODO:占位模块,后续任务填充实现。
|
||||
//! 对齐物:`~/Desktop/workspace/skills/ssw-jnpf-lite-react/src/backend/src/common/cipher.ts`
|
||||
//!
|
||||
//! 契约(**不得改动**,见 `.superpowers/sdd/tds-lite-rs-v1/task-1-brief.md`):
|
||||
//! 1. `key = md5_hex("EY8WePvjM5GGwQzn")` —— 把这 **32 个 ASCII 字节**当 key ⇒ **AES-256**
|
||||
//! (⚠️ 不是 16 字节原始摘要;用 16 字节会退化成 AES-128 ⇒ 所有登录全挂)
|
||||
//! 2. `src = md5_hex(plaintext)` 的 **32 个 ASCII 字节**
|
||||
//! 3. `AES-256-ECB-PKCS7`,输出 hex(32 字节明文 ⇒ PKCS7 补满一整块 ⇒ 48 字节密文 ⇒ 96 个 hex 字符)
|
||||
//!
|
||||
//! 🔴 **口令不得外泄**:本模块的输出只在**请求体**里出现(登录时前端传来的密文),
|
||||
//! 永不在响应里回显。库里存的是 `md5(明文)`(`base_user.f_password`)。
|
||||
|
||||
use aes::cipher::{block_padding::Pkcs7, BlockDecryptMut, BlockEncryptMut, KeyInit};
|
||||
use md5::{Digest, Md5};
|
||||
|
||||
/// AES-256-ECB 加密器(cipher 0.4 家族:`BlockEncryptMut` + `Pkcs7`)。
|
||||
type Aes256EcbEnc = ecb::Encryptor<aes::Aes256>;
|
||||
/// AES-256-ECB 解密器。
|
||||
type Aes256EcbDec = ecb::Decryptor<aes::Aes256>;
|
||||
|
||||
/// react 版 cipher.ts 里的 `CIPHER_KEY`。
|
||||
const CIPHER_KEY: &str = "EY8WePvjM5GGwQzn";
|
||||
|
||||
/// AES 分组长度(字节)。
|
||||
const BLOCK_SIZE: usize = 16;
|
||||
|
||||
/// `md5(明文)` 的十六进制串(32 个字符)。
|
||||
///
|
||||
/// 与 react 版 `md5Hex` 等价:CryptoJS.MD5(str).toString() ⇒ 小写 hex。
|
||||
pub fn md5_hex(s: &str) -> String {
|
||||
hex::encode(Md5::digest(s.as_bytes()))
|
||||
}
|
||||
|
||||
/// 派生出 AES-256 key:**32 个 ASCII 字节**(即 `md5_hex(CIPHER_KEY)` 这个 32 字符 hex 串本身)。
|
||||
fn cipher_key_bytes() -> [u8; 32] {
|
||||
let key = md5_hex(CIPHER_KEY);
|
||||
// `md5_hex` 恒为 32 个 ASCII 字符 ⇒ 长度必然是 32。
|
||||
let bytes = key.into_bytes();
|
||||
let mut out = [0u8; 32];
|
||||
out.copy_from_slice(&bytes);
|
||||
out
|
||||
}
|
||||
|
||||
/// 登录密码加密:`md5(明文)` → AES-256-ECB-PKCS7 → hex。
|
||||
///
|
||||
/// 上游检验向量:`encrypt_password("123456")` ==
|
||||
/// `d4958348e22108119b3ef57b022c83f4bf857dd0b247eaab15b9a43d47ee3c503900f7135bf0de255bc33620c3cdc02b`
|
||||
/// (96 个 hex 字符 = 48 字节密文;**不是** 64 —— 漏了 PKCS7 填充就会输出 64)。
|
||||
pub fn encrypt_password(plain: &str) -> String {
|
||||
// src = md5(明文) 的 32 个 ASCII 字节。
|
||||
let src = md5_hex(plain).into_bytes();
|
||||
|
||||
// 32 字节明文 + PKCS7 补满一整块 ⇒ 48 字节密文。
|
||||
let mut buf = [0u8; 48];
|
||||
buf[..src.len()].copy_from_slice(&src);
|
||||
|
||||
let key = cipher_key_bytes();
|
||||
let enc = Aes256EcbEnc::new_from_slice(&key).expect("AES-256 key 长度恒为 32");
|
||||
let ct = enc
|
||||
.encrypt_padded_mut::<Pkcs7>(&mut buf, src.len())
|
||||
.expect("缓冲长度足够容纳 PKCS7 填充");
|
||||
hex::encode(ct)
|
||||
}
|
||||
|
||||
/// 解密前端加密串 → `md5(明文)`,用于登录比对。
|
||||
///
|
||||
/// 非法 hex / 长度不是分组整数倍 / PKCS7 填充不合法 ⇒ `None`。
|
||||
pub fn decrypt_to_md5(encrypted_hex: &str) -> Option<String> {
|
||||
let mut ct = hex::decode(encrypted_hex).ok()?;
|
||||
if ct.is_empty() || ct.len() % BLOCK_SIZE != 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let key = cipher_key_bytes();
|
||||
let dec = Aes256EcbDec::new_from_slice(&key).ok()?;
|
||||
let pt = dec.decrypt_padded_mut::<Pkcs7>(&mut ct).ok()?;
|
||||
String::from_utf8(pt.to_vec()).ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// 上游(react 版 cipher.ts)检验向量 —— 逐字节相等才算通过。
|
||||
#[test]
|
||||
fn encrypt_password_matches_upstream_vector() {
|
||||
assert_eq!(
|
||||
encrypt_password("123456"),
|
||||
"d4958348e22108119b3ef57b022c83f4bf857dd0b247eaab15b9a43d47ee3c503900f7135bf0de255bc33620c3cdc02b"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn md5_hex_of_empty_string() {
|
||||
assert_eq!(md5_hex(""), "d41d8cd98f00b204e9800998ecf8427e");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn md5_hex_of_abc() {
|
||||
assert_eq!(md5_hex("abc"), "900150983cd24fb0d6963f7d28e17f72");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trip_returns_md5_of_plaintext() {
|
||||
assert_eq!(
|
||||
decrypt_to_md5(&encrypt_password("hunter2")),
|
||||
Some(md5_hex("hunter2"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_hex_yields_none() {
|
||||
assert_eq!(decrypt_to_md5("not-hex!!"), None);
|
||||
assert_eq!(decrypt_to_md5("zz"), None);
|
||||
}
|
||||
|
||||
/// 32 字节明文 ⇒ PKCS7 补满一整块 ⇒ 48 字节密文 ⇒ 96 个 hex 字符。
|
||||
#[test]
|
||||
fn ciphertext_length_is_96_hex_chars() {
|
||||
assert_eq!(encrypt_password("x").len(), 96);
|
||||
// 空明文同样走 32 字节 md5,长度不变。
|
||||
assert_eq!(encrypt_password("").len(), 96);
|
||||
}
|
||||
|
||||
/// key 必须是 md5_hex(CIPHER_KEY) 的 **32 个 ASCII 字节** ⇒ AES-256,不是 AES-128。
|
||||
#[test]
|
||||
fn key_is_32_ascii_bytes() {
|
||||
let key = cipher_key_bytes();
|
||||
assert_eq!(key.len(), 32);
|
||||
assert_eq!(std::str::from_utf8(&key).unwrap(), md5_hex(CIPHER_KEY));
|
||||
// 32 字节 key ⇒ AES-256(KeySize = U32)。
|
||||
assert!(Aes256EcbEnc::new_from_slice(&key).is_ok());
|
||||
}
|
||||
|
||||
/// 长度不是分组整数倍 ⇒ None(解不开)。
|
||||
#[test]
|
||||
fn wrong_length_ciphertext_yields_none() {
|
||||
assert_eq!(decrypt_to_md5("00"), None);
|
||||
assert_eq!(decrypt_to_md5(""), None);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user