//! # Cryptographic utilities //! //! Author: Pierre Hubert extern crate sha1; use crate::data::error::{ResultBoxError, ExecError}; use rand::{thread_rng, Rng}; use rand::distributions::Alphanumeric; /// Generate a new sha1 string /// /// ``` /// use comunic_server::utils::crypt_utils::sha1_str; /// /// let res = sha1_str("secret"); /// assert_eq!(res, "e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4"); /// ``` pub fn sha1_str(input: &str) -> String { sha1::Sha1::from(input).digest().to_string() } /// One-way user password crypt /// /// This method will have to be replaced by a stronger algorithm once this implementation is /// completely built. /// /// It currently depends on PHP /// /// ``` /// use comunic_server::utils::crypt_utils::crypt_pass; /// /// let res = crypt_pass("secret").unwrap(); /// assert_eq!(res, "e5GUe5kdeUMGs"); /// ``` pub fn crypt_pass(pass: &str) -> ResultBoxError { let hash = sha1_str(pass); let result = std::process::Command::new("/usr/bin/php") .arg("-r") .arg(format!("echo crypt('{}', '{}');", hash, hash)) .output()?; if !result.status.success() { return Err(ExecError::boxed_new("Failed to crypt password!")); } Ok(String::from_utf8(result.stdout)?) } /// Generate a random string of a given size /// /// ``` /// use comunic_server::utils::crypt_utils::rand_str; /// /// let size = 10; /// let rand = rand_str(size); /// assert_eq!(size, rand.len()); /// ``` pub fn rand_str(len: usize) -> String { thread_rng() .sample_iter(&Alphanumeric) .take(len) .collect() }