45 lines
1.1 KiB
Rust
45 lines
1.1 KiB
Rust
use ring::{
|
|
digest,
|
|
rand::{SecureRandom, SystemRandom},
|
|
};
|
|
|
|
pub fn generate_secret() -> Result<String, ring::error::Unspecified> {
|
|
let mut bytes = [0; 32];
|
|
SystemRandom::new().fill(&mut bytes)?;
|
|
|
|
let mut secret = String::with_capacity(bytes.len() * 2);
|
|
for byte in bytes {
|
|
use std::fmt::Write;
|
|
write!(&mut secret, "{byte:02x}").expect("writing to a String cannot fail");
|
|
}
|
|
|
|
Ok(secret)
|
|
}
|
|
|
|
pub fn hash_secret(secret: &str) -> Vec<u8> {
|
|
digest::digest(&digest::SHA256, secret.as_bytes())
|
|
.as_ref()
|
|
.to_vec()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn generates_256_bit_hex_secrets() {
|
|
let first = generate_secret().unwrap();
|
|
let second = generate_secret().unwrap();
|
|
|
|
assert_eq!(first.len(), 64);
|
|
assert!(first.bytes().all(|byte| byte.is_ascii_hexdigit()));
|
|
assert_ne!(first, second);
|
|
}
|
|
|
|
#[test]
|
|
fn hashes_secrets_deterministically() {
|
|
assert_eq!(hash_secret("test-secret"), hash_secret("test-secret"));
|
|
assert_ne!(hash_secret("test-secret"), hash_secret("other-secret"));
|
|
}
|
|
}
|