43 lines
886 B
Rust
43 lines
886 B
Rust
|
use rand::RngCore;
|
||
|
use sha2::{Sha256, Digest};
|
||
|
|
||
|
pub struct CodeGenerator {
|
||
|
counter: u64,
|
||
|
salt: [u8; 32],
|
||
|
}
|
||
|
|
||
|
impl CodeGenerator {
|
||
|
pub fn generate(&mut self) -> String {
|
||
|
let count = self.counter;
|
||
|
self.counter += 1;
|
||
|
|
||
|
let mut hasher = Sha256::new();
|
||
|
hasher.update(self.salt);
|
||
|
hasher.update(count.to_be_bytes());
|
||
|
|
||
|
format!("{:x}", hasher.finalize())[..6].to_string()
|
||
|
}
|
||
|
}
|
||
|
|
||
|
impl Default for CodeGenerator {
|
||
|
fn default() -> Self {
|
||
|
let mut salt = [0; 32];
|
||
|
rand::thread_rng().fill_bytes(&mut salt);
|
||
|
|
||
|
CodeGenerator {
|
||
|
counter: 0,
|
||
|
salt,
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
#[cfg(test)]
|
||
|
mod test {
|
||
|
use super::*;
|
||
|
#[test]
|
||
|
fn test_generate() {
|
||
|
let code = CodeGenerator::default().generate();
|
||
|
assert_eq!(code.len(), 6);
|
||
|
}
|
||
|
}
|