Browse Source

Started writing encryption/decryption tests.

Matthew Carr 2 years ago
parent
commit
7a5eef2813
3 changed files with 126 additions and 75 deletions
  1. 56 24
      crates/node/src/crypto.rs
  2. 6 6
      crates/node/src/main.rs
  3. 64 45
      crates/node/src/serde_tests.rs

+ 56 - 24
crates/node/src/crypto.rs

@@ -11,7 +11,7 @@ use serde_block_tree::{self, to_vec, from_vec};
 use serde::de::{DeserializeOwned};
 
 /// Data that may or may not be encrypted.
-#[derive(Debug, PartialEq, Serialize, Deserialize)]
+#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
 pub enum Cryptotext<T: Serialize> {
     /// The inner value of `T` is plaintext.
     Plain(T),
@@ -44,7 +44,7 @@ impl From<serde_block_tree::Error> for Error {
 pub type Result<T> = std::result::Result<T, Error>;
 
 /// A cryptographic hash.
-#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Hashable)]
+#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Hashable, Clone)]
 pub enum Hash {
     Sha2_256([u8; 32]),
     #[serde(with = "BigArray")]
@@ -52,18 +52,15 @@ pub enum Hash {
 }
 
 /// A cryptographic signature.
-#[derive(Debug, PartialEq, Serialize, Deserialize)]
+#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
 pub enum Signature {
     #[serde(with = "BigArray")]
     Ed25519([u8; 64]),
 }
 
 /// A cryptographic key.
-#[derive(Debug, PartialEq, Serialize, Deserialize)]
+#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
 pub enum Key {
-    // For keys that contain IVs, the key always comes first. The function `key_len` can be used
-    // to get the length of the key part of a variant's array.
-
     /// A key for the AES 256 cipher in Cipher Block Chaining mode. Note that this includes the
     /// initialization vector, so that a value of this variant contains all the information needed
     /// to fully initialize a cipher context.
@@ -72,7 +69,10 @@ pub enum Key {
         iv: [u8; 16],
     },
     /// A key for the AES 256 cipher in counter mode.
-    Aes256Ctr([u8; 32]),
+    Aes256Ctr {
+        key: [u8; 32],
+        iv: [u8; 16]
+    },
     Ed25519 {
         public: [u8; 32],
         private: Option<[u8; 32]>
@@ -85,7 +85,7 @@ impl Key {
     fn key_slice(&self) -> Option<&[u8]> {
         match self {
             Key::Aes256Cbc { key, .. } => Some(key),
-            Key::Aes256Ctr(key) => Some(key),
+            Key::Aes256Ctr { key, .. } => Some(key),
             Key::Ed25519 { private, .. } => match private {
                 Some(key) => Some(key.as_slice()),
                 None => None,
@@ -139,10 +139,10 @@ impl<'a> TryFrom<&'a Key> for EncryptionAlgo<'a> {
                 key: key_slice,
                 iv: Some(iv),
             }),
-            Key::Aes256Ctr(key_slice) => Ok(EncryptionAlgo::Symmetric {
+            Key::Aes256Ctr { key: key_slice, iv } => Ok(EncryptionAlgo::Symmetric {
                 cipher: Cipher::aes_256_ctr(),
                 key: key_slice,
-                iv: None
+                iv: Some(iv),
             }),
             Key::Ed25519 { public, .. } => {
                 let pkey = PKey::public_key_from_der(public.as_slice())
@@ -190,10 +190,10 @@ impl<'a> TryFrom<&'a Key> for DecryptionAlgo<'a> {
                 key: key_slice,
                 iv: Some(iv),
             }),
-            Key::Aes256Ctr(key_slice) => Ok(DecryptionAlgo::Symmetric {
+            Key::Aes256Ctr { key: key_slice, iv } => Ok(DecryptionAlgo::Symmetric {
                 cipher: Cipher::aes_256_ctr(),
                 key: key_slice,
-                iv: None
+                iv: Some(iv),
             }),
             Key::Ed25519 { private, .. } => {
                 let private = private.ok_or(Error::MissingPrivateKey)?;
@@ -266,17 +266,14 @@ fn decrypt_slice(ciphertext: &[u8], key: &Key) -> Result<Vec<u8>> {
 #[cfg(test)]
 mod tests {
     use super::*;
-
-    const 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,
-    ];
-
-    const IV: [u8; 16] = [
-        0x60, 0xE0, 0xBE, 0x45, 0xA9, 0xAB, 0x5D, 0x99, 0x3B, 0x3A, 0x1E, 0x54, 0x18, 0xE0, 0x46,
-        0xDE,
-    ];
+    use super::serde_tests::{
+        make_principal,
+        make_block,
+        KEY,
+        BLOCK_KEY,
+        IV,
+        BLOCK_IV,
+    };
 
     #[test]
     fn key_aes256cbc_key_slice_is_correct() -> Result<()> {
@@ -293,6 +290,41 @@ mod tests {
         assert_eq!(IV, iv_part);
     }
 
+    fn encrypt_decrypt_block_test_case(
+        mut actual: VersionedBlock, principal: &Principal, key: &Key
+    ) -> Result<()> {
+        let expected = actual.clone();
+        actual = encrypt_block(actual, principal, key)?;
+        actual = decrypt_block(actual, principal, key)?;
+        assert_eq!(expected, actual);
+        Ok(())
+    }
+
+    fn make_versioned_block(principal: Principal, block_key: Key) -> Result<VersionedBlock> {
+        let mut block = make_block()?;
+        block.read_caps.clear();
+        block.read_caps.insert(principal, Cryptotext::Plain(block_key));
+        Ok(VersionedBlock::V0(block))
+    }
+
+    #[test]
+    fn encrypt_decrypt_block_aes256cbc() -> Result<()> {
+        let principal = make_principal();
+        let block_key = Key::Aes256Cbc { key: BLOCK_KEY, iv: BLOCK_IV };
+        let block = make_versioned_block(principal.clone(), block_key)?;
+        let key = Key::Aes256Cbc { key: KEY, iv: IV };
+        encrypt_decrypt_block_test_case(block, &principal, &key)
+    }
+
+    #[test]
+    fn encrypt_decrypt_block_aes256ctr() -> Result<()> {
+        let principal = make_principal();
+        let block_key = Key::Aes256Ctr { key: BLOCK_KEY, iv: BLOCK_IV };
+        let block = make_versioned_block(principal.clone(), block_key)?;
+        let key = Key::Aes256Ctr { key: KEY, iv: IV };
+        encrypt_decrypt_block_test_case(block, &principal, &key)
+    }
+
     /// Tests that validate the dependencies of this module.
     mod dependency_tests {
         /// This test validates that data decrypted with the `Crypter` API matches data that was

+ 6 - 6
crates/node/src/main.rs

@@ -18,14 +18,14 @@ mod crypto;
 use crypto::{Hash, Signature, Key, Cryptotext};
 
 /// A Block tagged with its version number.
-#[derive(Debug, PartialEq, Serialize, Deserialize)]
+#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
 enum VersionedBlock {
     V0(Block)
 }
 
 /// A container which binds together ciphertext along with the metadata needed to identify,
 /// verify and decrypt it.
-#[derive(Debug, PartialEq, Serialize, Deserialize)]
+#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
 struct Block {
     /// Identifies this block and defines its location in the tree.
     path: Path,
@@ -58,7 +58,7 @@ impl ReadCap {
 }
 
 /// Verifies that a principal is authorized to write blocks in a tree.
-#[derive(Debug, PartialEq, Serialize, Deserialize)]
+#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
 struct WriteCap {
     /// The principal this `WriteCap` was issued to.
     issued_to: Principal,
@@ -131,11 +131,11 @@ impl FragmentRecord {
 }
 
 /// An identifier for a security principal, which is any entity that can be authenticated.
-#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Hashable)]
+#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Hashable, Clone)]
 struct Principal(Hash);
 
 /// An identifier for a block in a tree.
-#[derive(Debug, PartialEq, Serialize, Deserialize)]
+#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
 struct Path(Vec<String>);
 
 impl Path {
@@ -249,7 +249,7 @@ impl Display for PathError {
 }
 
 /// An instant in time represented by the number of seconds since January 1st 1970, 00:00:00 UTC.
-#[derive(Debug, PartialEq, Serialize, Deserialize)]
+#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
 struct Epoch(i64);
 
 /// The serial number of a block fragment.

+ 64 - 45
crates/node/src/serde_tests.rs

@@ -4,12 +4,12 @@ use super::*;
 use crypto::{Hash, Signature, Key};
 use serde_block_tree::{Error, Result, from_vec, to_vec};
 
-static PRINCIPAL: [u8; 32] = [
+pub const PRINCIPAL: [u8; 32] = [
     0x75, 0x28, 0xA9, 0xE0, 0x9D, 0x24, 0xBA, 0xB3, 0x79, 0x56, 0x15, 0x68, 0xFD, 0xA4, 0xE2, 0xA4,
     0xCF, 0xB2, 0xC0, 0xE3, 0x96, 0xAE, 0xA2, 0x6E, 0x45, 0x15, 0x50, 0xED, 0xA6, 0xBE, 0x6D, 0xEC,
 ];
 
-static PAYLOAD: [u8; 128] = [
+pub const PAYLOAD: [u8; 128] = [
     0x39, 0x79, 0x1A, 0x0D, 0x8E, 0x6C, 0xF5, 0x4B, 0xF3, 0xA4, 0x75, 0xC4, 0x44, 0x73, 0x58, 0x58,
     0x97, 0x14, 0x64, 0xE0, 0xC6, 0xFE, 0xCB, 0xCF, 0xBE, 0x67, 0x49, 0x49, 0x40, 0xAE, 0x71, 0x5A,
     0x94, 0x7E, 0x6C, 0x4B, 0xDE, 0x33, 0x22, 0x75, 0xD8, 0x54, 0x23, 0x37, 0xFD, 0x1A, 0x68, 0x4A,
@@ -20,25 +20,84 @@ static PAYLOAD: [u8; 128] = [
     0xEE, 0x1F, 0x84, 0x17, 0xA2, 0x74, 0xC3, 0xC3, 0xD5, 0x2F, 0x70, 0x74, 0xFE, 0xD8, 0x2C, 0x29,
 ];
 
-static SIGNATURE: [u8; 64] = [
+pub const SIGNATURE: [u8; 64] = [
     0x2E, 0x19, 0x8E, 0xCC, 0x2D, 0xE1, 0x0E, 0x42, 0x3F, 0xBB, 0x89, 0x3D, 0x07, 0xAB, 0x57, 0xBF,
     0xEB, 0xB1, 0xA7, 0x23, 0xF9, 0xD2, 0xC3, 0x3F, 0x7A, 0x3C, 0xD0, 0x31, 0x38, 0x01, 0x33, 0x1F,
     0x07, 0x8D, 0x68, 0x0C, 0x6B, 0xF1, 0xBA, 0xD3, 0xD4, 0xAE, 0xAD, 0x1A, 0xF7, 0x5D, 0x2C, 0xEF,
     0x1F, 0x5C, 0x50, 0xE9, 0xFA, 0x8A, 0xDB, 0xB2, 0x4C, 0xC6, 0x9B, 0x06, 0x5F, 0xFB, 0xE3, 0xDA,
 ];
 
-static KEY: [u8; 32] = [
+pub const 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,
 ];
 
-static LONG_KEY: [u8; 64] = [
+pub const BLOCK_KEY: [u8; 32] = [
+    0xEE, 0x76, 0xD6, 0xDC, 0x6D, 0x94, 0x1D, 0x95, 0xC2, 0x57, 0x94, 0x46, 0xA2, 0x97, 0x8F, 0x5B,
+    0x59, 0xE1, 0x7E, 0xE4, 0x3B, 0xB1, 0x69, 0x88, 0x5D, 0x16, 0x30, 0x5A, 0x50, 0xDB, 0x58, 0x65,
+];
+
+pub const LONG_KEY: [u8; 64] = [
     0x65, 0x4E, 0x78, 0x5C, 0x8E, 0xEE, 0x9E, 0x57, 0x58, 0x8D, 0xDE, 0x9E, 0x6D, 0x84, 0xF4, 0x68,
     0x7F, 0x9E, 0x48, 0xC4, 0x6F, 0x1F, 0x4F, 0x83, 0x46, 0x68, 0xB2, 0xC1, 0x46, 0xD0, 0x06, 0xF2,
     0x23, 0xB9, 0xD4, 0x66, 0x4B, 0xED, 0x65, 0x92, 0xF1, 0xA2, 0x04, 0x1A, 0xD9, 0xF6, 0xA2, 0xAE,
     0x87, 0x3E, 0xBF, 0x10, 0x4A, 0x29, 0x28, 0x83, 0x2A, 0x8F, 0xC5, 0x30, 0x86, 0x11, 0x48, 0x52,
 ];
 
+pub const IV: [u8; 16] = [
+    0x60, 0xE0, 0xBE, 0x45, 0xA9, 0xAB, 0x5D, 0x99, 0x3B, 0x3A, 0x1E, 0x54, 0x18, 0xE0, 0x46, 0xDE,
+];
+
+pub const BLOCK_IV: [u8; 16] = [
+    0xF2, 0xB5, 0x64, 0xF3, 0x82, 0xC6, 0xEC, 0x1E, 0x35, 0xAA, 0x34, 0xD1, 0x40, 0xA3, 0xA8, 0xB3,
+];
+
+pub(crate) fn make_principal() -> Principal {
+    Principal(Hash::Sha2_256(PRINCIPAL))
+}
+
+pub(crate) fn make_write_cap() -> Result<WriteCap> {
+    Ok(WriteCap {
+        issued_to: Principal(Hash::Sha2_256(PRINCIPAL)),
+        issued_by: Principal(Hash::Sha2_256(PRINCIPAL)),
+        path: Path::try_from("contacts/emergency").map_err(|err| Error::Message(err.to_string()))?,
+        expires: Epoch(1649904316),
+        signing_key: Key::Ed25519 { public: KEY, private: None },
+        signature: Signature::Ed25519(SIGNATURE),
+        next: Some(Box::from(WriteCap {
+            issued_to: Principal(Hash::Sha2_256(PRINCIPAL)),
+            issued_by: Principal(Hash::Sha2_256(PRINCIPAL)),
+            path: Path::try_from("contacts").map_err(|err| Error::Message(err.to_string()))?,
+            expires: Epoch(1649994316),
+            signing_key: Key::Ed25519 { public: KEY, private: None },
+            signature: Signature::Ed25519(SIGNATURE),
+            next: None,
+        }))
+    })
+}
+
+pub(crate) fn make_read_cap() -> ReadCap {
+    ReadCap::new(
+        Hash::Sha2_256(PRINCIPAL), Cryptotext::Plain(Key::Aes256Ctr { key: KEY, iv: IV })
+    )
+}
+
+pub(crate) fn make_block() -> Result<Block> {
+    let mut read_caps = HashMap::new();
+    {
+        let read_cap = make_read_cap();
+        read_caps.insert(read_cap.issued_to, read_cap.key);
+    }
+    let write_cap = make_write_cap()?;
+    Ok(Block {
+        path: Path::try_from("apps/verse").map_err(|err| Error::Message(err.to_string()))?,
+        read_caps,
+        write_cap,
+        body: Cryptotext::Plain(Vec::from(PAYLOAD)),
+        signature: Signature::Ed25519(SIGNATURE)
+    })
+}
+
 #[test]
 fn roundtrip_fragment_record() -> Result<()> {
     let expected = FragmentRecord::new(229, Hash::Sha2_256(PRINCIPAL));
@@ -76,26 +135,6 @@ fn roundtrip_fragment() -> Result<()> {
     Ok(())
 }
 
-fn make_write_cap() -> Result<WriteCap> {
-    Ok(WriteCap {
-        issued_to: Principal(Hash::Sha2_256(PRINCIPAL)),
-        issued_by: Principal(Hash::Sha2_256(PRINCIPAL)),
-        path: Path::try_from("contacts/emergency").map_err(|err| Error::Message(err.to_string()))?,
-        expires: Epoch(1649904316),
-        signing_key: Key::Ed25519 { public: KEY, private: None },
-        signature: Signature::Ed25519(SIGNATURE),
-        next: Some(Box::from(WriteCap {
-            issued_to: Principal(Hash::Sha2_256(PRINCIPAL)),
-            issued_by: Principal(Hash::Sha2_256(PRINCIPAL)),
-            path: Path::try_from("contacts").map_err(|err| Error::Message(err.to_string()))?,
-            expires: Epoch(1649994316),
-            signing_key: Key::Ed25519 { public: KEY, private: None },
-            signature: Signature::Ed25519(SIGNATURE),
-            next: None,
-        }))
-    })
-}
-
 #[test]
 fn roundtrip_write_cap() -> Result<()> {
     let expected = make_write_cap()?;
@@ -105,10 +144,6 @@ fn roundtrip_write_cap() -> Result<()> {
     Ok(())
 }
 
-fn make_read_cap() -> ReadCap {
-    ReadCap::new(Hash::Sha2_256(PRINCIPAL), Cryptotext::Plain(Key::Aes256Ctr(KEY)))
-}
-
 #[test]
 fn roundtrip_read_cap() -> Result<()> {
     let expected = make_read_cap();
@@ -118,22 +153,6 @@ fn roundtrip_read_cap() -> Result<()> {
     Ok(())
 }
 
-fn make_block() -> Result<Block> {
-    let mut read_caps = HashMap::new();
-    {
-        let read_cap = make_read_cap();
-        read_caps.insert(read_cap.issued_to, read_cap.key);
-    }
-    let write_cap = make_write_cap()?;
-    Ok(Block {
-            path: Path::try_from("apps/verse").map_err(|err| Error::Message(err.to_string()))?,
-            read_caps,
-            write_cap,
-            body: Cryptotext::Plain(Vec::from(PAYLOAD)),
-            signature: Signature::Ed25519(SIGNATURE)
-    })
-}
-
 #[test]
 fn roundtrip_versioned_block() -> Result<()> {
     let expected = VersionedBlock::V0(make_block()?);