use std::fmt;
use std::str::FromStr;
use crate::Error;
const ALPHABET: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
pub const MIN_SECRET_BYTES: usize = 16;
pub const MIN_STORED_SECRET_BYTES: usize = 10;
#[derive(Clone, PartialEq, Eq)]
pub struct Secret {
bytes: Vec<u8>,
}
impl Secret {
pub fn generate(bytes: usize) -> Result<Self, Error> {
if bytes < MIN_SECRET_BYTES {
return Err(Error::SecretTooShort);
}
let mut key = vec![0; bytes];
getrandom::fill(&mut key).map_err(|_| Error::Random)?;
Ok(Self { bytes: key })
}
pub fn from_bytes(bytes: impl Into<Vec<u8>>) -> Result<Self, Error> {
let bytes = bytes.into();
if bytes.len() < MIN_STORED_SECRET_BYTES {
return Err(Error::SecretTooShort);
}
Ok(Self { bytes })
}
#[must_use]
pub fn to_base32(&self) -> String {
let mut encoded = String::with_capacity(self.bytes.len().div_ceil(5) * 8);
let mut buffer: u16 = 0;
let mut bits = 0;
for &byte in &self.bytes {
buffer = (buffer << 8) | u16::from(byte);
bits += 8;
while bits >= 5 {
bits -= 5;
encoded.push(char::from(ALPHABET[usize::from((buffer >> bits) & 31)]));
}
}
if bits > 0 {
encoded.push(char::from(ALPHABET[usize::from((buffer << (5 - bits)) & 31)]));
}
encoded
}
#[must_use]
pub fn as_bytes(&self) -> &[u8] {
&self.bytes
}
}
impl FromStr for Secret {
type Err = Error;
fn from_str(base32: &str) -> Result<Self, Error> {
let mut bytes = Vec::with_capacity(base32.len() * 5 / 8);
let mut buffer: u16 = 0;
let mut bits = 0;
let text = base32.trim_end_matches(['=', ' ']);
for character in text.bytes() {
if matches!(character, b' ' | b'-') {
continue;
}
let value = ALPHABET
.iter()
.position(|&letter| letter == character.to_ascii_uppercase())
.ok_or(Error::InvalidSecret)?;
buffer = (buffer << 5) | u16::try_from(value).expect("an index below 32");
bits += 5;
if bits >= 8 {
bits -= 8;
bytes.push(u8::try_from((buffer >> bits) & 0xff).expect("a byte"));
}
}
if bits >= 5 || buffer & ((1 << bits) - 1) != 0 {
return Err(Error::InvalidSecret);
}
Self::from_bytes(bytes)
}
}
impl fmt::Debug for Secret {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Secret(..)")
}
}