Selaa lähdekoodia

Started writting tests to validate/learn openssl.

Matthew Carr 2 vuotta sitten
vanhempi
commit
586862d1be
1 muutettua tiedostoa jossa 38 lisäystä ja 0 poistoa
  1. 38 0
      crates/node/src/crypto.rs

+ 38 - 0
crates/node/src/crypto.rs

@@ -1,6 +1,9 @@
 /// Functions for performing cryptographic operations on the main data structures.
 
 use super::*;
+use openssl::{
+    symm::{Cipher, Crypter, Mode}
+};
 
 /// Errors that can occur during cryptographic operations.
 pub(crate) enum Error {
@@ -69,4 +72,39 @@ fn decrypt_in_place(_ciphertext: &mut [u8], _key: &Key) -> Result<()> {
 
 #[cfg(test)]
 mod tests {
+    use super::*;
+
+    static KEY: [u8; 32] = [
+        0xB2, 0xB3, 0xDA, 0x5A, 0x1A, 0xF6, 0xB3, 0x78, 0x30, 0xAB, 0x1D, 0x33, 0x33, 0xE7, 0xE3,
+        0x5B, 0xBB, 0xF9, 0xFE, 0xD0, 0xC1, 0xF7, 0x90, 0x34, 0x69, 0xB7, 0xE7, 0xC6, 0x1C, 0x46,
+        0x85, 0x48,
+    ];
+
+    #[test]
+    fn cryptor() {
+        let expected = b"We attack at the crack of noon.";
+
+        let cipher = Cipher::aes_256_cbc();
+        let mut encrypter = Crypter::new(
+            cipher,
+            Mode::Encrypt,
+            &KEY,
+            Some(&KEY)).unwrap();
+        let mut ciphertext = vec![0; expected.len() + cipher.block_size()];
+        let mut written = encrypter.update(expected.as_slice(), &mut ciphertext).unwrap();
+        written += encrypter.finalize(&mut ciphertext[written..]).unwrap();
+        ciphertext.truncate(written);
+
+        let mut actual = vec![0u8; expected.len() + cipher.block_size()];
+        let mut decrypter = Crypter::new(
+            cipher,
+            Mode::Decrypt,
+            &KEY,
+            Some(&KEY)).unwrap();
+        let mut written = decrypter.update(&ciphertext, &mut actual).unwrap();
+        written += decrypter.finalize(&mut actual[written..]).unwrap();
+        actual.truncate(written);
+
+        assert_eq!(expected, actual.as_slice());
+    }
 }