pass_manager/cryptography/src/account.rs

89 lines
2.8 KiB
Rust
Raw Normal View History

use chacha20poly1305::{aead::Aead, AeadCore, ChaCha20Poly1305, KeyInit};
use entity::account;
use pbkdf2::pbkdf2_hmac_array;
use rand::{rngs::OsRng, RngCore};
use sea_orm::ActiveValue::Set;
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-08-03 21:23:02 +00:00
pub fn new(password: &[u8], salt: &[u8]) -> Self {
let key = pbkdf2_hmac_array::<Sha256, 32>(password, salt, 480000);
Self {
chacha: ChaCha20Poly1305::new(&key.into()),
}
}
/// Encrypts the value with the current cipher. The 12 byte nonce is appended to the result
#[inline]
pub fn encrypt(&self, value: &[u8]) -> crate::Result<Vec<u8>> {
let nonce = ChaCha20Poly1305::generate_nonce(&mut OsRng);
let mut result = self.chacha.encrypt(&nonce, value)?;
result.extend(nonce);
Ok(result)
}
/// Decrypts the value with the current cipher. The 12 byte nonce is expected to be at the end of the value
#[inline]
2023-08-03 21:23:02 +00:00
pub fn decrypt(&self, value: &[u8]) -> crate::Result<Vec<u8>> {
let (data, nonce) = value.split_at(value.len() - 12);
self.chacha.decrypt(nonce.into(), data).map_err(Into::into)
}
}
pub trait AccountFromUnencryptedExt {
fn from_unencrypted(
user_id: u64,
name: String,
login: &str,
password: &str,
master_pass: &str,
) -> crate::Result<account::ActiveModel>;
}
impl AccountFromUnencryptedExt for account::ActiveModel {
/// Encryptes the provided data by the master password and creates the ActiveModel with all fields set to Set variant
#[inline]
fn from_unencrypted(
user_id: u64,
name: String,
login: &str,
password: &str,
master_pass: &str,
) -> crate::Result<Self> {
let mut salt = vec![0; 64];
OsRng.fill_bytes(&mut salt);
let cipher = Cipher::new(master_pass.as_bytes(), &salt);
let enc_login = Set(cipher.encrypt(login.as_bytes())?);
let enc_password = Set(cipher.encrypt(password.as_bytes())?);
Ok(Self {
name: Set(name),
user_id: Set(user_id),
salt: Set(salt),
enc_login,
enc_password,
})
}
}
pub trait DecryptAccountExt {
fn decrypt(&self, master_pass: &str) -> crate::Result<(String, String)>;
}
impl DecryptAccountExt for account::Model {
/// Returns the decrypted login and password of the account
#[inline]
fn decrypt(&self, master_pass: &str) -> crate::Result<(String, String)> {
let cipher = Cipher::new(master_pass.as_bytes(), &self.salt);
let login = String::from_utf8(cipher.decrypt(&self.enc_login)?)?;
let password = String::from_utf8(cipher.decrypt(&self.enc_password)?)?;
Ok((login, password))
}
}