You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@teaclave.apache.org by ms...@apache.org on 2020/04/10 00:24:53 UTC

[incubator-teaclave] 02/02: [crypto] Separate crypto related struct/functions from types in teaclave_crypto

This is an automated email from the ASF dual-hosted git repository.

mssun pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/incubator-teaclave.git

commit 700cb0890c4d0b77796a2eb2dd973683ad7c395c
Author: Mingshen Sun <bo...@mssun.me>
AuthorDate: Thu Apr 9 17:03:56 2020 -0700

    [crypto] Separate crypto related struct/functions from types in teaclave_crypto
---
 {types => crypto}/Cargo.toml                       |  13 +-
 types/src/crypto.rs => crypto/src/lib.rs           |  80 +-------
 function/Cargo.toml                                |   1 +
 function/src/context.rs                            |   2 +-
 function/src/gbdt_prediction.rs                    |   1 +
 function/src/gbdt_training.rs                      |   1 +
 function/src/logistic_regression_prediction.rs     |   1 +
 function/src/logistic_regression_training.rs       |   1 +
 function/src/mesapy.rs                             |   1 +
 services/execution/enclave/Cargo.toml              |   2 +
 services/execution/enclave/src/service.rs          |   1 +
 services/proto/Cargo.toml                          |   4 +-
 services/proto/src/teaclave_common.rs              |   3 +-
 tests/functional/enclave/Cargo.toml                |   2 +
 .../enclave/src/end_to_end/native_gbdt_training.rs |   1 +
 tests/integration/enclave/Cargo.toml               |   2 +
 tests/integration/enclave/src/teaclave_worker.rs   |   3 +-
 tests/unit/enclave/Cargo.toml                      |   3 +
 tests/unit/enclave/src/lib.rs                      |   1 +
 types/Cargo.toml                                   |   4 +-
 types/src/crypto.rs                                | 221 +--------------------
 types/src/lib.rs                                   |   2 +-
 types/src/staged_file.rs                           |   2 +-
 23 files changed, 41 insertions(+), 311 deletions(-)

diff --git a/types/Cargo.toml b/crypto/Cargo.toml
similarity index 66%
copy from types/Cargo.toml
copy to crypto/Cargo.toml
index 460d384..abc63e5 100644
--- a/types/Cargo.toml
+++ b/crypto/Cargo.toml
@@ -1,8 +1,8 @@
 [package]
-name = "teaclave_types"
+name = "teaclave_crypto"
 version = "0.1.0"
 authors = ["Teaclave Contributors <de...@teaclave.apache.org>"]
-description = "Teaclave types"
+description = "Teaclave crypto"
 license = "Apache-2.0"
 edition = "2018"
 
@@ -19,19 +19,12 @@ enclave_unit_test = ["teaclave_test_utils/mesalock_sgx"]
 [dependencies]
 protected_fs_rs  = { path = "../common/protected_fs_rs", default-features = false}
 
-log           = { version = "0.4.6" }
 anyhow       = { version = "1.0.26" }
-sgx_types    = { version = "1.1.1" }
 rand         = { version = "0.7.0" }
-hex          = { version = "0.4.0" }
 serde        = { version = "1.0.92", features = ["derive"] }
 serde_json   = { version = "1.0.39" }
-toml         = { version = "0.5.3" }
 ring         = { version = "0.16.5" }
-thiserror    = { version = "1.0.9" }
-url          = { version = "2.1.1", features = ["serde"]}
-uuid         = { version = "0.8.1", features = ["v4", "serde"] }
 
 teaclave_test_utils = { path = "../tests/utils", optional = true }
 
-sgx_tstd = { version = "1.1.1", features = ["net", "backtrace"], optional = true }
\ No newline at end of file
+sgx_tstd = { version = "1.1.1", features = ["net", "backtrace"], optional = true }
diff --git a/types/src/crypto.rs b/crypto/src/lib.rs
similarity index 75%
copy from types/src/crypto.rs
copy to crypto/src/lib.rs
index 6fb5711..12aa962 100644
--- a/types/src/crypto.rs
+++ b/crypto/src/lib.rs
@@ -15,10 +15,14 @@
 // specific language governing permissions and limitations
 // under the License.
 
