feat(verify):增加生成指定位数的验证码功能。

This commit is contained in:
徐涛 2023-06-29 15:56:36 +08:00
parent a0f189d1f4
commit 418fc4dccf
2 changed files with 20 additions and 1 deletions

View File

@ -23,7 +23,7 @@ Rust 中可以使用的常用辅助功能工具箱。主要配备以下功能:
- 签名算法 - 签名算法
- [ ] RSA 签名算法 - [ ] RSA 签名算法
- 验证码生成器 - 验证码生成器
- [ ] 随机验证码生成算法 - [x] 随机验证码生成算法
- 序列化算法 - 序列化算法
- [x] Base64 算法 - [x] Base64 算法
- [x] Hex 直转 - [x] Hex 直转

View File

@ -0,0 +1,19 @@
use rand::{seq::SliceRandom, thread_rng};
const RAND_STR_SRC: &str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
/// 生成一个指定长度的随机验证码。
///
/// - `n`:要生成的验证码长度。
pub fn random_verify_code(n: usize) -> Box<String> {
let choices = RAND_STR_SRC.as_bytes();
let mut rng = thread_rng();
let mut code: Vec<String> = vec![];
while code.len() < n {
match choices.choose(&mut rng) {
Some(c) => code.push(String::from_utf8(vec![*c]).unwrap()),
None => continue,
}
}
Box::from(code.join(""))
}