From d818e52d45ad5fd6a799b786a7f2cef740fc6f07 Mon Sep 17 00:00:00 2001 From: Hardcore Sushi Date: Thu, 8 Jul 2021 19:12:30 +0200 Subject: [PATCH] Add authentication integration test --- src/crypto.rs | 2 +- tests/authentication.rs | 51 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 tests/authentication.rs diff --git a/src/crypto.rs b/src/crypto.rs index fba4c35..d517797 100644 --- a/src/crypto.rs +++ b/src/crypto.rs @@ -60,7 +60,7 @@ pub struct EncryptionParams { } impl EncryptionParams { - fn get_params_len(&self) -> usize { + pub fn get_params_len(&self) -> usize { SALT_LEN + 4*2 + 2 + self.cipher.get_nonce_size() } diff --git a/tests/authentication.rs b/tests/authentication.rs new file mode 100644 index 0000000..1f52e6c --- /dev/null +++ b/tests/authentication.rs @@ -0,0 +1,51 @@ +use rand::Rng; +use doby::{ + crypto::{ + ArgonParams, + CipherAlgorithm, + EncryptionParams, + DobyCipher, + }, + encrypt, + decrypt, +}; + +fn different_elements(v1: &Vec, v2: &Vec) -> usize { + assert_eq!(v1.len(), v2.len()); + v1.into_iter().enumerate().filter(|x| v2[x.0] != *x.1).count() +} + +#[test] +fn authentication() { + const BLOCK_SIZE: usize = 65536; + const PLAINTEXT: &[u8; 13] = b"the plaintext"; + const PASSWORD: &str = "the password"; + let params = EncryptionParams::new(ArgonParams { + t_cost: 1, + m_cost: 8, + parallelism: 1, + }, CipherAlgorithm::AesCtr); + + let encrypter = DobyCipher::new(PASSWORD.into(), ¶ms).unwrap(); + let mut ciphertext = Vec::with_capacity(PLAINTEXT.len()+158); + encrypt(&mut &PLAINTEXT[..], &mut ciphertext, ¶ms, encrypter, BLOCK_SIZE, None).unwrap(); + assert_eq!(ciphertext.len(), PLAINTEXT.len()+158); + + for i in 0..ciphertext.len() { + let mut compromised = ciphertext.clone(); + while compromised[i] == ciphertext[i] { + compromised[i] = rand::thread_rng().gen(); + } + assert_eq!(different_elements(&compromised, &ciphertext), 1); + let decrypter = DobyCipher::new(PASSWORD.into(), ¶ms).unwrap(); + let mut decrypted = Vec::with_capacity(PLAINTEXT.len()); + let verified = decrypt(&mut &compromised[..], &mut decrypted, decrypter, BLOCK_SIZE).unwrap(); + assert_eq!(verified, false); + } + + let decrypter = DobyCipher::new(PASSWORD.into(), ¶ms).unwrap(); + let mut decrypted = Vec::with_capacity(PLAINTEXT.len()); + let verified = decrypt(&mut &ciphertext[4+params.get_params_len()..], &mut decrypted, decrypter, BLOCK_SIZE).unwrap(); + assert_eq!(decrypted, PLAINTEXT); + assert_eq!(verified, true); +} \ No newline at end of file