diff --git a/vault/src/key/symmetric.rs b/vault/src/key/symmetric.rs index 1caff50..00aaa96 100644 --- a/vault/src/key/symmetric.rs +++ b/vault/src/key/symmetric.rs @@ -8,6 +8,7 @@ use chacha20poly1305::{ChaCha20Poly1305, KeyInit, Nonce, aead::Aead}; use crate::error::CryptoError; +#[derive(Debug, PartialEq, Eq)] pub struct SymmetricKey([u8; 32]); /// Size of a nonce in ChaCha20Poly1305. @@ -102,3 +103,49 @@ impl SymmetricKey { Self(key) } } + +#[cfg(test)] +mod tests { + + /// Using the same password derives the same key + #[test] + fn same_password_derives_same_key() { + const EXPECTED_KEY: [u8; 32] = [ + 4, 179, 233, 202, 225, 70, 211, 200, 7, 73, 115, 1, 85, 149, 90, 42, 160, 68, 16, 106, + 136, 19, 197, 195, 153, 145, 179, 21, 37, 13, 37, 90, + ]; + const PASSWORD: &str = "test123"; + + let key = super::SymmetricKey::derive_from_password(PASSWORD); + + assert_eq!(key.0, EXPECTED_KEY); + } + + /// Make sure an encrypted value with some key can be decrypted with the same key + #[test] + fn can_decrypt() { + let key = super::SymmetricKey::new(); + + let message = b"this is a message to decrypt"; + + let enc = key.encrypt(message).expect("Can encrypt message"); + let dec = key.decrypt(&enc).expect("Can decrypt message"); + + assert_eq!(message.as_slice(), dec.as_slice()); + } + + /// Make sure a value encrypted with one key can't be decrypted with a different key. Since we + /// use AEAD encryption we will notice this when trying to decrypt + #[test] + fn different_key_cant_decrypt() { + let key1 = super::SymmetricKey::new(); + let key2 = super::SymmetricKey::new(); + + let message = b"this is a message to decrypt"; + + let enc = key1.encrypt(message).expect("Can encrypt message"); + let dec = key2.decrypt(&enc); + + assert!(dec.is_err()); + } +}