#[cfg(test)]
mod tests;
use std::ffi::{CString, NulError, CStr};
pub mod encryptions;
pub use encryptions::Encryptions;
pub mod raw;
pub struct Crypt {
pub encrypted: String,
salt: Option<CString>
}
impl Crypt {
pub fn new() -> Self {
Crypt {
encrypted: String::new(),
salt: None
}
}
pub fn set_salt(&mut self, salt: String) -> Result<(), NulError> {
self.salt = Some(CString::new(salt)?);
Ok(())
}
pub fn gen_salt(&mut self, encryption: Encryptions) -> Result<(), String> {
let decoded = encryption.decode();
self.salt = Some(unsafe {
let enc = match CString::new(decoded) {
Ok(o) => o,
Err(e) => return Err(format!("Failed to create C string: {e}"))
};
CString::from(
CStr::from_ptr(raw::crypt_gensalt(enc.as_ptr(), 15, std::ptr::null(), 0))
)
});
Ok(())
}
pub fn encrypt(&mut self, encrypt: String) -> Result<(), String> {
if let None = self.salt {
return Err("Salt hasn't been set".to_string());
}
let enc = match CString::new(encrypt) {
Ok(o) => o,
Err(e) => return Err(format!("Failed to allocate C string: {e}"))
};
let ptr = unsafe {
raw::crypt(enc.clone().as_ptr(), self.salt.clone().unwrap().as_ptr())
};
self.encrypted = unsafe {
match CStr::from_ptr(ptr).to_str() {
Err(e) => return Err(format!("Failed to encode C string: {e}")),
Ok(o) => o.to_string(),
}
};
Ok(())
}
pub fn get_salt(&self) -> Result<String, String> {
match self.salt.clone().unwrap().to_str() {
Err(e) => return Err(format!("Failed to encode C string: {e}")),
Ok(o) => Ok(o.to_string())
}
}
}