63 lines
1.8 KiB
Rust
63 lines
1.8 KiB
Rust
use argon2::{Algorithm, Argon2, ParamsBuilder, Result as Argon2Result, Version};
|
|
|
|
// tests take forever with production parameters, so we turn them down in dev
|
|
#[cfg(not(debug_assertions))]
|
|
const MEM_COST: u32 = 128 * 1024;
|
|
#[cfg(not(debug_assertions))]
|
|
const TIME_COST: u32 = 8;
|
|
#[cfg(not(debug_assertions))]
|
|
const PARALLELISM_COST: u32 = 4;
|
|
|
|
#[cfg(debug_assertions)]
|
|
const MEM_COST: u32 = 48 * 1024;
|
|
#[cfg(debug_assertions)]
|
|
const TIME_COST: u32 = 1;
|
|
#[cfg(debug_assertions)]
|
|
const PARALLELISM_COST: u32 = 1;
|
|
|
|
#[derive(Clone, Debug)]
|
|
pub enum AppSession {
|
|
Empty,
|
|
Locked,
|
|
Unlocked { key: [u8; 32] },
|
|
}
|
|
|
|
impl AppSession {
|
|
pub fn new(passphrase: &str, salt: &[u8]) -> Argon2Result<Self> {
|
|
let params = ParamsBuilder::new()
|
|
.m_cost(MEM_COST)
|
|
.t_cost(TIME_COST)
|
|
.p_cost(PARALLELISM_COST)
|
|
.build()
|
|
.unwrap(); // only errors if the given params are invalid
|
|
|
|
let hasher = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
|
|
|
|
let mut key = [0; 32]; // todo: replace this with a `zeroize` or `secrecy` type
|
|
hasher.hash_password_into(passphrase.as_bytes(), &salt, &mut key)?;
|
|
Ok(Self::Unlocked { key })
|
|
}
|
|
|
|
pub fn salt() -> Result<[u8; 32], getrandom::Error> {
|
|
let mut salt = [0; 32];
|
|
getrandom::fill(&mut salt)?;
|
|
Ok(salt)
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn test_new() {
|
|
let passphrase = "correct horse battery staple";
|
|
let salt = AppSession::salt().expect("salt generation failed.");
|
|
let session = AppSession::new(passphrase, &salt).expect("password KDF failed.");
|
|
match session {
|
|
AppSession::Unlocked { .. } => (),
|
|
_ => panic!("AppSession::new() should return an unlocked session"),
|
|
}
|
|
}
|
|
}
|