pass_manager/cryptography/src/account.rs

111 lines
3.3 KiB
Rust
Raw Normal View History

use chacha20poly1305::{AeadCore, AeadInPlace, ChaCha20Poly1305, KeyInit};
2023-11-25 16:29:06 +00:00
use entity::account::Account;
use pbkdf2::pbkdf2_hmac_array;
use rand::{rngs::OsRng, RngCore};
use sha2::Sha256;
2023-08-03 21:23:02 +00:00
pub struct Cipher {
chacha: ChaCha20Poly1305,
}
impl Cipher {
/// Creates a new cipher from a master password and the salt
#[inline]
2023-11-19 11:45:46 +00:00
#[must_use]
2023-08-03 21:23:02 +00:00
pub fn new(password: &[u8], salt: &[u8]) -> Self {
2023-11-19 11:45:46 +00:00
let key = pbkdf2_hmac_array::<Sha256, 32>(password, salt, 480_000);
Self {
chacha: ChaCha20Poly1305::new(&key.into()),
}
}
/// Encrypts the value with the current cipher. The 12 byte nonce is appended to the result
#[inline]
#[allow(clippy::missing_panics_doc)]
pub fn encrypt(&self, value: &mut Vec<u8>) {
let nonce = ChaCha20Poly1305::generate_nonce(&mut OsRng);
self.chacha.encrypt_in_place(&nonce, b"", value).unwrap();
value.extend_from_slice(&nonce);
}
/// Decrypts the value with the current cipher. The 12 byte nonce is expected to be at the end of the value
///
/// # Errors
///
/// Returns an error if the tag doesn't match the ciphertext
#[inline]
pub fn decrypt(&self, value: &mut Vec<u8>) -> crate::Result<()> {
let nonce: [u8; 12] = value[value.len() - 12..]
.try_into()
.map_err(|_| crate::Error::InvalidInputLength)?;
value.truncate(value.len() - 12);
2023-11-19 11:45:46 +00:00
self.chacha
.decrypt_in_place(nonce.as_slice().into(), b"", value)
.map_err(Into::into)
}
}
#[derive(serde::Serialize, serde::Deserialize)]
pub struct Decrypted {
pub name: String,
pub login: String,
pub password: String,
}
impl Decrypted {
/// Constructs `DecryptedAccount` by decrypting the provided account
///
/// # Errors
///
/// Returns an error if the tag doesn't match the ciphertext or if the decrypted data isn't valid UTF-8
#[inline]
2023-11-25 16:29:06 +00:00
pub fn from_account(mut account: Account, master_pass: &str) -> crate::Result<Self> {
let cipher = Cipher::new(master_pass.as_bytes(), &account.salt);
cipher.decrypt(&mut account.enc_login)?;
cipher.decrypt(&mut account.enc_password)?;
Ok(Self {
name: account.name,
login: String::from_utf8(account.enc_login)?,
password: String::from_utf8(account.enc_password)?,
})
}
/// Constructs `ActiveModel` with eath field Set by encrypting `self`
#[inline]
#[must_use]
2023-11-25 16:29:06 +00:00
pub fn into_account(self, user_id: u64, master_pass: &str) -> Account {
let mut enc_login = self.login.into_bytes();
let mut enc_password = self.password.into_bytes();
let mut salt = vec![0; 64];
OsRng.fill_bytes(&mut salt);
let cipher = Cipher::new(master_pass.as_bytes(), &salt);
2023-11-25 16:29:06 +00:00
cipher.encrypt(&mut enc_login);
cipher.encrypt(&mut enc_password);
2023-11-25 16:29:06 +00:00
Account {
user_id,
name: self.name,
salt,
enc_login,
enc_password,
}
}
/// Returns true if the account's fields are valid
#[inline]
#[must_use]
pub fn validate(&self) -> bool {
[
self.name.as_str(),
self.login.as_str(),
self.password.as_str(),
]
.into_iter()
.all(super::validate_field)
}
}