geekorm_core/utils/crypto/
mod.rs

1//! This module contains functions for generating random strings
2
3use std::fmt::Display;
4
5/// Random number generator
6#[cfg(feature = "rand")]
7pub mod rand;
8
9/// Hashing module
10#[cfg(feature = "hash")]
11pub mod hashing;
12
13#[cfg(feature = "hash")]
14use crate::utils::crypto::hashing::{generate_hash, verify_hash};
15
16/// Hashing algorithms
17#[derive(Default, Clone, Debug)]
18pub enum HashingAlgorithm {
19    /// PBKDF2 Hashing Algorithm
20    ///
21    /// This is the default hashing algorithm and is the most secure of all
22    /// supported algorithms.
23    #[default]
24    Pbkdf2,
25    /// Argon2 Hashing Algorithm
26    ///
27    /// Argon2id v19 + Salt
28    #[cfg(feature = "hash-argon2")]
29    Argon2,
30    /// SHA512 + Rounds (100k) Hashing Algorithm
31    ///
32    /// Weakest of all supported algorithms but fastest
33    #[cfg(feature = "hash-sha512")]
34    Sha512,
35}
36
37impl HashingAlgorithm {
38    /// Convert to string slice
39    pub fn to_str(&self) -> &str {
40        match self {
41            HashingAlgorithm::Pbkdf2 => "Pbkdf2",
42            #[cfg(feature = "hash-argon2")]
43            HashingAlgorithm::Argon2 => "Argon2",
44            #[cfg(feature = "hash-sha512")]
45            HashingAlgorithm::Sha512 => "Sha512",
46        }
47    }
48
49    /// Generate a hash using the selected algorithm
50    #[cfg(feature = "hash")]
51    pub fn generate_hash(&self, data: String) -> Result<String, crate::Error> {
52        generate_hash(data, self.clone())
53    }
54
55    /// Verify a hash using the selected algorithm
56    #[cfg(feature = "hash")]
57    pub fn verify_hash(&self, data: String, hash: String) -> Result<bool, crate::Error> {
58        verify_hash(data, hash, self.clone())
59    }
60}
61
62impl TryFrom<&str> for HashingAlgorithm {
63    type Error = crate::Error;
64
65    fn try_from(value: &str) -> Result<Self, Self::Error> {
66        match value.to_lowercase().as_str() {
67            "pbkdf2" => Ok(HashingAlgorithm::Pbkdf2),
68            #[cfg(feature = "hash-argon2")]
69            "argon2" => Ok(HashingAlgorithm::Argon2),
70            #[cfg(feature = "hash-sha512")]
71            "sha512" => Ok(HashingAlgorithm::Sha512),
72            _ => Err(crate::Error::HashingError(format!(
73                "Invalid hashing algorithm: {}",
74                value
75            ))),
76        }
77    }
78}
79
80impl TryFrom<&String> for HashingAlgorithm {
81    type Error = crate::Error;
82
83    fn try_from(value: &String) -> Result<Self, Self::Error> {
84        Self::try_from(value.as_str())
85    }
86}
87
88impl Display for HashingAlgorithm {
89    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
90        write!(f, "HashingAlgorithm({})", self.to_str())
91    }
92}