Skip to main content

nibkeep_crypto/
passphrase.rs

1//! Keys derived from passphrases with Argon2id.
2
3use 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/// How much work deriving a key from a passphrase takes: the memory, iterations and lanes
17/// of Argon2id.
18///
19/// In CBOR, the parameters are the array `[1, memory, iterations, lanes]`, with the memory
20/// in KiB.
21#[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	/// RFC 9106's first recommendation, for devices with enough memory: 2 GiB, one
30	/// iteration and four lanes.
31	pub const RECOMMENDED: Self = Self {
32		memory_kib: 2 * 1024 * 1024,
33		iterations: 1,
34		lanes: 4,
35	};
36
37	/// RFC 9106's second recommendation, for devices with little memory: 64 MiB, three
38	/// iterations and four lanes.
39	pub const LOW_MEMORY: Self = Self {
40		memory_kib: 64 * 1024,
41		iterations: 3,
42		lanes: 4,
43	};
44
45	/// Returns the parameters, with the memory in KiB.
46	///
47	/// # Errors
48	///
49	/// Returns [`CryptoError::Passphrase`] unless there are 1 to 16 iterations and 1 to 16
50	/// lanes, and the memory is at least 8 KiB per lane, as Argon2 requires, and at most
51	/// 4 GiB. The upper limits keep a damaged or hostile record from making a device
52	/// allocate unlimited memory or work for ever.
53	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	/// The memory, in KiB.
73	#[must_use]
74	pub const fn memory_kib(self) -> u32 {
75		self.memory_kib
76	}
77
78	/// The number of iterations.
79	#[must_use]
80	pub const fn iterations(self) -> u32 {
81		self.iterations
82	}
83
84	/// The number of lanes.
85	#[must_use]
86	pub const fn lanes(self) -> u32 {
87		self.lanes
88	}
89}
90
91impl Key {
92	/// Derives a key from a passphrase with Argon2id, version 1.3. The passphrase is first
93	/// brought into Unicode Normalization Form C, so that it gives the same key however it
94	/// was typed. NibKeep uses 16 random bytes of salt.
95	///
96	/// # Errors
97	///
98	/// Returns [`CryptoError::Passphrase`] if the salt is shorter than 8 bytes, or if the
99	/// passphrase or the salt is longer than Argon2 allows, 4 GiB, and
100	/// [`CryptoError::OutOfMemory`] if the device cannot provide the memory that the
101	/// parameters ask for.
102	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		// Reserve enough room up front, so that no unwiped copy is left behind when the
113		// string grows. Normalization makes UTF-8 text at most three times longer.
114		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}