pub mod base64;
pub mod vigenere;
pub mod xor;
pub use base64::Base64;
pub use vigenere::Vigenere;
pub use xor::Xor;
use crate::prelude::*;
use std::default::Default;
use std::sync::Arc;
use async_trait::async_trait;
pub static ALPHABET: [char; 26] = [
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
't', 'u', 'v', 'w', 'x', 'y', 'z',
];
#[derive(Default, Clone, Debug)]
pub struct NoUnique;
#[derive(Clone, Debug)]
pub struct Unique(Arc<str>);
#[derive(Default, Clone, Debug)]
pub struct NoVariable;
#[derive(Clone, Debug)]
pub struct Variable(Arc<str>);
#[derive(Clone, Default, Debug)]
pub struct PasswordBuilder<U, V> {
unique: U,
variable: V,
repeat: Option<u8>,
}
#[async_trait]
pub trait Method: std::fmt::Debug {
async fn encrypt(&self, uw: Arc<str>, vw: Arc<str>) -> Result<String>;
}
impl PasswordBuilder<NoUnique, NoVariable> {
pub fn new() -> Self {
Default::default()
}
}
impl<U, V> PasswordBuilder<U, V> {
pub fn unique(self, word: impl Into<String>) -> PasswordBuilder<Unique, V> {
PasswordBuilder {
unique: Unique(Arc::from(word.into())),
variable: self.variable,
repeat: self.repeat,
}
}
pub fn variable(self, word: impl Into<String>) -> PasswordBuilder<U, Variable> {
PasswordBuilder {
unique: self.unique,
variable: Variable(Arc::from(word.into())),
repeat: self.repeat,
}
}
}
impl PasswordBuilder<Unique, Variable> {
pub fn repeat(self, number: impl Into<u8>) -> Self {
PasswordBuilder {
repeat: Some(number.into()),
..self
}
}
pub async fn method<T: Method + Default + PartialEq + Clone>(self, method: T) -> Result<Self> {
let vw = self.variable.0.clone();
let mut repeat = self.repeat.unwrap_or(1);
if repeat == 0 {
repeat = 1_u8;
}
let mut pass = self.unique.0.clone();
for _ in 0..repeat {
let new_pass = method.encrypt(pass, vw.clone()).await?;
pass = Arc::from(new_pass);
}
Ok(PasswordBuilder {
unique: Unique(pass),
repeat: None,
..self
})
}
pub async fn method_ptr(self, method: Arc<dyn Method + Sync + Send>) -> Result<Self> {
let vw = self.variable.0.clone();
let mut repeat = self.repeat.unwrap_or(1);
if repeat == 0 {
repeat = 1_u8;
}
let mut pass = self.unique.0.clone();
for _ in 0..repeat {
let new_pass = method.encrypt(pass, vw.clone()).await?;
pass = Arc::from(new_pass);
}
Ok(PasswordBuilder {
unique: Unique(pass),
repeat: None,
..self
})
}
pub fn build(self) -> String {
self.unique.0.to_string()
}
}