bc_components/encrypted_key/
pbkdf2_params.rs

1use anyhow::Result;
2use bc_crypto::{hash::pbkdf2_hmac_sha512, pbkdf2_hmac_sha256};
3use dcbor::prelude::*;
4
5use super::{HashType, KeyDerivation, KeyDerivationMethod, SALT_LEN};
6use crate::{EncryptedMessage, Nonce, Salt, SymmetricKey};
7
8/// Struct representing PBKDF2 parameters.
9///
10/// CDDL:
11/// ```cddl
12/// PBKDF2Params = [1, Salt, iterations: uint, HashType]
13/// ```
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct PBKDF2Params {
16    salt: Salt,
17    iterations: u32,
18    hash_type: HashType,
19}
20
21impl PBKDF2Params {
22    pub fn new() -> Self {
23        Self::new_opt(
24            Salt::new_with_len(SALT_LEN).unwrap(),
25            100_000,
26            HashType::SHA256,
27        )
28    }
29
30    pub fn new_opt(salt: Salt, iterations: u32, hash_type: HashType) -> Self {
31        Self { salt, iterations, hash_type }
32    }
33
34    pub fn salt(&self) -> &Salt { &self.salt }
35
36    pub fn iterations(&self) -> u32 { self.iterations }
37
38    pub fn hash_type(&self) -> HashType { self.hash_type }
39}
40
41impl KeyDerivation for PBKDF2Params {
42    const INDEX: usize = KeyDerivationMethod::PBKDF2 as usize;
43
44    fn lock(
45        &mut self,
46        content_key: &SymmetricKey,
47        secret: impl AsRef<[u8]>,
48    ) -> Result<EncryptedMessage> {
49        let derived_key: SymmetricKey = (match self.hash_type {
50            HashType::SHA256 => {
51                pbkdf2_hmac_sha256(secret, &self.salt, self.iterations, 32)
52            }
53            HashType::SHA512 => {
54                pbkdf2_hmac_sha512(secret, &self.salt, self.iterations, 32)
55            }
56        })
57        .try_into()
58        .unwrap();
59        let encoded_method: Vec<u8> = self.to_cbor_data();
60        Ok(derived_key.encrypt(
61            content_key,
62            Some(encoded_method),
63            Option::<Nonce>::None,
64        ))
65    }
66
67    fn unlock(
68        &self,
69        encrypted_message: &EncryptedMessage,
70        secret: impl AsRef<[u8]>,
71    ) -> Result<SymmetricKey> {
72        let derived_key: SymmetricKey = (match self.hash_type {
73            HashType::SHA256 => {
74                pbkdf2_hmac_sha256(secret, &self.salt, self.iterations, 32)
75            }
76            HashType::SHA512 => {
77                pbkdf2_hmac_sha512(secret, &self.salt, self.iterations, 32)
78            }
79        })
80        .try_into()?;
81        derived_key.decrypt(encrypted_message)?.try_into()
82    }
83}
84
85impl std::fmt::Display for PBKDF2Params {
86    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
87        write!(f, "PBKDF2({})", self.hash_type)
88    }
89}
90
91impl Into<CBOR> for PBKDF2Params {
92    fn into(self) -> CBOR {
93        vec![
94            CBOR::from(Self::INDEX),
95            self.salt.into(),
96            self.iterations.into(),
97            self.hash_type.into(),
98        ]
99        .into()
100    }
101}
102
103impl TryFrom<CBOR> for PBKDF2Params {
104    type Error = dcbor::Error;
105
106    fn try_from(cbor: CBOR) -> dcbor::Result<Self> {
107        let a = cbor.try_into_array()?;
108        a.len()
109            .eq(&4)
110            .then_some(())
111            .ok_or_else(|| dcbor::Error::msg("Invalid PBKDF2Params"))?;
112        let mut iter = a.into_iter();
113        let _index: usize = iter
114            .next()
115            .ok_or_else(|| dcbor::Error::msg("Missing index"))?
116            .try_into()?;
117        let salt: Salt = iter
118            .next()
119            .ok_or_else(|| dcbor::Error::msg("Missing salt"))?
120            .try_into()?;
121        let iterations: u32 = iter
122            .next()
123            .ok_or_else(|| dcbor::Error::msg("Missing iterations"))?
124            .try_into()?;
125        let hash_type: HashType = iter
126            .next()
127            .ok_or_else(|| dcbor::Error::msg("Missing hash type"))?
128            .try_into()?;
129        Ok(Self { salt, iterations, hash_type })
130    }
131}