bc_components/encrypted_key/
key_derivation_method.rs

1use anyhow::{Error, Result};
2use dcbor::prelude::*;
3
4/// Enum representing the supported key derivation methods.
5///
6/// CDDL:
7/// ```cddl
8/// KeyDerivationMethod = HKDF / PBKDF2 / Scrypt / Argon2id
9/// HKDF = 0
10/// PBKDF2 = 1
11/// Scrypt = 2
12/// Argon2id = 3
13/// ```
14#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
15pub enum KeyDerivationMethod {
16    HKDF     = 0,
17    PBKDF2   = 1,
18    Scrypt   = 2,
19    Argon2id = 3,
20    SSHAgent = 4,
21}
22
23impl KeyDerivationMethod {
24    /// Returns the zero-based index of the key derivation method.
25    pub fn index(&self) -> usize { *self as usize }
26
27    /// Attempts to create a `KeyDerivationMethod` from a zero-based index.
28    pub fn from_index(index: usize) -> Option<Self> {
29        match index {
30            0 => Some(KeyDerivationMethod::HKDF),
31            1 => Some(KeyDerivationMethod::PBKDF2),
32            2 => Some(KeyDerivationMethod::Scrypt),
33            3 => Some(KeyDerivationMethod::Argon2id),
34            4 => Some(KeyDerivationMethod::SSHAgent),
35            _ => None,
36        }
37    }
38}
39
40impl std::fmt::Display for KeyDerivationMethod {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        match self {
43            KeyDerivationMethod::HKDF => write!(f, "HKDF"),
44            KeyDerivationMethod::PBKDF2 => write!(f, "PBKDF2"),
45            KeyDerivationMethod::Scrypt => write!(f, "Scrypt"),
46            KeyDerivationMethod::Argon2id => write!(f, "Argon2id"),
47            KeyDerivationMethod::SSHAgent => write!(f, "SSHAgent"),
48        }
49    }
50}
51
52impl TryFrom<&CBOR> for KeyDerivationMethod {
53    type Error = Error;
54
55    fn try_from(cbor: &CBOR) -> Result<Self> {
56        let i: usize = cbor.clone().try_into()?;
57        KeyDerivationMethod::from_index(i)
58            .ok_or_else(|| Error::msg("Invalid KeyDerivationMethod"))
59    }
60}