Updated account.rs to improve readability
This commit is contained in:
parent
0b92bcd9f3
commit
4d153d8c44
@ -32,6 +32,7 @@ struct Cipher {
|
||||
}
|
||||
|
||||
impl Cipher {
|
||||
/// Creates a new cipher from a master password and the salt
|
||||
fn new(password: &[u8], salt: &[u8]) -> Self {
|
||||
let key = pbkdf2_hmac_array::<Sha256, 32>(password, salt, 480000);
|
||||
|
||||
@ -40,6 +41,7 @@ impl Cipher {
|
||||
}
|
||||
}
|
||||
|
||||
/// Encrypts the value with the current cipher. The 12 byte nonce is appended to the result
|
||||
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)?;
|
||||
@ -47,15 +49,15 @@ impl Cipher {
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Decrypts the value with the current cipher. The 12 byte nonce is expected to be at the end of the value
|
||||
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(|err| err.into())
|
||||
self.chacha.decrypt(nonce.into(), data).map_err(Into::into)
|
||||
}
|
||||
}
|
||||
|
||||
impl ActiveModel {
|
||||
/// Encryptes the provided data by the master password and creates the ActiveModel with all fields set to Set variant
|
||||
pub fn from_unencrypted(
|
||||
user_id: u64,
|
||||
name: String,
|
||||
@ -65,9 +67,9 @@ impl ActiveModel {
|
||||
) -> crate::Result<Self> {
|
||||
let mut salt = vec![0; 64];
|
||||
OsRng.fill_bytes(&mut salt);
|
||||
let cipher = Cipher::new(master_pass.as_ref(), &salt);
|
||||
let enc_login = Set(cipher.encrypt(login.as_ref())?);
|
||||
let enc_password = Set(cipher.encrypt(password.as_ref())?);
|
||||
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),
|
||||
@ -79,10 +81,11 @@ impl ActiveModel {
|
||||
}
|
||||
|
||||
impl Model {
|
||||
/// Returns the decrypted login and password of the account
|
||||
pub fn decrypt(&self, master_pass: &str) -> crate::Result<(String, String)> {
|
||||
let cipher = Cipher::new(master_pass.as_ref(), self.salt.as_ref());
|
||||
let login = String::from_utf8(cipher.decrypt(self.enc_login.as_ref())?)?;
|
||||
let password = String::from_utf8(cipher.decrypt(self.enc_password.as_ref())?)?;
|
||||
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))
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user