+#![cfg_attr(feature = "mesalock_sgx", no_std)]
+#[cfg(feature = "mesalock_sgx")]
+extern crate sgx_tstd as std;
+
 #[cfg(feature = "mesalock_sgx")]
 use std::prelude::v1::*;
 
-use anyhow::{anyhow, bail, ensure, Result};
+use anyhow::{anyhow, ensure, Result};
 use rand::prelude::RngCore;
 use ring::aead;
 use serde::{Deserialize, Serialize};
@@ -167,80 +171,6 @@ impl Default for TeaclaveFile128Key {
     }
 }
 
-#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq)]
-pub enum FileCrypto {
-    AesGcm128(AesGcm128Key),
-    AesGcm256(AesGcm256Key),
-    TeaclaveFile128(TeaclaveFile128Key),
-    Raw,
-}
-
-impl FileCrypto {
-    pub fn new(schema: &str, key: &[u8], iv: &[u8]) -> Result<Self> {
-        let info = match schema {
-            "aes_gcm_128" => {
-                let crypto = AesGcm128Key::new(key, iv)?;
-                FileCrypto::AesGcm128(crypto)
-            }
-            "aes_gcm_256" => {
-                let crypto = AesGcm256Key::new(key, iv)?;
-                FileCrypto::AesGcm256(crypto)
-            }
-            "teaclave_file_128" => {
-                ensure!(iv.is_empty(), "IV is not empty for teaclave_file_128");
-                let crypto = TeaclaveFile128Key::new(key)?;
-                FileCrypto::TeaclaveFile128(crypto)
-            }
-            "raw" => FileCrypto::Raw,
-            _ => bail!("Invalid crypto schema: {}", schema),
-        };
-
-        Ok(info)
-    }
-
-    pub fn schema(&self) -> &str {
-        match self {
-            FileCrypto::AesGcm128(_) => "aes_gcm_128",
-            FileCrypto::AesGcm256(_) => "aes_gcm_256",
-            FileCrypto::TeaclaveFile128(_) => "teaclave_file_128",
-            FileCrypto::Raw => "raw",
-        }
-    }
-
-    pub fn key_iv(&self) -> (Vec<u8>, Vec<u8>) {
-        match self {
-            FileCrypto::AesGcm128(crypto) => (crypto.key.to_vec(), crypto.iv.to_vec()),
-            FileCrypto::AesGcm256(crypto) => (crypto.key.to_vec(), crypto.iv.to_vec()),
-            FileCrypto::TeaclaveFile128(crypto) => (crypto.key.to_vec(), Vec::new()),
-            FileCrypto::Raw => (vec![], vec![]),
-        }
-    }
-}
-
-impl std::convert::From<AesGcm128Key> for FileCrypto {
-    fn from(crypto: AesGcm128Key) -> Self {
-        FileCrypto::AesGcm128(crypto)
-    }
-}
-
-impl std::convert::From<AesGcm256Key> for FileCrypto {
-    fn from(crypto: AesGcm256Key) -> Self {
-        FileCrypto::AesGcm256(crypto)
-    }
-}
-
-impl std::convert::From<TeaclaveFile128Key> for FileCrypto {
-    fn from(crypto: TeaclaveFile128Key) -> Self {
-        FileCrypto::TeaclaveFile128(crypto)
-    }
-}
-
-impl Default for FileCrypto {
-    fn default() -> Self {
-        FileCrypto::TeaclaveFile128(TeaclaveFile128Key::random())
-    }
-}
-
 pub fn aead_decrypt<'a>(
     alg: &'static aead::Algorithm,
     in_out: &'a mut [u8],
diff --git a/function/Cargo.toml b/function/Cargo.toml
index e6022b7..0249283 100644
--- a/function/Cargo.toml
+++ b/function/Cargo.toml
@@ -32,6 +32,7 @@ gbdt          = { version = "0.1.0", features = ["input", "enable_training"] }
 rusty-machine = { version = "0.5.4" }
 itertools     = { version = "0.8.0", default-features = false }
 teaclave_types = { path = "../types" }
