nibkeep_crypto/
passphrase.rs1use argon2::{Algorithm, Argon2, Params, Version};
4use nibkeep_base::cbor::{self, FromCbor, ToCbor, Value};
5use unicode_normalization::UnicodeNormalization;
6use zeroize::Zeroizing;
7
8use crate::format;
9use crate::{CryptoError, Key};
10
11const MIN_SALT_LEN: usize = 8;
12const MAX_MEMORY_KIB: u32 = 4 * 1024 * 1024;
13const MAX_ITERATIONS: u32 = 16;
14const MAX_LANES: u32 = 16;
15
16#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
22pub struct PassphraseParams {
23 memory_kib: u32,
24 iterations: u32,
25 lanes: u32,
26}
27
28impl PassphraseParams {
29 pub const RECOMMENDED: Self = Self {
32 memory_kib: 2 * 1024 * 1024,
33 iterations: 1,
34 lanes: 4,
35 };
36
37 pub const LOW_MEMORY: Self = Self {
40 memory_kib: 64 * 1024,
41 iterations: 3,
42 lanes: 4,
43 };
44
45 pub fn new(memory_kib: u32, iterations: u32, lanes: u32) -> Result<Self, CryptoError> {
54 if !(1..=MAX_ITERATIONS).contains(&iterations) {
55 return Err(CryptoError::Passphrase("there must be 1 to 16 iterations"));
56 }
57 if !(1..=MAX_LANES).contains(&lanes) {
58 return Err(CryptoError::Passphrase("there must be 1 to 16 lanes"));
59 }
60 if memory_kib < 8 * lanes || memory_kib > MAX_MEMORY_KIB {
61 return Err(CryptoError::Passphrase(
62 "the memory must be at least 8 KiB per lane and at most 4 GiB",
63 ));
64 }
65 Ok(Self {
66 memory_kib,
67 iterations,
68 lanes,
69 })
70 }
71
72 #[must_use]
74 pub const fn memory_kib(self) -> u32 {
75 self.memory_kib
76 }
77
78 #[must_use]
80 pub const fn iterations(self) -> u32 {
81 self.iterations
82 }
83
84 #[must_use]
86 pub const fn lanes(self) -> u32 {
87 self.lanes
88 }
89}
90
91impl Key {
92 pub fn from_passphrase(
103 passphrase: &str,
104 salt: &[u8],
105 params: &PassphraseParams,
106 ) -> Result<Self, CryptoError> {
107 if salt.len() < MIN_SALT_LEN {
108 return Err(CryptoError::Passphrase(
109 "the salt must have at least 8 bytes",
110 ));
111 }
112 let capacity = passphrase
115 .len()
116 .checked_mul(3)
117 .ok_or(CryptoError::Passphrase("the passphrase is too long"))?;
118 let mut normalized = Zeroizing::new(String::with_capacity(capacity));
119 normalized.extend(passphrase.nfc());
120 let params = Params::new(params.memory_kib, params.iterations, params.lanes, Some(32))
121 .map_err(|_| CryptoError::Passphrase("the parameters are not valid"))?;
122 let argon2 = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
123 Self::fill_with(|bytes| {
124 argon2
125 .hash_password_into(normalized.as_bytes(), salt, bytes)
126 .map_err(|error| match error {
127 argon2::Error::OutOfMemory => CryptoError::OutOfMemory,
128 _ => CryptoError::Passphrase("the passphrase or the salt is too long"),
129 })
130 })
131 }
132}
133
134impl ToCbor for PassphraseParams {
135 fn to_cbor(&self) -> Value {
136 format::write([
137 self.memory_kib.to_cbor(),
138 self.iterations.to_cbor(),
139 self.lanes.to_cbor(),
140 ])
141 }
142}
143
144impl FromCbor for PassphraseParams {
145 fn from_cbor(value: &Value) -> Result<Self, cbor::Error> {
146 const EXPECTED: &str = "passphrase parameters: [1, memory, iterations, lanes]";
147 let error = || cbor::Error::Expected(EXPECTED);
148 let [memory, iterations, lanes] = format::read(value, EXPECTED)?;
149 let number = |item: &Value| u32::from_cbor(item).map_err(|_| error());
150 Self::new(number(memory)?, number(iterations)?, number(lanes)?).map_err(|_| error())
151 }
152}