Skip to main content

argon2/
algorithm.rs

1//! Argon2 algorithms (e.g. Argon2d, Argon2i, Argon2id).
2
3use crate::{Error, Result};
4use core::{
5    fmt::{self, Display},
6    str::FromStr,
7};
8
9#[cfg(feature = "password-hash")]
10use password_hash::phc::Ident;
11
12/// Argon2d algorithm identifier
13#[cfg(feature = "password-hash")]
14pub const ARGON2D_IDENT: Ident = Ident::new_unwrap("argon2d");
15
16/// Argon2i algorithm identifier
17#[cfg(feature = "password-hash")]
18pub const ARGON2I_IDENT: Ident = Ident::new_unwrap("argon2i");
19
20/// Argon2id algorithm identifier
21#[cfg(feature = "password-hash")]
22pub const ARGON2ID_IDENT: Ident = Ident::new_unwrap("argon2id");
23
24/// Argon2 primitive type: variants of the algorithm.
25#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Default, Ord)]
26pub enum Algorithm {
27    /// Optimizes against GPU cracking attacks but vulnerable to side-channels.
28    ///
29    /// Accesses the memory array in a password dependent order, reducing the
30    /// possibility of time–memory tradeoff (TMTO) attacks.
31    Argon2d = 0,
32
33    /// Optimized to resist side-channel attacks.
34    ///
35    /// Accesses the memory array in a password independent order, increasing the
36    /// possibility of time-memory tradeoff (TMTO) attacks.
37    Argon2i = 1,
38
39    /// Hybrid that mixes Argon2i and Argon2d passes (*default*).
40    ///
41    /// Uses the Argon2i approach for the first half pass over memory and
42    /// Argon2d approach for subsequent passes. This effectively places it in
43    /// the "middle" between the other two: it doesn't provide as good
44    /// TMTO/GPU cracking resistance as Argon2d, nor as good of side-channel
45    /// resistance as Argon2i, but overall provides the most well-rounded
46    /// approach to both classes of attacks.
47    #[default]
48    Argon2id = 2,
49}
50
51impl Algorithm {
52    /// Parse an [`Algorithm`] from the provided string.
53    ///
54    /// # Errors
55    /// Returns [`Error::AlgorithmInvalid`] if `id` is not a valid Argon2 algorithm identifier.
56    pub fn new(id: impl AsRef<str>) -> Result<Self> {
57        id.as_ref().parse()
58    }
59
60    /// Get the identifier string for this PBKDF2 [`Algorithm`].
61    #[must_use]
62    pub const fn as_str(&self) -> &'static str {
63        match self {
64            Algorithm::Argon2d => "argon2d",
65            Algorithm::Argon2i => "argon2i",
66            Algorithm::Argon2id => "argon2id",
67        }
68    }
69
70    /// Get the [`Ident`] that corresponds to this Argon2 [`Algorithm`].
71    #[cfg(feature = "password-hash")]
72    #[must_use]
73    pub const fn ident(&self) -> Ident {
74        match self {
75            Algorithm::Argon2d => ARGON2D_IDENT,
76            Algorithm::Argon2i => ARGON2I_IDENT,
77            Algorithm::Argon2id => ARGON2ID_IDENT,
78        }
79    }
80
81    /// Serialize primitive type as little endian bytes
82    pub(crate) const fn to_le_bytes(self) -> [u8; 4] {
83        (self as u32).to_le_bytes()
84    }
85}
86
87impl AsRef<str> for Algorithm {
88    fn as_ref(&self) -> &str {
89        self.as_str()
90    }
91}
92
93impl Display for Algorithm {
94    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95        f.write_str(self.as_str())
96    }
97}
98
99impl FromStr for Algorithm {
100    type Err = Error;
101
102    fn from_str(name: &str) -> Result<Algorithm> {
103        match name {
104            "argon2d" => Ok(Algorithm::Argon2d),
105            "argon2i" => Ok(Algorithm::Argon2i),
106            "argon2id" => Ok(Algorithm::Argon2id),
107            _ => Err(Error::AlgorithmInvalid),
108        }
109    }
110}
111
112#[cfg(feature = "password-hash")]
113impl From<Algorithm> for Ident {
114    fn from(alg: Algorithm) -> Ident {
115        alg.ident()
116    }
117}
118
119#[cfg(feature = "password-hash")]
120impl TryFrom<&str> for Algorithm {
121    type Error = password_hash::Error;
122
123    fn try_from(name: &str) -> password_hash::Result<Algorithm> {
124        name.parse().map_err(|_| password_hash::Error::Algorithm)
125    }
126}