diff --git a/src/entity/account.rs b/src/entity/account.rs index eff0f81..fa1b9dc 100644 --- a/src/entity/account.rs +++ b/src/entity/account.rs @@ -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::(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> { 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> { 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 { 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)) } }