wordval-utils 1.0.3

Wordval utilities: string manipulation, date handling, masking, ID generation, validation, crypto, web helpers, collection tools, retry utilities
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
//! 加密解密工具

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>;

/// AES-GCM nonce 固定 12 字节
const AES_NONCE_LEN: usize = 12;
/// AES 解密允许的最大密文长度(1MB)
const AES_MAX_CIPHERTEXT_LEN: usize = 1024 * 1024;

// ── Base64 字符表与解码查找表 ──

/// Base64 标准字符表
const B64_STD_CHARS: [u8; 64] = *b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/// Base64 URL 安全字符表
const B64_URL_CHARS: [u8; 64] = *b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
/// 解码表中的非法字符标记
const B64_INVALID: u8 = 0xFF;

/// 编译期生成 Base64 解码查找表(字节 → 6 位值,非法字节为 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);

/// 加密解密工具集
///
/// 提供 SHA-256、HMAC、AES-256-GCM、Argon2 密码哈希、Base64 URL 编解码、
/// 随机密钥/Token 生成等常用密码学操作。
pub struct Crypto;

impl Crypto {
    // ── hex 编解码(自研,替代 hex crate) ──

    /// hex 编码(小写,2 字符/字节)
    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
    }

    /// hex 解码(接受大小写混合,非法字符/奇数长度返回 None)
    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)
    }

    // ── Base64 编解码(自研,替代 base64 crate) ──

    /// Base64 标准编码(带 `=` 填充)
    pub fn encode_base64(data: &[u8]) -> String {
        Self::encode_base64_with(data, &B64_STD_CHARS, true)
    }

    /// Base64 URL 安全编码(`-`/`_`,无填充,适合 URL/文件名)
    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
    }

    /// Base64 标准解码(严格校验:长度 4 的倍数、`=` 仅限尾部 0-2 个、余位清零)
    pub fn decode_base64(s: &str) -> Option<Vec<u8>> {
        Self::decode_base64_with(s, &B64_STD_DECODE, true)
    }

    /// Base64 URL 安全解码(无填充,忽略尾部 `=`)
    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 {
            // 严格模式:长度须为 4 的倍数,`=` 只允许出现在尾部且至多 2 个
            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);
            }
        }
        // 剩余 6 位(即长度 % 4 == 1)无法构成合法编码
        if bits >= 6 {
            return None;
        }
        // 余位必须全 0,否则是非规范编码
        if bits > 0 && (acc & ((1u32 << bits) - 1)) != 0 {
            return None;
        }
        Some(out)
    }

    /// SHA-256 哈希(返回 hex 编码,64 字符)
    pub fn sha256(data: &str) -> String {
        let mut hasher = Sha256::new();
        hasher.update(data.as_bytes());
        Self::encode_hex(&hasher.finalize())
    }

    /// HMAC-SHA256 签名(返回 hex 编码)
    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())
    }

    /// AES-256-GCM 加密
    ///
    /// - `key`: 32 字节密钥,若非 32 字节返回 `None`
    /// - 返回 `(Base64 密文, Base64 nonce)` 元组
    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),
        ))
    }

    /// AES-256-GCM 解密(与 `aes_encrypt` 配对使用)
    ///
    /// 校验输入长度(GCM nonce 固定 12 字节、密文上限 1MB),非法输入返回 `None`。
    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)?;
        // GCM 密文 = 明文 + 16 字节 tag;密文长度上限 1MB
        if ciphertext.len() > AES_MAX_CIPHERTEXT_LEN {
            return None;
        }
        let nonce_vec = Self::decode_base64(nonce_b64)?;
        // GCM nonce 固定 12 字节:长度不符返回 None
        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()
    }

    /// Argon2 密码哈希(自动生成随机盐)
    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())
    }

    /// 验证密码是否匹配 Argon2 哈希
    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())
    }

    /// Base64 URL 安全编码(无填充,适合放在 URL/文件名中)
    pub fn base64_url_encode(data: &[u8]) -> String {
        Self::encode_base64_url(data)
    }

    /// Base64 URL 安全解码
    pub fn base64_url_decode(s: &str) -> Option<Vec<u8>> {
        Self::decode_base64_url(s)
    }

    /// 生成 32 字节随机密钥(用于 AES-256-GCM)
    pub fn random_key() -> Vec<u8> {
        let mut key = vec![0u8; 32];
        rand::thread_rng().fill(&mut key[..]);
        key
    }

    /// 生成随机 hex Token
    pub fn random_token(len: usize) -> String {
        let mut bytes = vec![0u8; len];
        rand::thread_rng().fill(&mut bytes[..]);
        Self::encode_hex(&bytes)
    }

    // ─── RSA 加密/解密(默认 OAEP + SHA-256;PKCS#1 v1.5 变体见 *_v15) ───

    /// 校验 RSA 密文格式是否合法(Base64 + 256 字节)。
    /// RSA 2048 加密结果固定为 256 字节 → Base64 编码后固定为 344 字符。
    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)
    }

    /// 使用 RSA 私钥(PKCS#8 PEM)解密密文,返回 UTF-8 原文。
    ///
    /// **默认使用 OAEP(SHA-256)填充**。
    /// 私钥优先读取 `RSA_PRIVATE_KEY` 环境变量,其次尝试 `config/rsa_priv.pem` 文件。
    pub fn rsa_decrypt(encrypted_b64: &str) -> Result<String, String> {
        Self::rsa_decrypt_oaep(encrypted_b64)
    }

    /// 使用 PKCS#1 v1.5 填充解密(与 node-forge 默认方式一致)
    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(|_| {
            // 回退到文件读取(支持多行 PEM 格式)
            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())
    }

    /// 使用 RSA 公钥(PKCS#8/SPKI PEM)加密明文,返回 Base64 密文。
    ///
    /// **默认使用 OAEP(SHA-256)填充**。用于公共服务或测试验证。
    pub fn rsa_encrypt(public_key_pem: &str, plaintext: &str) -> Result<String, String> {
        Self::rsa_encrypt_oaep(public_key_pem, plaintext)
    }

    /// 使用 PKCS#1 v1.5 填充加密(与 node-forge 默认方式一致)
    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_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_eq!(Crypto::decode_hex("ABC").is_none(), true); // 奇数长度
        assert_eq!(Crypto::decode_hex("0g").is_none(), true); // 非法字符
        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==");
        // URL 安全无填充
        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_eq!(Crypto::decode_base64("a").is_none(), true);
        assert_eq!(Crypto::decode_base64("ab===").is_none(), true);
        assert_eq!(Crypto::decode_base64("a=bc").is_none(), true);
    }
    #[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();
        // nonce 长度非 12 字节 → None(而非 panic)
        assert_eq!(Crypto::aes_decrypt(&key, &ct, "").is_none(), true);
        assert_eq!(Crypto::aes_decrypt(&key, &ct, "AAAA").is_none(), true);
        // 篡改密文 → GCM 认证失败 → None
        let bad_ct = format!("{}A", &ct[..ct.len() - 2]);
        assert_eq!(Crypto::aes_decrypt(&key, &bad_ct, &nonce64).is_none(), true);
        // 非 Base64 / 错误密钥
        assert_eq!(Crypto::aes_decrypt(&key, "!!!", &nonce64).is_none(), true);
        assert_eq!(
            Crypto::aes_decrypt(&[0u8; 16], &ct, &nonce64).is_none(),
            true
        );
    }
    #[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);
    }
}