Fixed Cipher::decrypt and added tests for account encryption

This commit is contained in:
2024-01-27 12:45:40 +03:00
parent 9db3e8f7fe
commit 64e3210cc5
4 changed files with 202 additions and 163 deletions

@ -35,10 +35,12 @@ impl Cipher {
///
/// Returns an error if the tag doesn't match the ciphertext
#[inline]
#[allow(clippy::missing_panics_doc)]
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)?;
if value.len() <= 12 {
return Err(crate::Error::InvalidInputLength);
}
let nonce: [u8; 12] = value[value.len() - 12..].try_into().unwrap();
value.truncate(value.len() - 12);
self.chacha
@ -47,7 +49,7 @@ impl Cipher {
}
}
#[derive(serde::Serialize, serde::Deserialize)]
#[derive(serde::Serialize, serde::Deserialize, Clone, PartialEq, Eq, Debug)]
pub struct Decrypted {
pub name: String,
pub login: String,
@ -108,3 +110,54 @@ impl Decrypted {
.all(super::validate_field)
}
}
#[cfg(test)]
mod tests {
use super::*;
use once_cell::sync::Lazy;
const TESTING_MASTER_PASSWORD: &str = "VeryStr^n#M@$terP@$$!word";
static CIPHER: Lazy<Cipher> = Lazy::new(|| {
let mut salt = [0; 64];
OsRng.fill_bytes(&mut salt);
Cipher::new(TESTING_MASTER_PASSWORD.as_bytes(), &salt)
});
#[test]
fn cipher_test() -> crate::Result<()> {
const ORIGINAL: &[u8] = b"Data to protect";
let mut data = ORIGINAL.to_owned();
CIPHER.encrypt(&mut data);
CIPHER.decrypt(&mut data)?;
assert_eq!(ORIGINAL, data);
Ok(())
}
#[test]
fn account_encryption() -> crate::Result<()> {
let original = Decrypted {
name: "Account Name".into(),
login: "StrongLogin@mail.com".into(),
password: "StrongP@$$word!".into(),
};
let account = original.clone().into_account(1, TESTING_MASTER_PASSWORD);
let decrypted = Decrypted::from_account(account, TESTING_MASTER_PASSWORD)?;
assert_eq!(original, decrypted);
Ok(())
}
#[test]
fn decrypt_invalid_input_length() {
let mut bytes = vec![0];
assert!(matches!(
CIPHER.decrypt(&mut bytes),
Err(crate::Error::InvalidInputLength)
));
}
}