doby/tests/authentication.rs

50 lines
1.8 KiB
Rust
Raw Normal View History

2021-07-08 19:12:30 +02:00
use rand::Rng;
use doby::{
crypto::{
CipherAlgorithm,
EncryptionParams,
DobyCipher,
},
encrypt,
decrypt,
};
fn different_elements<T: Eq>(v1: &Vec<T>, v2: &Vec<T>) -> 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";
2021-11-13 19:08:28 +01:00
const CIPHERTEXT_SIZE: usize = PLAINTEXT.len()+145;
2021-07-08 19:12:30 +02:00
const PASSWORD: &str = "the password";
2021-11-13 19:08:28 +01:00
let params = EncryptionParams::new(
argon2::Params::new(8, 1, 1, None).unwrap(),
CipherAlgorithm::AesCtr
);
2021-07-08 19:12:30 +02:00
2021-11-13 19:08:28 +01:00
let encrypter = DobyCipher::new(PASSWORD.as_bytes(), &params);
2021-08-30 16:06:55 +02:00
let mut ciphertext = Vec::with_capacity(CIPHERTEXT_SIZE);
2021-07-08 19:12:30 +02:00
encrypt(&mut &PLAINTEXT[..], &mut ciphertext, &params, encrypter, BLOCK_SIZE, None).unwrap();
2021-08-30 16:06:55 +02:00
assert_eq!(ciphertext.len(), CIPHERTEXT_SIZE);
2021-07-08 19:12:30 +02:00
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);
2021-11-13 19:08:28 +01:00
let decrypter = DobyCipher::new(PASSWORD.as_bytes(), &params);
2021-07-08 19:12:30 +02:00
let mut decrypted = Vec::with_capacity(PLAINTEXT.len());
let verified = decrypt(&mut &compromised[..], &mut decrypted, decrypter, BLOCK_SIZE).unwrap();
assert_eq!(verified, false);
}
2021-11-13 19:08:28 +01:00
let decrypter = DobyCipher::new(PASSWORD.as_bytes(), &params);
2021-07-08 19:12:30 +02:00
let mut decrypted = Vec::with_capacity(PLAINTEXT.len());
2021-08-31 13:06:45 +02:00
let verified = decrypt(&mut &ciphertext[4+EncryptionParams::LEN..], &mut decrypted, decrypter, BLOCK_SIZE).unwrap();
2021-07-08 19:12:30 +02:00
assert_eq!(decrypted, PLAINTEXT);
assert_eq!(verified, true);
}