+teaclave_crypto = { path = "../crypto" }
 teaclave_runtime = { path = "../runtime", optional = true }
 teaclave_test_utils = { path = "../tests/utils", optional = true }
 
diff --git a/function/src/context.rs b/function/src/context.rs
index 7c34c36..20b2f8e 100644
--- a/function/src/context.rs
+++ b/function/src/context.rs
@@ -237,12 +237,12 @@ pub mod tests {
     use super::*;
     use std::path::PathBuf;
     use std::str::FromStr;
+    use teaclave_crypto::TeaclaveFile128Key;
     use teaclave_runtime::RawIoRuntime;
     use teaclave_test_utils::*;
     use teaclave_types::hashmap;
     use teaclave_types::StagedFileInfo;
     use teaclave_types::StagedFiles;
-    use teaclave_types::TeaclaveFile128Key;
 
     pub fn run_tests() -> bool {
         run_tests!(test_file_handle_encoding, test_rtc_api,)
diff --git a/function/src/gbdt_prediction.rs b/function/src/gbdt_prediction.rs
index 57ec08b..de2bdac 100644
--- a/function/src/gbdt_prediction.rs
+++ b/function/src/gbdt_prediction.rs
@@ -92,6 +92,7 @@ fn parse_test_data(input: impl io::Read) -> anyhow::Result<Vec<Data>> {
 pub mod tests {
     use super::*;
     use std::untrusted::fs;
+    use teaclave_crypto::*;
     use teaclave_runtime::*;
     use teaclave_test_utils::*;
     use teaclave_types::*;
diff --git a/function/src/gbdt_training.rs b/function/src/gbdt_training.rs
index e911834..27b376a 100644
--- a/function/src/gbdt_training.rs
+++ b/function/src/gbdt_training.rs
@@ -159,6 +159,7 @@ fn parse_training_data(input: impl io::Read, feature_size: usize) -> anyhow::Res
 pub mod tests {
     use super::*;
     use std::untrusted::fs;
+    use teaclave_crypto::*;
     use teaclave_runtime::*;
     use teaclave_test_utils::*;
     use teaclave_types::*;
diff --git a/function/src/logistic_regression_prediction.rs b/function/src/logistic_regression_prediction.rs
index 7aacd79..1f6b645 100644
--- a/function/src/logistic_regression_prediction.rs
+++ b/function/src/logistic_regression_prediction.rs
@@ -103,6 +103,7 @@ pub mod tests {
     use super::*;
     use std::path::Path;
     use std::untrusted::fs;
+    use teaclave_crypto::*;
     use teaclave_runtime::*;
     use teaclave_test_utils::*;
     use teaclave_types::*;
diff --git a/function/src/logistic_regression_training.rs b/function/src/logistic_regression_training.rs
index d79f4a7..b415961 100644
--- a/function/src/logistic_regression_training.rs
+++ b/function/src/logistic_regression_training.rs
@@ -121,6 +121,7 @@ pub mod tests {
     use super::*;
     use std::path::Path;
     use std::untrusted::fs;
+    use teaclave_crypto::*;
     use teaclave_runtime::*;
     use teaclave_test_utils::*;
     use teaclave_types::*;
diff --git a/function/src/mesapy.rs b/function/src/mesapy.rs
index c77f8c8..7398901 100644
--- a/function/src/mesapy.rs
+++ b/function/src/mesapy.rs
@@ -94,6 +94,7 @@ impl TeaclaveFunction for Mesapy {
 #[cfg(feature = "enclave_unit_test")]
 pub mod tests {
     use super::*;
+    use teaclave_crypto::*;
     use teaclave_runtime::*;
     use teaclave_test_utils::*;
     use teaclave_types::*;
diff --git a/services/execution/enclave/Cargo.toml b/services/execution/enclave/Cargo.toml
index 029dad6..6923155 100644
--- a/services/execution/enclave/Cargo.toml
+++ b/services/execution/enclave/Cargo.toml
@@ -20,6 +20,7 @@ mesalock_sgx = [
   "teaclave_rpc/mesalock_sgx",
   "teaclave_service_enclave_utils/mesalock_sgx",
   "teaclave_types/mesalock_sgx",
+  "teaclave_crypto/mesalock_sgx",
   "teaclave_config/mesalock_sgx",
   "teaclave_config/build_config",
   "teaclave_worker/mesalock_sgx",
@@ -44,6 +45,7 @@ teaclave_binder                = { path = "../../../binder" }
 teaclave_rpc                   = { path = "../../../rpc" }
 teaclave_service_enclave_utils = { path = "../../utils/service_enclave_utils" }
 teaclave_types                 = { path = "../../../types" }
+teaclave_crypto                = { path = "../../../crypto" }
 teaclave_worker                = { path = "../../../worker" }
 teaclave_test_utils            = { path = "../../../tests/utils", optional = true }
 
diff --git a/services/execution/enclave/src/service.rs b/services/execution/enclave/src/service.rs
index 0dae8d5..d743cba 100644
--- a/services/execution/enclave/src/service.rs
+++ b/services/execution/enclave/src/service.rs
@@ -166,6 +166,7 @@ fn finalize_task(file_mgr: &TaskFileManager) -> Result<()> {
 pub mod tests {
     use super::*;
     use std::format;
+    use teaclave_crypto::*;
     use url::Url;
     use uuid::Uuid;
 
diff --git a/services/proto/Cargo.toml b/services/proto/Cargo.toml
index d90247e..f5bfac4 100644
--- a/services/proto/Cargo.toml
+++ b/services/proto/Cargo.toml
@@ -10,7 +10,8 @@ edition = "2018"
 default = []
 mesalock_sgx = [
     "sgx_tstd",
-    "teaclave_types/mesalock_sgx"
+    "teaclave_types/mesalock_sgx",
+    "teaclave_crypto/mesalock_sgx",
 ]
 cov = ["sgx_cov"]
 
@@ -30,3 +31,4 @@ sgx_tstd     = { version = "1.1.1", features = ["net", "backtrace"], optional =
 sgx_types    = { version = "1.1.1" }
 teaclave_rpc = { path = "../../rpc" }
 teaclave_types = { path = "../../types" }
+teaclave_crypto = { path = "../../crypto" }
diff --git a/services/proto/src/teaclave_common.rs b/services/proto/src/teaclave_common.rs
index b98b028..5b0c496 100644
--- a/services/proto/src/teaclave_common.rs
+++ b/services/proto/src/teaclave_common.rs
@@ -20,7 +20,8 @@ use std::prelude::v1::*;
 
 use crate::teaclave_common_proto as proto;
 use anyhow::{bail, Error, Result};
-use teaclave_types::{FileCrypto, TaskFailure, TaskOutputs, TaskStatus, TeaclaveFile128Key};
+use teaclave_crypto::TeaclaveFile128Key;
+use teaclave_types::{FileCrypto, TaskFailure, TaskOutputs, TaskStatus};
 
 #[derive(Debug)]
 pub struct UserCredential {
diff --git a/tests/functional/enclave/Cargo.toml b/tests/functional/enclave/Cargo.toml
index 03111cc..ae544cd 100644
--- a/tests/functional/enclave/Cargo.toml
+++ b/tests/functional/enclave/Cargo.toml
@@ -22,6 +22,7 @@ mesalock_sgx = [
   "teaclave_config/build_config",
   "teaclave_service_enclave_utils/mesalock_sgx",
   "teaclave_types/mesalock_sgx",
+  "teaclave_crypto/mesalock_sgx",
   "teaclave_test_utils/mesalock_sgx",
 ]
 cov = ["teaclave_service_enclave_utils/cov"]
@@ -42,6 +43,7 @@ teaclave_binder                = { path = "../../../binder" }
 teaclave_rpc                   = { path = "../../../rpc" }
 teaclave_service_enclave_utils = { path = "../../../services/utils/service_enclave_utils" }
 teaclave_types                 = { path = "../../../types" }
+teaclave_crypto                = { path = "../../../crypto" }
 teaclave_proto                 = { path = "../../../services/proto" }
 teaclave_test_utils            = { path = "../../../tests/utils" }
 
diff --git a/tests/functional/enclave/src/end_to_end/native_gbdt_training.rs b/tests/functional/enclave/src/end_to_end/native_gbdt_training.rs
index 5f1b70a..0affbdf 100644
--- a/tests/functional/enclave/src/end_to_end/native_gbdt_training.rs
+++ b/tests/functional/enclave/src/end_to_end/native_gbdt_training.rs
@@ -16,6 +16,7 @@
 // under the License.
 
 use super::*;
+use teaclave_crypto::TeaclaveFile128Key;
 
 // Authenticate user before talking to frontend service
 fn authorized_frontend_client() -> TeaclaveFrontendClient {
diff --git a/tests/integration/enclave/Cargo.toml b/tests/integration/enclave/Cargo.toml
index 43253a3..80b8d4a 100644
--- a/tests/integration/enclave/Cargo.toml
+++ b/tests/integration/enclave/Cargo.toml
@@ -21,6 +21,7 @@ mesalock_sgx = [
   "teaclave_rpc/mesalock_sgx",
   "teaclave_service_enclave_utils/mesalock_sgx",
   "teaclave_types/mesalock_sgx",
+  "teaclave_crypto/mesalock_sgx",
   "rusty-leveldb/mesalock_sgx",
   "protected_fs_rs/mesalock_sgx",
   "teaclave_worker/mesalock_sgx",
@@ -46,6 +47,7 @@ teaclave_binder                = { path = "../../../binder" }
 teaclave_rpc                   = { path = "../../../rpc" }
 teaclave_service_enclave_utils = { path = "../../../services/utils/service_enclave_utils" }
 teaclave_types                 = { path = "../../../types" }
+teaclave_crypto                = { path = "../../../crypto" }
 teaclave_proto                 = { path = "../../../services/proto" }
 teaclave_worker                = { path = "../../../worker" }
 teaclave_test_utils            = { path = "../../../tests/utils" }
diff --git a/tests/integration/enclave/src/teaclave_worker.rs b/tests/integration/enclave/src/teaclave_worker.rs
index 383bbaa..ae4dbcd 100644
--- a/tests/integration/enclave/src/teaclave_worker.rs
+++ b/tests/integration/enclave/src/teaclave_worker.rs
@@ -17,9 +17,10 @@
 
 use std::prelude::v1::*;
 
+use teaclave_crypto::TeaclaveFile128Key;
 use teaclave_types::{
     hashmap, read_all_bytes, Executor, ExecutorType, FunctionArguments, StagedFileInfo,
-    StagedFiles, StagedFunction, TeaclaveFile128Key,
+    StagedFiles, StagedFunction,
 };
 use teaclave_worker::Worker;
 
diff --git a/tests/unit/enclave/Cargo.toml b/tests/unit/enclave/Cargo.toml
index 42112d5..7239ab7 100644
--- a/tests/unit/enclave/Cargo.toml
+++ b/tests/unit/enclave/Cargo.toml
@@ -21,6 +21,8 @@ mesalock_sgx = [
   "teaclave_service_enclave_utils/mesalock_sgx",
   "teaclave_types/mesalock_sgx",
   "teaclave_types/enclave_unit_test",
+  "teaclave_crypto/mesalock_sgx",
+  "teaclave_crypto/enclave_unit_test",
   "teaclave_config/mesalock_sgx",
   "teaclave_access_control_service_enclave/mesalock_sgx",
   "teaclave_access_control_service_enclave/enclave_unit_test",
@@ -70,6 +72,7 @@ teaclave_binder                = { path = "../../../binder" }
 teaclave_rpc                   = { path = "../../../rpc" }
 teaclave_service_enclave_utils = { path = "../../../services/utils/service_enclave_utils" }
 teaclave_types                 = { path = "../../../types" }
+teaclave_crypto                = { path = "../../../crypto" }
 
 sgx_tstd  = { version = "1.1.1", features = ["net", "thread", "backtrace"], optional = true }
 sgx_types = { version = "1.1.1" }
diff --git a/tests/unit/enclave/src/lib.rs b/tests/unit/enclave/src/lib.rs
index fb5a000..008f002 100644
--- a/tests/unit/enclave/src/lib.rs
+++ b/tests/unit/enclave/src/lib.rs
@@ -42,6 +42,7 @@ fn handle_run_test(_: &RunTestInput) -> TeeServiceResult<RunTestOutput> {
         teaclave_runtime::tests::run_tests(),
         teaclave_function::tests::run_tests(),
         teaclave_types::tests::run_tests(),
+        teaclave_crypto::tests::run_tests(),
         rusty_leveldb::tests::run_tests(),
     );
 
diff --git a/types/Cargo.toml b/types/Cargo.toml
index 460d384..8a8c5fd 100644
--- a/types/Cargo.toml
+++ b/types/Cargo.toml
@@ -12,6 +12,7 @@ default = [
 ]
 mesalock_sgx = [
     "sgx_tstd",
+    "teaclave_crypto/mesalock_sgx",
     "protected_fs_rs/mesalock_sgx",
 ]
 enclave_unit_test = ["teaclave_test_utils/mesalock_sgx"]
@@ -33,5 +34,6 @@ url          = { version = "2.1.1", features = ["serde"]}
 uuid         = { version = "0.8.1", features = ["v4", "serde"] }
 
 teaclave_test_utils = { path = "../tests/utils", optional = true }
+teaclave_crypto = { path = "../crypto" }
 
-sgx_tstd = { version = "1.1.1", features = ["net", "backtrace"], optional = true }
\ No newline at end of file
+sgx_tstd = { version = "1.1.1", features = ["net", "backtrace"], optional = true }
diff --git a/types/src/crypto.rs b/types/src/crypto.rs
index 6fb5711..0f47917 100644
--- a/types/src/crypto.rs
+++ b/types/src/crypto.rs
@@ -18,154 +18,11 @@
 #[cfg(feature = "mesalock_sgx")]
 use std::prelude::v1::*;
 
-use anyhow::{anyhow, bail, ensure, Result};
-use rand::prelude::RngCore;
-use ring::aead;
+use anyhow::{bail, ensure, Result};
 use serde::{Deserialize, Serialize};
 use std::format;
 
-const AES_GCM_128_KEY_LENGTH: usize = 16;
-const AES_GCM_128_IV_LENGTH: usize = 12;
-
-const AES_GCM_256_KEY_LENGTH: usize = 32;
-const AES_GCM_256_IV_LENGTH: usize = 12;
-
-const TEACLAVE_FILE_128_ROOT_KEY_LENGTH: usize = 16;
-
-#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq)]
-pub struct AesGcm256Key {
-    pub key: [u8; AES_GCM_256_KEY_LENGTH],
-    pub iv: [u8; AES_GCM_256_IV_LENGTH],
-}
-
-impl AesGcm256Key {
-    pub fn new(in_key: &[u8], in_iv: &[u8]) -> Result<Self> {
-        ensure!(
-            in_key.len() == AES_GCM_256_KEY_LENGTH,
-            "Invalid key length for AesGcm256: {}",
-            in_key.len()
-        );
-        ensure!(
-            in_iv.len() == AES_GCM_256_IV_LENGTH,
-            "Invalid iv length for AesGcm256: {}",
-            in_iv.len()
-        );
-        let mut key = [0u8; AES_GCM_256_KEY_LENGTH];
-        let mut iv = [0u8; AES_GCM_256_IV_LENGTH];
-        key.copy_from_slice(in_key);
-        iv.copy_from_slice(in_iv);
-
-        Ok(AesGcm256Key { key, iv })
-    }
-
-    pub fn decrypt(&self, in_out: &mut Vec<u8>) -> Result<()> {
-        let plaintext_len = aead_decrypt(&aead::AES_256_GCM, in_out, &self.key, &self.iv)?.len();
-        in_out.truncate(plaintext_len);
-
-        Ok(())
-    }
-
-    pub fn encrypt(&self, in_out: &mut Vec<u8>) -> Result<()> {
-        aead_encrypt(&aead::AES_128_GCM, in_out, &self.key, &self.iv)
-    }
-}
-
-impl Default for AesGcm256Key {
-    fn default() -> Self {
-        let mut key = [0u8; AES_GCM_256_KEY_LENGTH];
-        let mut iv = [0u8; AES_GCM_256_IV_LENGTH];
-        let mut rng = rand::thread_rng();
-        rng.fill_bytes(&mut key);
-        rng.fill_bytes(&mut iv);
-
-        Self { key, iv }
-    }
-}
-
-#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq)]
-pub struct AesGcm128Key {
-    pub key: [u8; AES_GCM_128_KEY_LENGTH],
-    pub iv: [u8; AES_GCM_128_IV_LENGTH],
-}
-
-impl AesGcm128Key {
-    pub fn new(in_key: &[u8], in_iv: &[u8]) -> Result<Self> {
-        ensure!(
-            in_key.len() == AES_GCM_128_KEY_LENGTH,
-            "Invalid key length for AesGcm128: {}",
-            in_key.len()
-        );
-
-        ensure!(
-            in_iv.len() == AES_GCM_128_IV_LENGTH,
-            "Invalid iv length for AesGcm128: {}",
-            in_iv.len()
-        );
-
-        let mut key = [0u8; AES_GCM_128_KEY_LENGTH];
-        let mut iv = [0u8; AES_GCM_128_IV_LENGTH];
-        key.copy_from_slice(in_key);
-        iv.copy_from_slice(in_iv);
-
-        Ok(AesGcm128Key { key, iv })
-    }
-
-    pub fn decrypt(&self, in_out: &mut Vec<u8>) -> Result<()> {
-        let plaintext_len = aead_decrypt(&aead::AES_128_GCM, in_out, &self.key, &self.iv)?.len();
-        in_out.truncate(plaintext_len);
-
-        Ok(())
-    }
-
-    pub fn encrypt(&self, in_out: &mut Vec<u8>) -> Result<()> {
-        aead_encrypt(&aead::AES_128_GCM, in_out, &self.key, &self.iv)
-    }
-}
-
-impl Default for AesGcm128Key {
-    fn default() -> Self {
-        let mut key = [0u8; AES_GCM_128_KEY_LENGTH];
-        let mut iv = [0u8; AES_GCM_128_IV_LENGTH];
-        let mut rng = rand::thread_rng();
-        rng.fill_bytes(&mut key);
-        rng.fill_bytes(&mut iv);
-
-        Self { key, iv }
-    }
-}
-
-#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq)]
-pub struct TeaclaveFile128Key {
-    pub key: [u8; TEACLAVE_FILE_128_ROOT_KEY_LENGTH],
-}
-
-impl TeaclaveFile128Key {
-    pub fn random() -> Self {
-        Self::default()
-    }
-
-    pub fn new(in_key: &[u8]) -> Result<Self> {
-        ensure!(
-            in_key.len() == TEACLAVE_FILE_128_ROOT_KEY_LENGTH,
-            "Invalid key length for teaclave_file_128: {}",
-            in_key.len()
-        );
-        let mut key = [0u8; TEACLAVE_FILE_128_ROOT_KEY_LENGTH];
-        key.copy_from_slice(in_key);
-
-        Ok(TeaclaveFile128Key { key })
-    }
-}
-
-impl Default for TeaclaveFile128Key {
-    fn default() -> Self {
-        let mut key = [0u8; TEACLAVE_FILE_128_ROOT_KEY_LENGTH];
-        let mut rng = rand::thread_rng();
-        rng.fill_bytes(&mut key);
-
-        TeaclaveFile128Key { key }
-    }
-}
+use teaclave_crypto::*;
 
 #[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq)]
 pub enum FileCrypto {
@@ -240,77 +97,3 @@ impl Default for FileCrypto {
         FileCrypto::TeaclaveFile128(TeaclaveFile128Key::random())
     }
 }
-
-pub fn aead_decrypt<'a>(
-    alg: &'static aead::Algorithm,
-    in_out: &'a mut [u8],
-    key: &[u8],
-    iv: &[u8],
-) -> Result<&'a mut [u8]> {
-    let key =
-        aead::UnboundKey::new(alg, key).map_err(|_| anyhow!("Aead unbound key init error"))?;
-    let nonce =
-        aead::Nonce::try_assume_unique_for_key(iv).map_err(|_| anyhow!("Aead iv init error"))?;
-    let aad = aead::Aad::from([0u8; 8]);
-
-    let dec_key = aead::LessSafeKey::new(key);
-    let slice = dec_key
-        .open_in_place(nonce, aad, in_out)
-        .map_err(|_| anyhow!("Aead open_in_place error"))?;
-    Ok(slice)
-}
-
-pub fn aead_encrypt(
-    alg: &'static aead::Algorithm,
-    in_out: &mut Vec<u8>,
-    key: &[u8],
-    iv: &[u8],
-) -> Result<()> {
-    let key =
-        aead::UnboundKey::new(alg, key).map_err(|_| anyhow!("Aead unbound key init error"))?;
-    let nonce =
-        aead::Nonce::try_assume_unique_for_key(iv).map_err(|_| anyhow!("Aead iv init error"))?;
-    let aad = aead::Aad::from([0u8; 8]);
-
-    let enc_key = aead::LessSafeKey::new(key);
-    enc_key
-        .seal_in_place_append_tag(nonce, aad, in_out)
-        .map_err(|_| anyhow!("Aead seal_in_place_append_tag error"))?;
-    Ok(())
-}
-
-#[cfg(feature = "enclave_unit_test")]
-pub mod tests {
-    use super::*;
-    use teaclave_test_utils::*;
-
-    pub fn run_tests() -> bool {
-        run_tests!(test_aead_enc_then_dec, test_crypto_info,)
-    }
-
-    fn test_aead_enc_then_dec() {
-        let plain_text: [u8; 5] = [0xde, 0xff, 0xab, 0xcd, 0x90];
-        let key = [0x90u8; AES_GCM_128_KEY_LENGTH];
-        let iv = [0x89u8; 12];
-
-        let mut buf = plain_text.to_vec();
-        aead_encrypt(&aead::AES_128_GCM, &mut buf, &key, &iv).unwrap();
-        let result = aead_decrypt(&aead::AES_128_GCM, &mut buf, &key, &iv).unwrap();
-        assert_eq!(&result[..], &plain_text[..]);
-    }
-
-    fn test_crypto_info() {
-        let key = [0x90u8; AES_GCM_128_KEY_LENGTH];
-        let iv = [0x89u8; AES_GCM_128_IV_LENGTH];
-        let crypto_info = AesGcm128Key { key, iv };
-
-        let plain_text: [u8; 5] = [0xde, 0xff, 0xab, 0xcd, 0x90];
-        let mut buf = plain_text.to_vec();
-
-        crypto_info.encrypt(&mut buf).unwrap();
-        assert_ne!(&buf[..], &plain_text[..]);
-
-        crypto_info.decrypt(&mut buf).unwrap();
-        assert_eq!(&buf[..], &plain_text[..]);
-    }
-}
diff --git a/types/src/lib.rs b/types/src/lib.rs
index 9ca26e3..4b404e6 100644
--- a/types/src/lib.rs
+++ b/types/src/lib.rs
@@ -232,6 +232,6 @@ pub mod tests {
     use super::*;
 
     pub fn run_tests() -> bool {
-        worker::tests::run_tests() & crypto::tests::run_tests()
+        worker::tests::run_tests()
     }
 }
diff --git a/types/src/staged_file.rs b/types/src/staged_file.rs
index 0008527..e003f0a 100644
--- a/types/src/staged_file.rs
+++ b/types/src/staged_file.rs
@@ -15,7 +15,7 @@
 // specific language governing permissions and limitations
 // under the License.
 
-use crate::TeaclaveFile128Key;
+use teaclave_crypto::TeaclaveFile128Key;
 
 use std::collections::HashMap;
 #[cfg(not(feature = "mesalock_sgx"))]


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@teaclave.apache.org
For additional commands, e-mail: commits-help@teaclave.apache.org