use aes_gcm::aead::{Aead, AeadInPlace, KeyInit, Payload};
use aes_gcm::{Aes256Gcm, Key, Nonce};
use argon2::{Algorithm, Argon2, Params, Version};
use zeroize::Zeroizing;
use crate::error::{MnemoError, Result};
pub const KEY_LEN: usize = 32;
pub const NONCE_LEN: usize = 12;
pub const TAG_LEN: usize = 16;
pub const SALT_LEN: usize = 16;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct KdfParams {
pub m_cost: u32,
pub t_cost: u32,
pub p_cost: u32,
}
impl KdfParams {
pub fn secure() -> Self {
Self {
m_cost: 19_456,
t_cost: 2,
p_cost: 1,
}
}
pub fn raw_key() -> Self {
Self {
m_cost: 8,
t_cost: 1,
p_cost: 1,
}
}
#[doc(hidden)]
pub fn fast() -> Self {
Self {
m_cost: 512,
t_cost: 1,
p_cost: 1,
}
}
}
impl Default for KdfParams {
fn default() -> Self {
Self::secure()
}
}
const PASSPHRASE_FLOOR_M_COST: u32 = 512;
impl KdfParams {
pub fn for_passphrase(self) -> Self {
let s = Self::secure();
Self {
m_cost: self.m_cost.max(s.m_cost),
t_cost: self.t_cost.max(s.t_cost),
p_cost: self.p_cost.max(s.p_cost),
}
}
pub fn below_passphrase_floor(&self) -> bool {
self.m_cost < PASSPHRASE_FLOOR_M_COST
}
pub fn is_test_grade(&self) -> bool {
!self.below_passphrase_floor() && self.m_cost < Self::secure().m_cost
}
}
pub(crate) type SaltHook<'a> = dyn FnMut(&[u8; SALT_LEN]) -> Result<()> + 'a;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SecretKind {
Passphrase,
Key,
}
pub(crate) fn check_kdf_for(kind: SecretKind, kdf: KdfParams) -> Result<()> {
if kind == SecretKind::Passphrase && kdf.below_passphrase_floor() {
return Err(MnemoError::Invalid(format!(
"these KDF parameters ({} KiB, {} pass) are for a raw 256-bit key, not a \
passphrase; use create_with_key or rekey_with_key for a key, or \
KdfParams::secure() for a passphrase",
kdf.m_cost, kdf.t_cost
)));
}
Ok(())
}
pub fn derive_kek(
passphrase: &[u8],
salt: &[u8],
params: KdfParams,
) -> Result<Zeroizing<[u8; KEY_LEN]>> {
let p = Params::new(params.m_cost, params.t_cost, params.p_cost, Some(KEY_LEN))
.map_err(|e| MnemoError::Kdf(e.to_string()))?;
let argon = Argon2::new(Algorithm::Argon2id, Version::V0x13, p);
let mut key = Zeroizing::new([0u8; KEY_LEN]);
argon
.hash_password_into(passphrase, salt, &mut key[..])
.map_err(|e| MnemoError::Kdf(e.to_string()))?;
Ok(key)
}
fn cipher(key: &[u8; KEY_LEN]) -> Aes256Gcm {
Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key))
}
pub(crate) fn page_cipher(key: &[u8; KEY_LEN]) -> Aes256Gcm {
cipher(key)
}
pub(crate) fn aead_decrypt_in_place(
cipher: &Aes256Gcm,
nonce: &[u8; NONCE_LEN],
aad: &[u8],
buf: &mut [u8],
tag: &[u8],
) -> Result<()> {
cipher
.decrypt_in_place_detached(
Nonce::from_slice(nonce),
aad,
buf,
aes_gcm::Tag::from_slice(tag),
)
.map_err(|_| MnemoError::Crypto("authentication failed".into()))
}
pub fn aead_encrypt(
key: &[u8; KEY_LEN],
nonce: &[u8; NONCE_LEN],
plaintext: &[u8],
aad: &[u8],
) -> Result<Vec<u8>> {
cipher(key)
.encrypt(
Nonce::from_slice(nonce),
Payload {
msg: plaintext,
aad,
},
)
.map_err(|e| MnemoError::Crypto(e.to_string()))
}
pub fn aead_decrypt(
key: &[u8; KEY_LEN],
nonce: &[u8; NONCE_LEN],
ciphertext: &[u8],
aad: &[u8],
) -> Result<Vec<u8>> {
cipher(key)
.decrypt(
Nonce::from_slice(nonce),
Payload {
msg: ciphertext,
aad,
},
)
.map_err(|_| MnemoError::Crypto("authentication failed".into()))
}
pub fn random_dek() -> Zeroizing<[u8; KEY_LEN]> {
use rand::RngCore;
let mut dek = Zeroizing::new([0u8; KEY_LEN]);
rand::thread_rng().fill_bytes(&mut dek[..]);
dek
}
pub fn random_salt() -> [u8; SALT_LEN] {
use rand::RngCore;
let mut salt = [0u8; SALT_LEN];
rand::thread_rng().fill_bytes(&mut salt);
salt
}
pub fn random_nonce() -> [u8; NONCE_LEN] {
use rand::RngCore;
let mut n = [0u8; NONCE_LEN];
rand::thread_rng().fill_bytes(&mut n);
n
}
pub fn random_u64() -> u64 {
use rand::RngCore;
rand::thread_rng().next_u64()
}
pub fn session_page_nonce(session_random: u64, session_counter: u32) -> [u8; NONCE_LEN] {
let mut n = [0u8; NONCE_LEN];
n[0..8].copy_from_slice(&session_random.to_le_bytes());
n[8..12].copy_from_slice(&session_counter.to_le_bytes());
n
}
pub fn wrap_dek(
kek: &[u8; KEY_LEN],
nonce: &[u8; NONCE_LEN],
dek: &[u8; KEY_LEN],
) -> Result<Vec<u8>> {
aead_encrypt(kek, nonce, dek, &[])
}
pub fn unwrap_dek(
kek: &[u8; KEY_LEN],
nonce: &[u8; NONCE_LEN],
wrapped: &[u8],
) -> Result<Zeroizing<[u8; KEY_LEN]>> {
let plain = cipher(kek)
.decrypt(
Nonce::from_slice(nonce),
Payload {
msg: wrapped,
aad: &[],
},
)
.map_err(|_| MnemoError::WrongPassphrase)?;
if plain.len() != KEY_LEN {
return Err(MnemoError::WrongPassphrase);
}
let mut dek = Zeroizing::new([0u8; KEY_LEN]);
dek.copy_from_slice(&plain);
Ok(dek)
}