49 lines
1.2 KiB
Rust
49 lines
1.2 KiB
Rust
use crate::error::Error;
|
|
use crate::hash::{hash, Hash};
|
|
use nanoid::nanoid;
|
|
use nanoid_dictionary::{ALPHANUMERIC, NUMBERS};
|
|
use std::fmt::{Display, Formatter};
|
|
|
|
// Struct to generate the secret
|
|
pub struct SecretString(String);
|
|
impl SecretString {
|
|
pub fn new(length: usize) -> Self {
|
|
Self(nanoid!(length, ALPHANUMERIC))
|
|
}
|
|
pub fn new_digits(length: usize) -> Self {
|
|
Self(nanoid!(length, NUMBERS))
|
|
}
|
|
}
|
|
impl Default for SecretString {
|
|
fn default() -> Self {
|
|
Self::new(64)
|
|
}
|
|
}
|
|
impl AsRef<str> for SecretString {
|
|
fn as_ref(&self) -> &str {
|
|
self.0.as_ref()
|
|
}
|
|
}
|
|
impl Display for SecretString {
|
|
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
|
write!(f, "{}", self.0)
|
|
}
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
pub struct Secret(Hash);
|
|
|
|
impl Secret {
|
|
pub fn new(plain: SecretString) -> Result<Self, Error> {
|
|
Ok(Self(Hash::from_hash(hash(&plain.0)?)))
|
|
}
|
|
pub fn from_hash(hash: impl Into<String>) -> Self {
|
|
Self(Hash::from_hash(hash))
|
|
}
|
|
pub fn hash(&self) -> &str {
|
|
self.0.hash()
|
|
}
|
|
pub fn compare(&self, plain: &str) -> Result<bool, Error> {
|
|
self.0.compare(plain).map_err(Error::from)
|
|
}
|
|
}
|