geekorm_core/utils/crypto/
mod.rs1use std::fmt::Display;
4
5#[cfg(feature = "rand")]
7pub mod rand;
8
9#[cfg(feature = "hash")]
11pub mod hashing;
12
13#[cfg(feature = "hash")]
14use crate::utils::crypto::hashing::{generate_hash, verify_hash};
15
16#[derive(Default, Clone, Debug)]
18pub enum HashingAlgorithm {
19 #[default]
24 Pbkdf2,
25 #[cfg(feature = "hash-argon2")]
29 Argon2,
30 #[cfg(feature = "hash-sha512")]
34 Sha512,
35}
36
37impl HashingAlgorithm {
38 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 #[cfg(feature = "hash")]
51 pub fn generate_hash(&self, data: String) -> Result<String, crate::Error> {
52 generate_hash(data, self.clone())
53 }
54
55 #[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}