67 lines
1.7 KiB
Rust
67 lines
1.7 KiB
Rust
//! API-Keys erzeugen und hashen, Zufallswerte lesen.
|
|
//!
|
|
//! Keys sind 256 Bit lang und zufällig. Gespeichert wird nur der SHA-256-Hash
|
|
//! (bei so viel Zufall ist kein langsamer Passwort-Hash nötig).
|
|
|
|
use std::io::Read;
|
|
|
|
use sha2::{Digest, Sha256};
|
|
|
|
use crate::{Error, Result};
|
|
|
|
const KEY_PREFIX: &str = "nx-";
|
|
|
|
/// Liefert `bytes` Zufallsbytes als Hex-Text aus `/dev/urandom`.
|
|
pub fn random_hex(bytes: usize) -> Result<String> {
|
|
let mut buf = vec![0u8; bytes];
|
|
let path = "/dev/urandom";
|
|
std::fs::File::open(path)
|
|
.and_then(|mut f| f.read_exact(&mut buf))
|
|
.map_err(|source| Error::Io {
|
|
path: path.into(),
|
|
source,
|
|
})?;
|
|
Ok(hex(&buf))
|
|
}
|
|
|
|
/// Erzeugt einen neuen Key, zum Beispiel `nx-3f9a…` (3 + 64 Zeichen).
|
|
pub fn generate_api_key() -> Result<String> {
|
|
Ok(format!("{KEY_PREFIX}{}", random_hex(32)?))
|
|
}
|
|
|
|
/// SHA-256 des Keys als Hex-Text.
|
|
pub fn hash_api_key(key: &str) -> String {
|
|
hex(&Sha256::digest(key.as_bytes()))
|
|
}
|
|
|
|
fn hex(bytes: &[u8]) -> String {
|
|
bytes.iter().map(|b| format!("{b:02x}")).collect()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn key_hat_praefix_und_laenge_und_ist_jedes_mal_anders() {
|
|
let a = generate_api_key().unwrap();
|
|
let b = generate_api_key().unwrap();
|
|
assert!(a.starts_with("nx-"));
|
|
assert_eq!(a.len(), 3 + 64);
|
|
assert_ne!(a, b);
|
|
}
|
|
|
|
#[test]
|
|
fn hash_ist_bekannter_sha256_wert() {
|
|
assert_eq!(
|
|
hash_api_key("abc"),
|
|
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn zufallswert_hat_die_gewuenschte_laenge() {
|
|
assert_eq!(random_hex(8).unwrap().len(), 16);
|
|
}
|
|
}
|