doby/src/crypto.rs

181 lines
6.0 KiB
Rust
Raw Normal View History

2021-06-27 20:35:23 +02:00
use std::{convert::TryFrom, io::{self, Read, Write}};
use num_enum::TryFromPrimitive;
use chacha20::XChaCha20;
2021-06-25 23:01:50 +02:00
use aes::{Aes256Ctr, cipher::{NewCipher, StreamCipher}};
use hmac::{Hmac, Mac, NewMac};
use rand::{Rng, rngs::OsRng};
use argon2::{Argon2, Version, Algorithm};
use hkdf::Hkdf;
use zeroize::Zeroize;
const SALT_LEN: usize = 64;
2021-06-27 20:35:23 +02:00
const AES_NONCE_LEN: usize = 16;
const XCHACHA20_NONCE_LEN: usize = 24;
2021-06-25 23:01:50 +02:00
const HASH_LEN: usize = 32;
const KEY_LEN: usize = HASH_LEN;
pub struct ArgonParams {
pub t_cost: u32,
pub m_cost: u32,
pub parallelism: u8,
}
2021-06-27 20:35:23 +02:00
#[derive(Clone, Copy, Debug, TryFromPrimitive)]
#[repr(u8)]
pub enum CipherAlgorithm {
AesCtr = 0,
XChaCha20 = 1,
}
impl CipherAlgorithm {
fn get_nonce_size(&self) -> usize {
match self {
CipherAlgorithm::AesCtr => AES_NONCE_LEN,
CipherAlgorithm::XChaCha20 => XCHACHA20_NONCE_LEN,
}
}
}
2021-06-25 23:01:50 +02:00
pub struct EncryptionParams {
password_salt: [u8; SALT_LEN],
argon2: ArgonParams,
hkdf_salt: [u8; SALT_LEN],
2021-06-27 20:35:23 +02:00
nonce: Vec<u8>,
cipher: CipherAlgorithm,
2021-06-25 23:01:50 +02:00
}
impl EncryptionParams {
2021-06-27 20:35:23 +02:00
fn get_params_len(&self) -> usize {
SALT_LEN*2 + 4*2 + 1 + self.cipher.get_nonce_size()
}
2021-06-25 23:01:50 +02:00
2021-06-27 20:35:23 +02:00
pub fn new(argon2_params: ArgonParams, cipher: CipherAlgorithm) -> EncryptionParams {
2021-06-25 23:01:50 +02:00
let mut password_salt = [0; SALT_LEN];
OsRng.fill(&mut password_salt);
let mut hkdf_salt = [0; SALT_LEN];
OsRng.fill(&mut hkdf_salt);
2021-06-27 20:35:23 +02:00
let mut nonce = vec![0; cipher.get_nonce_size()];
OsRng.fill(&mut nonce[..]);
2021-06-25 23:01:50 +02:00
EncryptionParams {
password_salt,
argon2: argon2_params,
hkdf_salt,
nonce,
2021-06-27 20:35:23 +02:00
cipher,
2021-06-25 23:01:50 +02:00
}
}
pub fn write<W: Write>(&self, writer: &mut W) -> io::Result<()> {
writer.write_all(&self.password_salt)?;
writer.write_all(&self.argon2.t_cost.to_be_bytes())?;
writer.write_all(&self.argon2.m_cost.to_be_bytes())?;
writer.write_all(&self.argon2.parallelism.to_be_bytes())?;
writer.write_all(&self.hkdf_salt)?;
2021-06-27 20:35:23 +02:00
writer.write_all(&(self.cipher as u8).to_be_bytes())?;
2021-06-25 23:01:50 +02:00
writer.write_all(&self.nonce)?;
Ok(())
}
2021-06-27 20:35:23 +02:00
pub fn read<R: Read>(reader: &mut R) -> io::Result<Option<Self>> {
2021-06-25 23:01:50 +02:00
let mut password_salt = [0; SALT_LEN];
reader.read_exact(&mut password_salt)?;
2021-06-27 20:35:23 +02:00
let mut t_cost = [0; 4];
reader.read_exact(&mut t_cost)?;
let mut m_cost = [0; 4];
reader.read_exact(&mut m_cost)?;
let mut parallelism = [0; 1];
reader.read_exact(&mut parallelism)?;
2021-06-25 23:01:50 +02:00
let mut hkdf_salt = [0; SALT_LEN];
reader.read_exact(&mut hkdf_salt)?;
2021-06-27 20:35:23 +02:00
let mut cipher_buff = [0; 1];
reader.read_exact(&mut cipher_buff)?;
match CipherAlgorithm::try_from(cipher_buff[0]) {
Ok(cipher) => {
let mut nonce = vec![0; cipher.get_nonce_size()];
reader.read_exact(&mut nonce)?;
let argon2_params = ArgonParams {
t_cost: u32::from_be_bytes(t_cost),
m_cost: u32::from_be_bytes(m_cost),
parallelism: u8::from_be_bytes(parallelism),
};
Ok(Some(EncryptionParams {
password_salt,
argon2: argon2_params,
hkdf_salt,
nonce,
cipher,
}))
}
Err(_) => Ok(None)
}
2021-06-25 23:01:50 +02:00
}
}
2021-06-27 20:35:23 +02:00
pub struct DobyCipher {
cipher: Box<dyn StreamCipher>,
2021-06-25 23:01:50 +02:00
hmac: Hmac<blake3::Hasher>,
buffer: Vec<u8>,
}
2021-06-27 20:35:23 +02:00
impl DobyCipher {
2021-06-25 23:01:50 +02:00
pub fn new(password: &[u8], params: &EncryptionParams) -> Result<Self, argon2::Error> {
let argon = Argon2::new(None, params.argon2.t_cost, params.argon2.m_cost, params.argon2.parallelism.into(), Version::V0x13)?;
let mut master_key = [0; KEY_LEN];
argon.hash_password_into(Algorithm::Argon2id, password, &params.password_salt, &[], &mut master_key)?;
let hkdf = Hkdf::<blake3::Hasher>::new(Some(&params.hkdf_salt), &master_key);
let mut encryption_key = [0; KEY_LEN];
hkdf.expand(b"doby_encryption_key", &mut encryption_key).unwrap();
let mut authentication_key = [0; KEY_LEN];
hkdf.expand(b"doby_authentication_key", &mut authentication_key).unwrap();
master_key.zeroize();
2021-06-27 20:35:23 +02:00
let mut encoded_params = Vec::with_capacity(params.get_params_len());
2021-06-25 23:01:50 +02:00
params.write(&mut encoded_params).unwrap();
let mut hmac = Hmac::new_from_slice(&authentication_key).unwrap();
hmac.update(&encoded_params);
2021-06-27 20:35:23 +02:00
Ok(Self {
cipher: match params.cipher {
CipherAlgorithm::AesCtr => Box::new(Aes256Ctr::new_from_slices(&encryption_key, &params.nonce).unwrap()),
CipherAlgorithm::XChaCha20 => Box::new(XChaCha20::new_from_slices(&encryption_key, &params.nonce).unwrap()),
},
2021-06-25 23:01:50 +02:00
hmac,
buffer: Vec::new(),
})
}
pub fn encrypt_chunk<W: Write>(&mut self, buff: &mut [u8], writer: &mut W) -> io::Result<()> {
self.cipher.apply_keystream(buff);
self.hmac.update(buff);
writer.write_all(buff)
}
pub fn write_hmac<W: Write>(self, writer: &mut W) -> io::Result<usize> {
let tag = self.hmac.finalize().into_bytes();
writer.write(&tag)
}
pub fn decrypt_chunk<R: Read>(&mut self, reader: &mut R, buff: &mut [u8]) -> io::Result<usize> {
let buffer_len = self.buffer.len();
buff[..buffer_len].clone_from_slice(&self.buffer);
let read = reader.read(&mut buff[buffer_len..])?;
let n = if buffer_len + read >= HASH_LEN {
2021-06-27 20:35:23 +02:00
self.buffer.clear();
2021-06-25 23:01:50 +02:00
buffer_len + read - HASH_LEN
} else {
0
};
self.buffer.extend_from_slice(&buff[n..buffer_len+read]);
self.hmac.update(&buff[..n]);
self.cipher.apply_keystream(&mut buff[..n]);
Ok(n)
}
pub fn verify_hmac(self) -> bool {
self.hmac.verify(&self.buffer).is_ok()
}
}