bc_components/encrypted_key/
key_derivation_method.rs

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