[core] Vault and generators: Argon2id key slot + XChaCha20-Poly1305 file, atomic save, item templates, memorable/nickname/random/PIN/strict generators
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
//! The only module that calls the cryptographic crates.
|
||||
|
||||
use crate::{Error, KdfParams};
|
||||
use argon2::{Algorithm, Argon2, Params, Version};
|
||||
use chacha20poly1305::aead::{Aead, KeyInit, Payload};
|
||||
use chacha20poly1305::{XChaCha20Poly1305, XNonce};
|
||||
use rand::Rng;
|
||||
use rand::rand_core::UnwrapErr;
|
||||
use rand::rngs::SysRng;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
pub const KEY_LEN: usize = 32;
|
||||
pub const NONCE_LEN: usize = 24;
|
||||
pub const TAG_LEN: usize = 16;
|
||||
|
||||
/// Fills `buf` from the OS CSPRNG. Panics only if the OS has no randomness to give, where going on
|
||||
/// without it would be worse.
|
||||
pub fn fill_random(buf: &mut [u8]) {
|
||||
UnwrapErr(SysRng).fill_bytes(buf);
|
||||
}
|
||||
|
||||
pub fn random_key() -> Zeroizing<[u8; KEY_LEN]> {
|
||||
let mut k = Zeroizing::new([0u8; KEY_LEN]);
|
||||
fill_random(k.as_mut());
|
||||
k
|
||||
}
|
||||
|
||||
pub fn random_nonce() -> [u8; NONCE_LEN] {
|
||||
let mut n = [0u8; NONCE_LEN];
|
||||
fill_random(&mut n);
|
||||
n
|
||||
}
|
||||
|
||||
/// Argon2id(password, salt) → key-encryption key. The caller has already checked `p` against the limits.
|
||||
pub fn derive_kek(password: &[u8], salt: &[u8], p: KdfParams) -> Result<Zeroizing<[u8; KEY_LEN]>, Error> {
|
||||
let params = Params::new(p.m_cost_kib, p.t_cost, p.p_cost, Some(KEY_LEN)).map_err(|_| Error::UnsupportedKdf)?;
|
||||
let mut kek = Zeroizing::new([0u8; KEY_LEN]);
|
||||
Argon2::new(Algorithm::Argon2id, Version::V0x13, params)
|
||||
.hash_password_into(password, salt, kek.as_mut())
|
||||
.map_err(|_| Error::UnsupportedKdf)?;
|
||||
Ok(kek)
|
||||
}
|
||||
|
||||
fn cipher(key: &[u8; KEY_LEN]) -> XChaCha20Poly1305 {
|
||||
XChaCha20Poly1305::new_from_slice(key).expect("32-byte key")
|
||||
}
|
||||
|
||||
fn nonce(n: &[u8; NONCE_LEN]) -> XNonce {
|
||||
XNonce::try_from(&n[..]).expect("24-byte nonce")
|
||||
}
|
||||
|
||||
pub fn seal(key: &[u8; KEY_LEN], n: &[u8; NONCE_LEN], plaintext: &[u8], aad: &[u8]) -> Vec<u8> {
|
||||
cipher(key)
|
||||
.encrypt(&nonce(n), Payload { msg: plaintext, aad })
|
||||
.expect("encryption cannot fail for in-memory buffers")
|
||||
}
|
||||
|
||||
/// `None` when the tag does not verify: wrong key, or changed ciphertext, nonce or AAD.
|
||||
pub fn open(key: &[u8; KEY_LEN], n: &[u8; NONCE_LEN], ciphertext: &[u8], aad: &[u8]) -> Option<Zeroizing<Vec<u8>>> {
|
||||
cipher(key).decrypt(&nonce(n), Payload { msg: ciphertext, aad }).ok().map(Zeroizing::new)
|
||||
}
|
||||
Reference in New Issue
Block a user