teaclave-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From din...@apache.org
Subject [incubator-mesatee-sgx] branch v1.1.0-beta updated: v1.1.0-beta
Date Mon, 09 Dec 2019 01:11:40 GMT
This is an automated email from the ASF dual-hosted git repository.

dingyu pushed a commit to branch v1.1.0-beta
in repository https://gitbox.apache.org/repos/asf/incubator-mesatee-sgx.git


The following commit(s) were added to refs/heads/v1.1.0-beta by this push:
     new 347eaa8  v1.1.0-beta
347eaa8 is described below

commit 347eaa88b07e8a10e0d83e32fe6fc89d02413e8c
Author: Yu Ding <dingelish@gmail.com>
AuthorDate: Sun Dec 8 17:11:29 2019 -0800

    v1.1.0-beta
---
 .../localattestation/attestation/src/func.rs       |   8 +-
 .../localattestation/attestation/src/types.rs      |   2 +-
 samplecode/prost-protobuf/app/Cargo.toml           |   8 +-
 samplecode/unit-test/enclave/Cargo.toml            |   2 +
 samplecode/unit-test/enclave/src/lib.rs            |  13 +
 samplecode/unit-test/enclave/src/test_alignbox.rs  | 313 +++++++++++++++++
 sgx_tcrypto/src/crypto.rs                          | 369 +++++++++++++++------
 sgx_tdh/src/dh.rs                                  |  57 ++--
 sgx_tdh/src/ecp.rs                                 |  11 +-
 sgx_tprotected_fs/src/fs.rs                        |  22 +-
 sgx_tse/src/alignalloc.rs                          | 363 ++++++++++++++++++++
 sgx_tse/src/alignbox.rs                            | 260 +++++++++++++++
 sgx_tse/src/alloc.rs                               | 350 +++++++++++++++++++
 sgx_tse/src/lib.rs                                 | 194 +----------
 sgx_tse/src/{lib.rs => se.rs}                      |  20 +-
 sgx_tseal/src/internal.rs                          |  17 +-
 sgx_tstd/src/sgxfs.rs                              |   6 +-
 sgx_tstd/src/sys/sgxfs.rs                          |  20 +-
 sgx_types/src/function.rs                          |   4 +-
 sgx_types/src/metadata.rs                          |  12 +-
 sgx_types/src/types.rs                             |  64 +++-
 sgx_ucrypto/src/crypto.rs                          | 182 +++++-----
 sgx_ucrypto/src/util.rs                            |   2 +-
 23 files changed, 1807 insertions(+), 492 deletions(-)

diff --git a/samplecode/localattestation/attestation/src/func.rs b/samplecode/localattestation/attestation/src/func.rs
index 89c21b1..beb017b 100644
--- a/samplecode/localattestation/attestation/src/func.rs
+++ b/samplecode/localattestation/attestation/src/func.rs
@@ -78,7 +78,7 @@ pub fn create_session(src_enclave_id: sgx_enclave_id_t, dest_enclave_id: sgx_enc
 
     let mut dh_msg1: SgxDhMsg1 = SgxDhMsg1::default(); //Diffie-Hellman Message 1
     let mut dh_msg2: SgxDhMsg2 = SgxDhMsg2::default(); //Diffie-Hellman Message 2
-    let mut dh_aek: sgx_key_128bit_t = sgx_key_128bit_t::default(); // Session Key
+    let mut dh_aek: sgx_align_key_128bit_t = sgx_align_key_128bit_t::default(); // Session Key
     let mut responder_identity: sgx_dh_session_enclave_identity_t = sgx_dh_session_enclave_identity_t::default();
     let mut ret = 0;
 
@@ -114,7 +114,7 @@ pub fn create_session(src_enclave_id: sgx_enclave_id_t, dest_enclave_id: sgx_enc
     }
     let dh_msg3 = dh_msg3.unwrap();
 
-    let status = initiator.proc_msg3(&dh_msg3, &mut dh_aek, &mut responder_identity);
+    let status = initiator.proc_msg3(&dh_msg3, &mut dh_aek.key, &mut responder_identity);
     if status.is_err() {
         return ATTESTATION_STATUS::ATTESTATION_ERROR;
     }
@@ -169,7 +169,7 @@ pub extern "C" fn session_request(src_enclave_id: sgx_enclave_id_t, dh_msg1: *mu
 #[allow(unused_variables)]
 fn exchange_report_safe(src_enclave_id: sgx_enclave_id_t, dh_msg2: &mut sgx_dh_msg2_t , dh_msg3: &mut sgx_dh_msg3_t, session_info: &mut DhSessionInfo) -> ATTESTATION_STATUS {
 
-    let mut dh_aek = sgx_key_128bit_t::default() ;   // Session key
+    let mut dh_aek = sgx_align_key_128bit_t::default() ;   // Session key
     let mut initiator_identity = sgx_dh_session_enclave_identity_t::default();
 
     let mut responder = match session_info.session.session_status {
@@ -180,7 +180,7 @@ fn exchange_report_safe(src_enclave_id: sgx_enclave_id_t, dh_msg2: &mut sgx_dh_m
     };
 
     let mut dh_msg3_r = SgxDhMsg3::default();
-    let status = responder.proc_msg2(dh_msg2, &mut dh_msg3_r, &mut dh_aek, &mut initiator_identity);
+    let status = responder.proc_msg2(dh_msg2, &mut dh_msg3_r, &mut dh_aek.key, &mut initiator_identity);
     if status.is_err() {
         return ATTESTATION_STATUS::ATTESTATION_ERROR;
     }
diff --git a/samplecode/localattestation/attestation/src/types.rs b/samplecode/localattestation/attestation/src/types.rs
index 51df55e..325a575 100644
--- a/samplecode/localattestation/attestation/src/types.rs
+++ b/samplecode/localattestation/attestation/src/types.rs
@@ -66,7 +66,7 @@ pub struct Callback {
 pub enum DhSessionStatus {
     Closed,
     InProgress(SgxDhResponder),
-    Active(sgx_key_128bit_t),
+    Active(sgx_align_key_128bit_t),
 }
 
 impl Default for DhSessionStatus {
diff --git a/samplecode/prost-protobuf/app/Cargo.toml b/samplecode/prost-protobuf/app/Cargo.toml
index 0301f42..32c6134 100644
--- a/samplecode/prost-protobuf/app/Cargo.toml
+++ b/samplecode/prost-protobuf/app/Cargo.toml
@@ -7,13 +7,13 @@ build = "build.rs"
 [dependencies]
 sgx_types = { rev = "v1.0.9", git = "https://github.com/baidu/rust-sgx-sdk.git" }
 sgx_urts = { rev = "v1.0.9", git = "https://github.com/baidu/rust-sgx-sdk.git" }
-prost = "*"
-prost-types = "*"
-bytes = "*"
+prost = "0.5"
+prost-types = "0.5"
+bytes = "0.4"
 
 [patch.'https://github.com/baidu/rust-sgx-sdk.git']
 sgx_types = { path = "../../../sgx_types" }
 sgx_urts = { path = "../../../sgx_urts" }
 
 [build-dependencies]
-prost-build = "*"
+prost-build = "0.5"
diff --git a/samplecode/unit-test/enclave/Cargo.toml b/samplecode/unit-test/enclave/Cargo.toml
index cb873a6..8638c1f 100644
--- a/samplecode/unit-test/enclave/Cargo.toml
+++ b/samplecode/unit-test/enclave/Cargo.toml
@@ -19,10 +19,12 @@ sgx_trts = { git = "https://github.com/baidu/rust-sgx-sdk.git" }
 sgx_rand = { git = "https://github.com/baidu/rust-sgx-sdk.git" }
 sgx_tseal = { git = "https://github.com/baidu/rust-sgx-sdk.git" }
 sgx_serialize = { git = "https://github.com/baidu/rust-sgx-sdk.git" }
+sgx_tse= { git = "https://github.com/baidu/rust-sgx-sdk.git" }
 
 [dependencies]
 sgx_serialize_derive = { git = "https://github.com/baidu/rust-sgx-sdk.git" }
 rand = { version = "0.5.5", default-features = false }
+memoffset = "0.5"
 
 [patch.'https://github.com/baidu/rust-sgx-sdk.git']
 sgx_alloc = { path = "../../../sgx_alloc" }
diff --git a/samplecode/unit-test/enclave/src/lib.rs b/samplecode/unit-test/enclave/src/lib.rs
index 762ff6c..e67f2cf 100644
--- a/samplecode/unit-test/enclave/src/lib.rs
+++ b/samplecode/unit-test/enclave/src/lib.rs
@@ -49,6 +49,10 @@ extern crate sgx_rand;
 extern crate sgx_tseal;
 extern crate rand;
 
+#[macro_use]
+extern crate memoffset;
+extern crate sgx_tse;
+
 extern crate sgx_serialize;
 pub use sgx_serialize::*;
 #[macro_use]
@@ -105,6 +109,9 @@ use test_thread::*;
 mod test_mpsc;
 use test_mpsc::*;
 
+mod test_alignbox;
+use test_alignbox::*;
+
 #[no_mangle]
 pub extern "C"
 fn test_main_entrance() -> size_t {
@@ -327,6 +334,12 @@ fn test_main_entrance() -> size_t {
                     test_mpsc_sync_try_send2,
                     test_mpsc_sync_try_send3,
                     test_mpsc_sync_issue_15761,
+                    //test alignbox
+                    test_alignbox,
+                    test_alignbox_heap_init,
+                    test_alignbox_clone,
+                    test_alignbox_clonefrom,
+                    test_alignbox_clonefrom_no_eq_size,
                     )
 }
 
diff --git a/samplecode/unit-test/enclave/src/test_alignbox.rs b/samplecode/unit-test/enclave/src/test_alignbox.rs
new file mode 100644
index 0000000..3b91abc
--- /dev/null
+++ b/samplecode/unit-test/enclave/src/test_alignbox.rs
@@ -0,0 +1,313 @@
+// Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+//
+//  * Redistributions of source code must retain the above copyright
+//    notice, this list of conditions and the following disclaimer.
+//  * Redistributions in binary form must reproduce the above copyright
+//    notice, this list of conditions and the following disclaimer in
+//    the documentation and/or other materials provided with the
+//    distribution.
+//  * Neither the name of Baidu, Inc., nor the names of its
+//    contributors may be used to endorse or promote products derived
+//    from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+use std::mem;
+use sgx_tse::alignbox::*;
+use sgx_types::*;
+
+impl_struct! {
+    pub struct user_struct {
+        pub a: u8,
+        pub b: [u16; 2], 
+        pub c: u32,
+        pub d: [u64; 6],
+    }
+}
+
+impl_struct! {
+    pub struct struct_align_128_t {
+        pub key: sgx_key_128bit_t,
+    }
+}
+
+impl_struct! {
+    pub struct struct_no_align_t {
+        pub key1: sgx_key_128bit_t,
+        pub key2: sgx_key_128bit_t,
+        pub key3: sgx_key_128bit_t,
+        pub key4: sgx_key_128bit_t,
+    }
+}
+
+impl_struct! {
+    #[derive(PartialEq, Debug)]
+    pub struct struct_align_t{
+        pub key1: sgx_key_128bit_t,
+        pub pad1: [u8; 16],
+        pub key2: sgx_key_128bit_t ,
+        pub pad2: [u8; 16],
+        pub key3: sgx_key_128bit_t,
+        pub pad3: [u8; 16],
+        pub key4: sgx_key_128bit_t,
+    }
+}
+
+ pub fn test_alignbox() {
+    //align
+    {
+        let aligned_box: Option<AlignBox<struct_align_128_t>> = AlignBox::<struct_align_128_t>::new();
+        assert_eq!(aligned_box.is_some(), true);
+    }
+    //no align
+    {
+        let str_slice: &[align_req_t] = &[];
+        let aligned_box: Option<AlignBox<user_struct>> = AlignBox::<user_struct>::new_with_req(1, &str_slice);
+        assert_eq!(aligned_box.is_none(), true);
+    }
+    //align
+    {
+        let str_slice: &[align_req_t] = &[
+            align_req_t {
+                offset:offset_of!(user_struct, a),
+                len:mem::size_of::<u8>(),
+            },
+            align_req_t {
+                offset:offset_of!(user_struct, b),
+                len:mem::size_of::<[u16; 2]>(),
+            },
+            align_req_t {
+                offset: offset_of!(user_struct, d),
+                len:mem::size_of::<[u64; 6]>(),
+            }
+        ];
+        let aligned_box: Option<AlignBox<user_struct>> = AlignBox::<user_struct>::new_with_req(1, &str_slice);
+        assert_eq!(aligned_box.is_some(), true);
+    }
+    //no align
+    {
+        let str_slice: &[align_req_t] = &[
+            align_req_t {
+                offset:offset_of!(user_struct, a),
+                len:mem::size_of::<u8>(),
+            },
+            align_req_t {
+                offset:offset_of!(user_struct, b),
+                len:mem::size_of::<[u16; 2]>(),
+            },
+            align_req_t {
+                offset: offset_of!(user_struct, d),
+                len:mem::size_of::<[u64; 6]>(),
+            }
+        ];
+        let aligned_box: Option<AlignBox<user_struct>>  = AlignBox::<user_struct>::new_with_req(16, &str_slice);
+        assert_eq!(aligned_box.is_none(), true);
+    }
+    //no align
+    {
+        let str_slice: &[align_req_t] = &[
+            align_req_t {
+                offset:offset_of!(struct_align_t, key1),
+                len:mem::size_of::<sgx_key_128bit_t>(),
+            },
+            align_req_t {
+                offset: offset_of!(struct_align_t, key2),
+                len:mem::size_of::<sgx_key_128bit_t>(),
+            },
+            align_req_t {
+                offset:offset_of!(struct_align_t, key3),
+                len:mem::size_of::<sgx_key_128bit_t>(),
+            },
+            align_req_t {
+                offset: offset_of!(struct_align_t, key4),
+                len:mem::size_of::<sgx_key_128bit_t>(),
+            }
+        ];
+        let aligned_box: Option<AlignBox<struct_align_t>>  = AlignBox::<struct_align_t>::new_with_req(32, &str_slice);
+        assert_eq!(aligned_box.is_none(), true);
+    }
+    //align
+    {
+        let str_slice: &[align_req_t] = &[
+            align_req_t {
+                offset:offset_of!(struct_align_t, key1),
+                len:mem::size_of::<sgx_key_128bit_t>(),
+            },
+            align_req_t {
+                offset: offset_of!(struct_align_t, key2),
+                len:mem::size_of::<sgx_key_128bit_t>(),
+            },
+            align_req_t {
+                offset:offset_of!(struct_align_t, key3),
+                len:mem::size_of::<sgx_key_128bit_t>(),
+            },
+            align_req_t {
+                offset: offset_of!(struct_align_t, key4),
+                len:mem::size_of::<sgx_key_128bit_t>(),
+            }
+        ];
+        let aligned_box: Option<AlignBox<struct_align_t>>  = AlignBox::<struct_align_t>::new_with_req(16, &str_slice);
+        assert_eq!(aligned_box.is_some(), true);
+    }
+}
+
+pub fn test_alignbox_heap_init() {
+    let str_slice: &[align_req_t] = &[
+        align_req_t {
+            offset:offset_of!(struct_align_t, key1),
+            len:mem::size_of::<sgx_key_128bit_t>(),
+        },
+        align_req_t {
+            offset: offset_of!(struct_align_t, key2),
+            len:mem::size_of::<sgx_key_128bit_t>(),
+        },
+        align_req_t {
+            offset:offset_of!(struct_align_t, key3),
+            len:mem::size_of::<sgx_key_128bit_t>(),
+        },
+        align_req_t {
+            offset: offset_of!(struct_align_t, key4),
+            len:mem::size_of::<sgx_key_128bit_t>(),
+        }
+    ];
+
+    let stack_align_obj = struct_align_t {
+        key1: [0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff],
+        pad1: [0x00; 16],
+        key2: [0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff],
+        pad2: [0x00; 16],
+        key3: [0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff],
+        pad3: [0x00; 16],
+        key4: [0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff],
+    };
+    let heap_align_obj = AlignBox::<struct_align_t>::heap_init_with_req(|mut t| {
+        t.key1 = [0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff];
+        t.pad1 = [0x00; 16];
+        t.key2 = [0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff];
+        t.pad2 = [0x00; 16];
+        t.key3 = [0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff];
+        t.pad3 = [0x00; 16];
+        t.key4 = [0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff];
+    }, 16, &str_slice);
+    assert_eq!(heap_align_obj.is_some(), true);
+    assert_eq!(stack_align_obj, *(heap_align_obj.unwrap()));
+}
+
+pub fn test_alignbox_clone() {
+    let str_slice: &[align_req_t] = &[
+        align_req_t {
+            offset:offset_of!(struct_align_t, key1),
+            len:mem::size_of::<sgx_key_128bit_t>(),
+        },
+        align_req_t {
+            offset: offset_of!(struct_align_t, key2),
+            len:mem::size_of::<sgx_key_128bit_t>(),
+        },
+        align_req_t {
+            offset:offset_of!(struct_align_t, key3),
+            len:mem::size_of::<sgx_key_128bit_t>(),
+        },
+        align_req_t {
+            offset: offset_of!(struct_align_t, key4),
+            len:mem::size_of::<sgx_key_128bit_t>(),
+        }
+    ];
+    let heap_align_obj = AlignBox::<struct_align_t>::heap_init_with_req(|mut t| {
+        t.key1 = [0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff];
+        t.pad1 = [0x00; 16];
+        t.key2 = [0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff];
+        t.pad2 = [0x00; 16];
+        t.key3 = [0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff];
+        t.pad3 = [0x00; 16];
+        t.key4 = [0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff];
+    }, 16, &str_slice);
+    assert_eq!(heap_align_obj.is_some(), true);
+    let align_box_clone = heap_align_obj.clone();
+   assert_eq!(*align_box_clone.unwrap(), *heap_align_obj.unwrap());
+}
+
+pub fn test_alignbox_clonefrom() {
+    let str_slice: &[align_req_t] = &[
+        align_req_t {
+            offset:offset_of!(struct_align_t, key1),
+            len:mem::size_of::<sgx_key_128bit_t>(),
+        },
+        align_req_t {
+            offset: offset_of!(struct_align_t, key2),
+            len:mem::size_of::<sgx_key_128bit_t>(),
+        },
+        align_req_t {
+            offset:offset_of!(struct_align_t, key3),
+            len:mem::size_of::<sgx_key_128bit_t>(),
+        },
+        align_req_t {
+            offset: offset_of!(struct_align_t, key4),
+            len:mem::size_of::<sgx_key_128bit_t>(),
+        }
+    ];
+    let heap_align_obj = AlignBox::<struct_align_t>::heap_init_with_req(|mut t| {
+        t.key1 = [0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff];
+        t.pad1 = [0x00; 16];
+        t.key2 = [0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff];
+        t.pad2 = [0x00; 16];
+        t.key3 = [0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff];
+        t.pad3 = [0x00; 16];
+        t.key4 = [0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff];
+    }, 16, &str_slice);
+    assert_eq!(heap_align_obj.is_some(), true);
+
+    let mut heap_align_zero_obj = AlignBox::<struct_align_t>::new_with_req(16, &str_slice);
+    assert_eq!(heap_align_zero_obj.is_some(), true);
+    heap_align_zero_obj.clone_from(&heap_align_obj);
+    assert_eq!(*(heap_align_zero_obj.unwrap()), *(heap_align_obj.unwrap()));
+}
+
+pub fn test_alignbox_clonefrom_no_eq_size() {
+    let str_slice: &[align_req_t] = &[
+        align_req_t {
+            offset:offset_of!(struct_align_t, key1),
+            len:mem::size_of::<sgx_key_128bit_t>(),
+        },
+        align_req_t {
+            offset: offset_of!(struct_align_t, key2),
+            len:mem::size_of::<sgx_key_128bit_t>(),
+        },
+        align_req_t {
+            offset:offset_of!(struct_align_t, key3),
+            len:mem::size_of::<sgx_key_128bit_t>(),
+        },
+        align_req_t {
+            offset: offset_of!(struct_align_t, key4),
+            len:mem::size_of::<sgx_key_128bit_t>(),
+        }
+    ];
+    let heap_align_obj = AlignBox::<struct_align_t>::heap_init_with_req(|mut t| {
+        t.key1 = [0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff];
+        t.pad1 = [0x00; 16];
+        t.key2 = [0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff];
+        t.pad2 = [0x00; 16];
+        t.key3 = [0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff];
+        t.pad3 = [0x00; 16];
+        t.key4 = [0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff];
+    }, 16, &str_slice);
+    assert_eq!(heap_align_obj.is_some(), true);
+
+    let mut heap_align_zero_obj = AlignBox::<struct_align_t>::new_with_req(1, &str_slice);
+    assert_eq!(heap_align_zero_obj.is_some(), true);
+    heap_align_zero_obj.clone_from(&heap_align_obj);
+    assert_eq!(*(heap_align_zero_obj.unwrap()), *(heap_align_obj.unwrap()));
+}
diff --git a/sgx_tcrypto/src/crypto.rs b/sgx_tcrypto/src/crypto.rs
index 3419e2c..92872e2 100644
--- a/sgx_tcrypto/src/crypto.rs
+++ b/sgx_tcrypto/src/crypto.rs
@@ -119,7 +119,6 @@ pub fn rsgx_sha256_slice<T>(src: &[T]) -> SgxResult<sgx_sha256_hash_t>
 }
 
 fn rsgx_sha256_init(sha_handle: &mut sgx_sha_state_handle_t) -> sgx_status_t {
-
     unsafe {
         sgx_sha256_init(sha_handle as * mut sgx_sha_state_handle_t)
     }
@@ -157,12 +156,10 @@ fn rsgx_sha256_update_slice<T>(src: &[T], sha_handle: sgx_sha_state_handle_t) ->
 }
 
 fn rsgx_sha256_get_hash(sha_handle: sgx_sha_state_handle_t, hash: &mut sgx_sha256_hash_t) -> sgx_status_t {
-
     unsafe { sgx_sha256_get_hash(sha_handle, hash as * mut sgx_sha256_hash_t) }
 }
 
 fn rsgx_sha256_close(sha_handle: sgx_sha_state_handle_t) -> sgx_status_t {
-
      unsafe { sgx_sha256_close(sha_handle) }
 }
 
@@ -205,7 +202,6 @@ pub fn rsgx_sha1_slice<T>(src: &[T]) -> SgxResult<sgx_sha1_hash_t>
 }
 
 fn rsgx_sha1_init(sha_handle: &mut sgx_sha_state_handle_t) -> sgx_status_t {
-
     unsafe {
         sgx_sha1_init(sha_handle as * mut sgx_sha_state_handle_t)
     }
@@ -243,12 +239,10 @@ fn rsgx_sha1_update_slice<T>(src: &[T], sha_handle: sgx_sha_state_handle_t) -> s
 }
 
 fn rsgx_sha1_get_hash(sha_handle: sgx_sha_state_handle_t, hash: &mut sgx_sha1_hash_t) -> sgx_status_t {
-
     unsafe { sgx_sha1_get_hash(sha_handle, hash as * mut sgx_sha1_hash_t) }
 }
 
 fn rsgx_sha1_close(sha_handle: sgx_sha_state_handle_t) -> sgx_status_t {
-
      unsafe { sgx_sha1_close(sha_handle) }
 }
 
@@ -309,7 +303,6 @@ impl SgxShaHandle {
     /// The SHA256 state is not initialized properly due to an internal cryptography library failure.
     ///
     pub fn init(&self) -> SgxError {
-
         if self.initflag.get() {
             return Ok(());
         }
@@ -425,7 +418,6 @@ impl SgxShaHandle {
     /// The SHA256 state passed in is likely problematic causing an internal cryptography library failure.
     ///
     pub fn get_hash(&self) -> SgxResult<sgx_sha256_hash_t> {
-
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
@@ -457,7 +449,6 @@ impl SgxShaHandle {
     /// The input handle is invalid.
     ///
     pub fn close(&self) -> SgxError {
-
         if !self.initflag.get() {
             return Ok(());
         }
@@ -513,7 +504,6 @@ impl SgxSha1Handle {
     }
 
     pub fn init(&self) -> SgxError {
-
         if self.initflag.get() {
             return Ok(());
         }
@@ -557,7 +547,6 @@ impl SgxSha1Handle {
     }
 
     pub fn get_hash(&self) -> SgxResult<sgx_sha1_hash_t> {
-
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
@@ -571,7 +560,6 @@ impl SgxSha1Handle {
     }
 
     pub fn close(&self) -> SgxError {
-
         if !self.initflag.get() {
             return Ok(());
         }
@@ -819,7 +807,6 @@ pub fn rsgx_rijndael128GCM_decrypt(key: &sgx_aes_gcm_128bit_key_t,
                                    aad: &[u8],
                                    mac: &sgx_aes_gcm_128bit_tag_t,
                                    dst: &mut [u8]) -> SgxError {
-
     let src_len = src.len();
     if src_len > u32::max_value() as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
@@ -933,6 +920,30 @@ pub fn rsgx_rijndael128_cmac_msg<T>(key: &sgx_cmac_128bit_key_t, src: &T) -> Sgx
     }
 }
 
+pub fn rsgx_rijndael128_align_cmac_msg<T>(key: &sgx_cmac_128bit_key_t, src: &T) -> SgxResult<sgx_align_mac_128bit_t>
+    where T: Copy + ContiguousMemory {
+
+    let size = mem::size_of::<T>();
+    if size == 0 {
+        return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
+    }
+    if size > u32::max_value() as usize {
+        return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
+    }
+
+    let mut align_mac = sgx_align_mac_128bit_t::default();
+    let ret = unsafe {
+        sgx_rijndael128_cmac_msg(key as * const sgx_cmac_128bit_key_t,
+                                 src as * const _ as * const u8,
+                                 size as u32,
+                                 &mut align_mac.mac as * mut sgx_cmac_128bit_tag_t)
+    };
+    match ret {
+        sgx_status_t::SGX_SUCCESS => Ok(align_mac),
+        _ => Err(ret),
+    }
+}
+
 ///
 /// The rsgx_rijndael128_cmac_slice function performs a standard 128bit CMAC hash over the input data buffer.
 ///
@@ -960,8 +971,31 @@ pub fn rsgx_rijndael128_cmac_slice<T>(key: &sgx_cmac_128bit_key_t, src: &[T]) ->
     }
 }
 
-fn rsgx_cmac128_init(key: &sgx_cmac_128bit_key_t, cmac_handle: &mut sgx_cmac_state_handle_t) -> sgx_status_t {
+pub fn rsgx_rijndael128_align_cmac_slice<T>(key: &sgx_cmac_128bit_key_t, src: &[T]) -> SgxResult<sgx_align_mac_128bit_t>
+    where T: Copy + ContiguousMemory {
+
+    let size = mem::size_of_val(src);
+    if size == 0 {
+        return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
+    }
+    if size > u32::max_value() as usize {
+        return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
+    }
 
+    let mut align_mac = sgx_align_mac_128bit_t::default();
+    let ret = unsafe {
+        sgx_rijndael128_cmac_msg(key as * const sgx_cmac_128bit_key_t,
+                                 src.as_ptr() as * const u8,
+                                 size as u32,
+                                 &mut align_mac.mac as * mut sgx_cmac_128bit_tag_t)
+    };
+    match ret {
+        sgx_status_t::SGX_SUCCESS => Ok(align_mac),
+        _ => Err(ret),
+    }
+}
+
+fn rsgx_cmac128_init(key: &sgx_cmac_128bit_key_t, cmac_handle: &mut sgx_cmac_state_handle_t) -> sgx_status_t {
     unsafe {
         sgx_cmac128_init(key as * const sgx_cmac_128bit_key_t,
                          cmac_handle as * mut sgx_cmac_state_handle_t)
@@ -999,12 +1033,10 @@ fn rsgx_cmac128_update_slice<T>(src: &[T], cmac_handle: sgx_cmac_state_handle_t)
 }
 
 fn rsgx_cmac128_final(cmac_handle: sgx_cmac_state_handle_t, hash: &mut sgx_cmac_128bit_tag_t) -> sgx_status_t {
-
     unsafe { sgx_cmac128_final(cmac_handle, hash as * mut sgx_cmac_128bit_tag_t) }
 }
 
 fn rsgx_cmac128_close(cmac_handle: sgx_cmac_state_handle_t) -> sgx_status_t {
-
     unsafe { sgx_cmac128_close(cmac_handle) }
 }
 
@@ -1073,7 +1105,6 @@ impl SgxCmacHandle {
     /// An internal cryptography library failure occurred.
     ///
     pub fn init(&self, key: &sgx_cmac_128bit_key_t) -> SgxError {
-
         if self.initflag.get() {
             return Ok(());
         }
@@ -1194,7 +1225,6 @@ impl SgxCmacHandle {
     /// The CMAC state passed in is likely problematic causing an internal cryptography library failure.
     ///
     pub fn get_hash(&self) -> SgxResult<sgx_cmac_128bit_tag_t> {
-
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
@@ -1207,6 +1237,19 @@ impl SgxCmacHandle {
         }
     }
 
+    pub fn get_align_hash(&self) -> SgxResult<sgx_align_mac_128bit_t> {
+        if !self.initflag.get() {
+            return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
+        }
+
+        let mut align_hash = sgx_align_mac_128bit_t::default();
+        let ret = rsgx_cmac128_final(*self.handle.borrow(), &mut align_hash.mac);
+        match ret {
+            sgx_status_t::SGX_SUCCESS => Ok(align_hash),
+            _ => Err(ret),
+        }
+    }
+
     ///
     /// close cleans up and deallocates the CMAC algorithm context state that was allocated in function init.
     ///
@@ -1226,7 +1269,6 @@ impl SgxCmacHandle {
     /// The input handle is invalid.
     ///
     pub fn close(&self) -> SgxError {
-
         if !self.initflag.get() {
             return Ok(());
         }
@@ -1292,6 +1334,32 @@ pub fn rsgx_hmac_sha256_msg<T>(key: &sgx_hmac_256bit_key_t, src: &T) -> SgxResul
     }
 }
 
+pub fn rsgx_align_hmac_sha256_msg<T>(key: &sgx_hmac_256bit_key_t, src: &T) -> SgxResult<sgx_align_mac_256bit_t>
+    where T: Copy + ContiguousMemory {
+
+    let size = mem::size_of::<T>();
+    if size == 0 {
+        return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
+    }
+    if size > u32::max_value() as usize {
+        return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
+    }
+
+    let mut align_mac = sgx_align_mac_256bit_t::default();
+    let ret = unsafe {
+        sgx_hmac_sha256_msg(src as * const _ as * const u8,
+                            size as i32,
+                            key as * const u8,
+                            SGX_HMAC256_KEY_SIZE as i32,
+                            &mut align_mac.mac as * mut sgx_hmac_256bit_tag_t as * mut u8,
+                            SGX_HMAC256_MAC_SIZE as i32)
+    };
+    match ret {
+        sgx_status_t::SGX_SUCCESS => Ok(align_mac),
+        _ => Err(ret),
+    }
+}
+
 pub fn rsgx_hmac_sha256_slice<T>(key: &sgx_hmac_256bit_key_t, src: &[T]) -> SgxResult<sgx_hmac_256bit_tag_t>
     where T: Copy + ContiguousMemory {
 
@@ -1318,8 +1386,33 @@ pub fn rsgx_hmac_sha256_slice<T>(key: &sgx_hmac_256bit_key_t, src: &[T]) -> SgxR
     }
 }
 
-fn rsgx_hmac256_init(key: &sgx_hmac_256bit_key_t, hmac_handle: &mut sgx_hmac_state_handle_t) -> sgx_status_t {
+pub fn rsgx_align_hmac_sha256_slice<T>(key: &sgx_hmac_256bit_key_t, src: &[T]) -> SgxResult<sgx_align_mac_256bit_t>
+    where T: Copy + ContiguousMemory {
+
+    let size = mem::size_of_val(src);
+    if size == 0 {
+        return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
+    }
+    if size > u32::max_value() as usize {
+        return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
+    }
+
+    let mut align_mac = sgx_align_mac_256bit_t::default();
+    let ret = unsafe {
+        sgx_hmac_sha256_msg(src.as_ptr() as * const u8,
+                            size as i32,
+                            key as * const u8,
+                            SGX_HMAC256_KEY_SIZE as i32,
+                            &mut align_mac.mac as * mut sgx_hmac_256bit_tag_t as * mut u8,
+                            SGX_HMAC256_MAC_SIZE as i32)
+    };
+    match ret {
+        sgx_status_t::SGX_SUCCESS => Ok(align_mac),
+        _ => Err(ret),
+    }
+}
 
+fn rsgx_hmac256_init(key: &sgx_hmac_256bit_key_t, hmac_handle: &mut sgx_hmac_state_handle_t) -> sgx_status_t {
     unsafe {
         sgx_hmac256_init(key as * const sgx_hmac_256bit_key_t as * const u8,
                          SGX_HMAC256_KEY_SIZE as i32,
@@ -1358,7 +1451,6 @@ fn rsgx_hmac256_update_slice<T>(src: &[T], hmac_handle: sgx_hmac_state_handle_t)
 }
 
 fn rsgx_hmac256_final(hmac_handle: sgx_hmac_state_handle_t, hash: &mut sgx_hmac_256bit_tag_t) -> sgx_status_t {
-
     unsafe {
         sgx_hmac256_final(hash as * mut sgx_hmac_256bit_tag_t as * mut u8,
                           SGX_HMAC256_MAC_SIZE as i32,
@@ -1367,7 +1459,6 @@ fn rsgx_hmac256_final(hmac_handle: sgx_hmac_state_handle_t, hash: &mut sgx_hmac_
 }
 
 fn rsgx_hmac256_close(hmac_handle: sgx_hmac_state_handle_t) -> sgx_status_t {
-
     unsafe { sgx_hmac256_close(hmac_handle) }
 }
 
@@ -1386,7 +1477,6 @@ impl SgxHmacHandle {
     }
 
     pub fn init(&self, key: &sgx_hmac_256bit_key_t) -> SgxError {
-
         if self.initflag.get() {
             return Ok(());
         }
@@ -1430,7 +1520,6 @@ impl SgxHmacHandle {
     }
 
     pub fn get_hash(&self) -> SgxResult<sgx_hmac_256bit_tag_t> {
-
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
@@ -1443,8 +1532,20 @@ impl SgxHmacHandle {
         }
     }
 
-    pub fn close(&self) -> SgxError {
+    pub fn get_align_hash(&self) -> SgxResult<sgx_align_mac_256bit_t> {
+        if !self.initflag.get() {
+            return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
+        }
 
+        let mut align_hash = sgx_align_mac_256bit_t::default();
+        let ret = rsgx_hmac256_final(*self.handle.borrow(), &mut align_hash.mac);
+        match ret {
+            sgx_status_t::SGX_SUCCESS => Ok(align_hash),
+            _ => Err(ret),
+        }
+    }
+
+    pub fn close(&self) -> SgxError {
         if !self.initflag.get() {
             return Ok(());
         }
@@ -1671,12 +1772,10 @@ pub fn rsgx_aes_ctr_decrypt(key: &sgx_aes_ctr_128bit_key_t,
 }
 
 fn rsgx_ecc256_open_context(ecc_handle: &mut sgx_ecc_state_handle_t) -> sgx_status_t {
-
     unsafe { sgx_ecc256_open_context(ecc_handle as * mut _ as * mut sgx_ecc_state_handle_t) }
 }
 
 fn rsgx_ecc256_close_context(ecc_handle: sgx_ecc_state_handle_t) -> sgx_status_t {
-
     unsafe { sgx_ecc256_close_context(ecc_handle) }
 }
 
@@ -1691,7 +1790,6 @@ fn rsgx_ecc256_create_key_pair(private: &mut sgx_ec256_private_t,
 }
 
 fn rsgx_ecc256_check_point(point: &sgx_ec256_public_t, ecc_handle: sgx_ecc_state_handle_t, valid: &mut i32) -> sgx_status_t {
-
     unsafe { sgx_ecc256_check_point(point as * const sgx_ec256_public_t, ecc_handle, valid as * mut i32) }
 }
 
@@ -1712,7 +1810,6 @@ fn rsgx_ecc256_compute_shared_dhkey512(private_b: &sgx_ec256_private_t,
                                        public_ga: &sgx_ec256_public_t,
                                        shared_key: &mut sgx_ec256_dh_shared512_t,
                                        ecc_handle: sgx_ecc_state_handle_t) -> sgx_status_t {
-
     unsafe {
         sgx_ecc256_compute_shared_dhkey512(private_b as * const _ as * mut sgx_ec256_private_t,
                                            public_ga as * const _ as * mut sgx_ec256_public_t,
@@ -1784,7 +1881,6 @@ fn rsgx_ecdsa_verify_msg<T>(data: &T,
     }
 
     unsafe {
-
         let mut verify: u8 = 0;
         let ret = sgx_ecdsa_verify(data as * const _ as * const u8,
                                    size as u32,
@@ -1819,7 +1915,6 @@ fn rsgx_ecdsa_verify_slice<T>(data: &[T],
     }
 
     unsafe {
-
         let mut verify: u8 = 0;
         let ret = sgx_ecdsa_verify(data.as_ptr() as * const _ as * const u8,
                                    size as u32,
@@ -1843,9 +1938,7 @@ fn rsgx_ecdsa_verify_hash(hash: &sgx_sha256_hash_t,
                           signature: &sgx_ec256_signature_t,
                           result: &mut sgx_generic_ecresult_t,
                           ecc_handle: sgx_ecc_state_handle_t) -> sgx_status_t {
-
     unsafe {
-
         let mut verify: u8 = 0;
         let ret = sgx_ecdsa_verify_hash(hash as * const sgx_sha256_hash_t as * const u8,
                                         public as * const sgx_ec256_public_t,
@@ -1945,7 +2038,6 @@ impl SgxEccHandle {
     /// The ECC context state was not initialized properly due to an internal cryptography library failure.
     ///
     pub fn open(&self) -> SgxError {
-
         if self.initflag.get() {
             return Ok(());
         }
@@ -2016,7 +2108,6 @@ impl SgxEccHandle {
     /// The key creation process failed due to an internal cryptography library failure.
     ///
     pub fn create_key_pair(&self) -> SgxResult<(sgx_ec256_private_t, sgx_ec256_public_t)> {
-
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
@@ -2031,6 +2122,21 @@ impl SgxEccHandle {
         }
     }
 
+    pub fn create_align_key_pair(&self) -> SgxResult<(sgx_align_ec256_private_t, sgx_ec256_public_t)> {
+        if !self.initflag.get() {
+            return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
+        }
+
+        let mut private = sgx_align_ec256_private_t::default();
+        let mut public = sgx_ec256_public_t::default();
+        let ret = rsgx_ecc256_create_key_pair(&mut private.key, &mut public, *self.handle.borrow());
+
+        match ret {
+            sgx_status_t::SGX_SUCCESS => Ok((private, public)),
+            _ => Err(ret),
+        }
+    }
+
     ///
     /// check_point checks whether the input point is a valid point on the ECC curve for the given cryptographic system.
     ///
@@ -2079,7 +2185,6 @@ impl SgxEccHandle {
     /// An internal cryptography library failure occurred.
     ///
     pub fn check_point(&self, point: &sgx_ec256_public_t) -> SgxResult<bool> {
-
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
@@ -2189,7 +2294,6 @@ impl SgxEccHandle {
     /// The key creation process failed due to an internal cryptography library failure.
     ///
     pub fn compute_shared_dhkey(&self, private_b: &sgx_ec256_private_t, public_ga: &sgx_ec256_public_t) -> SgxResult<sgx_ec256_dh_shared_t> {
-
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
@@ -2202,6 +2306,19 @@ impl SgxEccHandle {
         }
     }
 
+    pub fn compute_align_shared_dhkey(&self, private_b: &sgx_ec256_private_t, public_ga: &sgx_ec256_public_t) -> SgxResult<sgx_align_ec256_dh_shared_t> {
+        if !self.initflag.get() {
+            return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
+        }
+
+        let mut shared_key = sgx_align_ec256_dh_shared_t::default();
+        let ret = rsgx_ecc256_compute_shared_dhkey(private_b, public_ga, &mut shared_key.key, *self.handle.borrow());
+        match ret {
+            sgx_status_t::SGX_SUCCESS => Ok(shared_key),
+            _ => Err(ret),
+        }
+    }
+
     /* delete (intel sgx sdk 2.0)
     pub fn compute_shared_dhkey512(&self, private_b: &sgx_ec256_private_t, public_ga: &sgx_ec256_public_t) -> SgxResult<sgx_ec256_dh_shared512_t> {
 
@@ -2424,7 +2541,6 @@ impl SgxEccHandle {
                              hash: &sgx_sha256_hash_t,
                              public: &sgx_ec256_public_t,
                              signature: &sgx_ec256_signature_t) -> SgxResult<bool> {
-
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
@@ -2461,7 +2577,6 @@ impl SgxEccHandle {
     /// The input handle is invalid.
     ///
     pub fn close(&self) -> SgxError {
-
         if !self.initflag.get() {
             return Ok(());
         }
@@ -2730,7 +2845,6 @@ pub fn rsgx_create_rsa_key_pair(n_byte_size: i32,
                                 dmp1: &mut [u8],
                                 dmq1: &mut [u8],
                                 iqmp: &mut [u8]) -> SgxError {
-
     if (n_byte_size <= 0) || (e_byte_size <= 0) {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
@@ -2786,7 +2900,6 @@ fn rsgx_create_rsa_priv2_key(mod_size: i32,
                              dmq1: &[u8],
                              iqmp: &[u8],
                              new_pri_key: &mut sgx_rsa_key_t) -> sgx_status_t {
-
     if (mod_size <= 0) || (exp_size <= 0) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
@@ -2829,7 +2942,6 @@ fn rsgx_create_rsa_priv1_key(n_size: i32,
                             e: &[u8],
                             d: &[u8],
                             new_pri_key: &mut sgx_rsa_key_t) -> sgx_status_t {
-
     if (n_size <= 0) || (e_size <= 0) || (d_size <= 0) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
@@ -2859,7 +2971,6 @@ fn rsgx_create_rsa_pub1_key(mod_size: i32,
                            n: &[u8],
                            e: &[u8],
                            new_pub_key: &mut sgx_rsa_key_t) -> sgx_status_t {
-
     if (mod_size <= 0) || (exp_size <= 0) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
@@ -2883,7 +2994,6 @@ fn rsgx_free_rsa_key(rsa_key: sgx_rsa_key_t,
                      key_type: sgx_rsa_key_type_t,
                      mod_size: i32,
                      exp_size: i32) -> sgx_status_t {
-
     if (mod_size <= 0) || (exp_size <= 0) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
@@ -2897,7 +3007,6 @@ fn rsgx_rsa_priv_decrypt_sha256(rsa_key: sgx_rsa_key_t,
                                 out_data: &mut [u8],
                                 out_len: &mut usize,
                                 in_data: &[u8]) -> sgx_status_t {
-
     if in_data.is_empty() {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
@@ -2924,7 +3033,6 @@ fn rsgx_rsa_pub_encrypt_sha256(rsa_key: sgx_rsa_key_t,
                                out_data: &mut [u8],
                                out_len: &mut usize,
                                in_data: &[u8]) -> sgx_status_t {
-
     if in_data.is_empty() {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
@@ -2975,7 +3083,6 @@ impl SgxRsaPrivKey {
                   dmp1: &[u8],
                   dmq1: &[u8],
                   iqmp: &[u8]) -> SgxError {
-
         self.create2(mod_size, exp_size, e, p, q, dmp1, dmq1, iqmp)
     }
 
@@ -2988,7 +3095,6 @@ impl SgxRsaPrivKey {
                    dmp1: &[u8],
                    dmq1: &[u8],
                    iqmp: &[u8]) -> SgxError {
-
         if self.createflag.get() {
             return Ok(());
         }
@@ -3020,7 +3126,6 @@ impl SgxRsaPrivKey {
                    n: &[u8],
                    e: &[u8],
                    d: &[u8]) -> SgxError {
-
         if self.createflag.get() {
             return Ok(());
         }
@@ -3047,7 +3152,6 @@ impl SgxRsaPrivKey {
                           out_data: &mut [u8],
                           out_len: &mut usize,
                           in_data: &[u8]) -> SgxError {
-
         if !self.createflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
@@ -3065,7 +3169,6 @@ impl SgxRsaPrivKey {
     }
 
     pub fn free(&self) -> SgxError {
-
         if !self.createflag.get() {
             return Ok(());
         }
@@ -3128,7 +3231,6 @@ impl SgxRsaPubKey {
                   exp_size: i32,
                   n: &[u8],
                   e: &[u8]) -> SgxError {
-
         if self.createflag.get() {
             return Ok(());
         }
@@ -3153,7 +3255,6 @@ impl SgxRsaPubKey {
                           out_data: &mut [u8],
                           out_len: &mut usize,
                           in_data: &[u8]) -> SgxError {
-
         if !self.createflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
@@ -3171,7 +3272,6 @@ impl SgxRsaPubKey {
     }
 
     pub fn free(&self) -> SgxError {
-
         if !self.createflag.get() {
             return Ok(());
         }
@@ -3249,7 +3349,6 @@ impl Drop for SgxRsaPubKey {
 pub fn rsgx_calculate_ecdsa_priv_key(hash_drg: &[u8],
                                      sgx_nistp256_r_m1: &[u8],
                                      out_key: &mut [u8]) -> SgxError {
-
     if (hash_drg.is_empty()) || (hash_drg.len() > i32::max_value() as usize) {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
@@ -3268,7 +3367,6 @@ pub fn rsgx_calculate_ecdsa_priv_key(hash_drg: &[u8],
                                      out_key.as_mut_ptr(),
                                      out_key.len() as i32)
     };
-
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(()),
         _ => Err(ret),
@@ -3277,33 +3375,88 @@ pub fn rsgx_calculate_ecdsa_priv_key(hash_drg: &[u8],
 
 pub fn rsgx_ecc256_calculate_pub_from_priv(priv_key: &sgx_ec256_private_t,
                                            pub_key: &mut sgx_ec256_public_t) -> SgxError {
-
     let ret = unsafe {
         sgx_ecc256_calculate_pub_from_priv(priv_key as * const sgx_ec256_private_t,
                                            pub_key as * mut sgx_ec256_public_t)
     };
-
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(()),
         _ => Err(ret),
     }
 }
 
+pub fn rsgx_ecc256_priv_key(hash_drg: &[u8], sgx_nistp256_r_m1: &[u8]) -> SgxResult<sgx_ec256_private_t> {
+    if (hash_drg.is_empty()) || (hash_drg.len() > i32::max_value() as usize) {
+        return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
+    }
+    if (sgx_nistp256_r_m1.is_empty()) || (sgx_nistp256_r_m1.len() > i32::max_value() as usize) {
+        return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
+    }
+
+    let mut priv_key = sgx_ec256_private_t::default();
+    let ret = unsafe {
+        sgx_calculate_ecdsa_priv_key(hash_drg.as_ptr(),
+                                     hash_drg.len() as i32,
+                                     sgx_nistp256_r_m1.as_ptr(),
+                                     sgx_nistp256_r_m1.len() as i32,
+                                     &mut priv_key as * mut sgx_ec256_private_t as * mut u8,
+                                     mem::size_of::<sgx_ec256_private_t>() as i32)
+    };
+    match ret {
+        sgx_status_t::SGX_SUCCESS => Ok(priv_key),
+        _ => Err(ret),
+    }
+}
+
+pub fn rsgx_align_ecc256_priv_key(hash_drg: &[u8], sgx_nistp256_r_m1: &[u8]) -> SgxResult<sgx_align_ec256_private_t> {
+    if (hash_drg.is_empty()) || (hash_drg.len() > i32::max_value() as usize) {
+        return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
+    }
+    if (sgx_nistp256_r_m1.is_empty()) || (sgx_nistp256_r_m1.len() > i32::max_value() as usize) {
+        return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
+    }
+
+    let mut align_priv_key = sgx_align_ec256_private_t::default();
+    let ret = unsafe {
+        sgx_calculate_ecdsa_priv_key(hash_drg.as_ptr(),
+                                     hash_drg.len() as i32,
+                                     sgx_nistp256_r_m1.as_ptr(),
+                                     sgx_nistp256_r_m1.len() as i32,
+                                     &mut align_priv_key.key as * mut sgx_ec256_private_t as * mut u8,
+                                     mem::size_of::<sgx_ec256_private_t>() as i32)
+    };
+    match ret {
+        sgx_status_t::SGX_SUCCESS => Ok(align_priv_key),
+        _ => Err(ret),
+    }
+}
+
+pub fn rsgx_ecc256_pub_from_priv(priv_key: &sgx_ec256_private_t) -> SgxResult<sgx_ec256_public_t> {
+    let mut pub_key = sgx_ec256_public_t::default();
+    let ret = unsafe {
+        sgx_ecc256_calculate_pub_from_priv(priv_key as * const sgx_ec256_private_t,
+                                           &mut pub_key as * mut sgx_ec256_public_t)
+    };
+    match ret {
+        sgx_status_t::SGX_SUCCESS => Ok(pub_key),
+        _ => Err(ret),
+    }
+}
+
 fn rsgx_aes_gcm128_enc_init(key: &sgx_aes_gcm_128bit_key_t,
                             iv: &[u8],
                             aad: &[u8],
-                            aes_gcm_state: &mut sgx_aes_state_handle_t) -> SgxError {
-
+                            aes_gcm_state: &mut sgx_aes_state_handle_t) -> sgx_status_t {
     let iv_len = iv.len();
     if iv_len != SGX_AESGCM_IV_SIZE {
-        return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
+        return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
     let aad_len = aad.len();
     if aad_len > u32::max_value() as usize {
-        return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
+        return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
 
-    let ret = unsafe {
+    unsafe {
         let p_aad = if !aad.is_empty() { aad.as_ptr() } else { ptr::null() };
         sgx_aes_gcm128_enc_init(key as * const sgx_aes_gcm_128bit_key_t as * const u8,
                                 iv.as_ptr(),
@@ -3311,63 +3464,44 @@ fn rsgx_aes_gcm128_enc_init(key: &sgx_aes_gcm_128bit_key_t,
                                 p_aad,
                                 aad_len as u32,
                                 aes_gcm_state as * mut sgx_aes_state_handle_t)
-    };
-    match ret {
-        sgx_status_t::SGX_SUCCESS => Ok(()),
-        _ => Err(ret),
     }
 }
 
 fn rsgx_aes_gcm128_enc_update(src: &[u8],
                               dst: &mut [u8],
-                              aes_gcm_state: sgx_aes_state_handle_t) -> SgxError {
-
+                              aes_gcm_state: sgx_aes_state_handle_t) -> sgx_status_t {
     let src_len = src.len();
     if src_len > u32::max_value() as usize {
-        return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
+        return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
     if src_len == 0 {
-        return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
+        return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
     let dst_len = dst.len();
     if dst_len > u32::max_value() as usize {
-        return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
+        return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
     if dst_len == 0 || dst_len < src_len {
-        return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
+        return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
 
-    let ret = unsafe {
+    unsafe {
         sgx_aes_gcm128_enc_update(src.as_ptr(),
                                   src_len as u32,
                                   dst.as_mut_ptr(),
                                   aes_gcm_state)
-    };
-    match ret {
-        sgx_status_t::SGX_SUCCESS => Ok(()),
-        _ => Err(ret),
     }
 }
 
-fn rsgx_aes_gcm128_enc_get_mac(aes_gcm_state: sgx_aes_state_handle_t) -> SgxResult<sgx_aes_gcm_128bit_tag_t> {
-
-    let mut mac = sgx_aes_gcm_128bit_tag_t::default();
-    let ret = unsafe {
-        sgx_aes_gcm128_enc_get_mac(&mut mac as * mut sgx_aes_gcm_128bit_tag_t as * mut u8 , aes_gcm_state)
-    };
-    match ret {
-        sgx_status_t::SGX_SUCCESS => Ok(mac),
-        _ => Err(ret),
+fn rsgx_aes_gcm128_enc_get_mac(mac: &mut sgx_aes_gcm_128bit_tag_t,
+                               aes_gcm_state: sgx_aes_state_handle_t) -> sgx_status_t {
+    unsafe {
+        sgx_aes_gcm128_enc_get_mac(mac as * mut sgx_aes_gcm_128bit_tag_t as * mut u8, aes_gcm_state)
     }
 }
 
-fn rsgx_aes_gcm_close(aes_gcm_state: sgx_aes_state_handle_t) -> SgxError {
-
-    let ret = unsafe { sgx_aes_gcm_close(aes_gcm_state) };
-    match ret {
-        sgx_status_t::SGX_SUCCESS => Ok(()),
-        _ => Err(ret),
-    }
+fn rsgx_aes_gcm_close(aes_gcm_state: sgx_aes_state_handle_t) -> sgx_status_t {
+    unsafe { sgx_aes_gcm_close(aes_gcm_state) }
 }
 
 pub struct SgxAesHandle {
@@ -3385,31 +3519,52 @@ impl SgxAesHandle {
     }
 
     pub fn init(&self, key: &sgx_aes_gcm_128bit_key_t, iv: &[u8], aad: &[u8]) -> SgxError {
-
         if self.initflag.get() {
             return Ok(());
         }
-        rsgx_aes_gcm128_enc_init(key, iv, aad, self.handle.borrow_mut().deref_mut())
+        let ret = rsgx_aes_gcm128_enc_init(key, iv, aad, self.handle.borrow_mut().deref_mut());
+        match ret {
+            sgx_status_t::SGX_SUCCESS => Ok(()),
+            _ => Err(ret),
+        }
     }
 
     pub fn update(&self, src: &[u8], dst: &mut [u8]) -> SgxError {
-
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
-        rsgx_aes_gcm128_enc_update(src, dst, *self.handle.borrow())
+        let ret = rsgx_aes_gcm128_enc_update(src, dst, *self.handle.borrow());
+        match ret {
+            sgx_status_t::SGX_SUCCESS => Ok(()),
+            _ => Err(ret),
+        }
     }
 
     pub fn get_mac(&self) -> SgxResult<sgx_aes_gcm_128bit_tag_t> {
+        if !self.initflag.get() {
+            return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
+        }
+        let mut mac = sgx_aes_gcm_128bit_tag_t::default();
+        let ret = rsgx_aes_gcm128_enc_get_mac(&mut mac, *self.handle.borrow());
+        match ret {
+            sgx_status_t::SGX_SUCCESS => Ok(mac),
+            _ => Err(ret),
+        }
+    }
 
+    pub fn get_align_mac(&self) -> SgxResult<sgx_align_mac_128bit_t> {
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
-        rsgx_aes_gcm128_enc_get_mac(*self.handle.borrow())
+        let mut align_mac = sgx_align_mac_128bit_t::default();
+        let ret = rsgx_aes_gcm128_enc_get_mac(&mut align_mac.mac, *self.handle.borrow());
+        match ret {
+            sgx_status_t::SGX_SUCCESS => Ok(align_mac),
+            _ => Err(ret),
+        }
     }
 
     pub fn close(&self) -> SgxError {
-
         if !self.initflag.get() {
             return Ok(());
         }
@@ -3417,17 +3572,19 @@ impl SgxAesHandle {
         let ret = {
             let handle = *self.handle.borrow();
             if handle.is_null() {
-                Ok(())
+                sgx_status_t::SGX_SUCCESS
             } else {
                 rsgx_aes_gcm_close(handle)
             }
         };
-
-        if ret.is_ok() {
-            self.initflag.set(false);
-            *self.handle.borrow_mut() = ptr::null_mut();
+        match ret {
+            sgx_status_t::SGX_SUCCESS => {
+                self.initflag.set(false);
+                *self.handle.borrow_mut() = ptr::null_mut();
+                Ok(())
+            },
+            _ => Err(ret),
         }
-        ret
     }
 }
 
diff --git a/sgx_tdh/src/dh.rs b/sgx_tdh/src/dh.rs
index 4e3db0a..2f1f04b 100644
--- a/sgx_tdh/src/dh.rs
+++ b/sgx_tdh/src/dh.rs
@@ -213,20 +213,20 @@ enum SgxDhSessionState {
 #[derive(Copy, Clone)]
 pub struct SgxDhResponder {
     state: SgxDhSessionState,
-    prv_key: sgx_ec256_private_t,
+    prv_key: sgx_align_ec256_private_t,
     pub_key: sgx_ec256_public_t,
-    smk_aek: sgx_key_128bit_t,
-    shared_key: sgx_ec256_dh_shared_t,
+    smk_aek: sgx_align_key_128bit_t,
+    shared_key: sgx_align_ec256_dh_shared_t,
 }
 
 impl Default for SgxDhResponder {
     fn default() -> Self {
         SgxDhResponder {
            state: SgxDhSessionState::SGX_DH_SESSION_STATE_RESET,
-           prv_key: sgx_ec256_private_t::default(),
+           prv_key: sgx_align_ec256_private_t::default(),
            pub_key: sgx_ec256_public_t::default(),
-           smk_aek: sgx_key_128bit_t::default(),
-           shared_key: sgx_ec256_dh_shared_t::default(),
+           smk_aek: sgx_align_key_128bit_t::default(),
+           shared_key: sgx_align_ec256_dh_shared_t::default(),
         }
     }
 }
@@ -408,9 +408,9 @@ impl SgxDhResponder {
 
         let ecc_state = SgxEccHandle::new();
         ecc_state.open().map_err(|ret| self.set_error(ret))?;
-        self.shared_key = ecc_state.compute_shared_dhkey(&self.prv_key, &msg2.g_b).map_err(|ret| self.set_error(ret))?;
+        self.shared_key = ecc_state.compute_align_shared_dhkey(&self.prv_key.key, &msg2.g_b).map_err(|ret| self.set_error(ret))?;
 
-        self.smk_aek = derive_key(&self.shared_key, &EC_SMK_LABEL).map_err(|ret| self.set_error(ret))?;
+        self.smk_aek = derive_key(&self.shared_key.key, &EC_SMK_LABEL).map_err(|ret| self.set_error(ret))?;
 
         #[cfg(feature = "use_lav2")]
         self.lav2_verify_message2(msg2).map_err(|ret| self.set_error(ret))?;
@@ -428,8 +428,8 @@ impl SgxDhResponder {
         #[cfg(not(feature = "use_lav2"))]
         self.dh_generate_message3(msg2, msg3).map_err(|ret| self.set_error(ret))?;
 
-        * aek = derive_key(&self.shared_key, &EC_AEK_LABEL).map_err(|ret| self.set_error(ret))?;
-
+        let align_aek = derive_key(&self.shared_key.key, &EC_AEK_LABEL).map_err(|ret| self.set_error(ret))?;
+        *aek = align_aek.key;
         *self = Self::default();
         self.state = SgxDhSessionState::SGX_DH_SESSION_ACTIVE;
 
@@ -449,7 +449,7 @@ impl SgxDhResponder {
 
         let ecc_state = SgxEccHandle::new();
         ecc_state.open()?;
-        let (prv_key, pub_key) = ecc_state.create_key_pair()?;
+        let (prv_key, pub_key) = ecc_state.create_align_key_pair()?;
 
         self.prv_key = prv_key;
         self.pub_key = pub_key;
@@ -469,7 +469,7 @@ impl SgxDhResponder {
         }
 
         let report = msg2.report;
-        let data_mac = rsgx_rijndael128_cmac_msg(&self.smk_aek, &report)?;
+        let data_mac = rsgx_rijndael128_cmac_msg(&self.smk_aek.key, &report)?;
         if !data_mac.consttime_memeq(&msg2.cmac) {
             return Err(sgx_status_t::SGX_ERROR_MAC_MISMATCH);
         }
@@ -502,7 +502,7 @@ impl SgxDhResponder {
         report.body.report_data.d[..SGX_SHA256_HASH_SIZE].copy_from_slice(&msg_hash);
 
         rsgx_verify_report(&report)?;
-        let data_mac = rsgx_rijndael128_cmac_msg(&self.smk_aek, &msg2.g_b)?;
+        let data_mac = rsgx_rijndael128_cmac_msg(&self.smk_aek.key, &msg2.g_b)?;
         if !data_mac.consttime_memeq(&msg2.cmac) {
             return Err(sgx_status_t::SGX_ERROR_MAC_MISMATCH);
         }
@@ -536,7 +536,7 @@ impl SgxDhResponder {
 
         let add_prop_len = msg3.msg3_body.additional_prop.len() as u32;
         let cmac_handle = SgxCmacHandle::new();
-        cmac_handle.init(&self.smk_aek)?;
+        cmac_handle.init(&self.smk_aek.key)?;
         cmac_handle.update_msg(&msg3.msg3_body.report)?;
         cmac_handle.update_msg(&add_prop_len)?;
         if add_prop_len > 0 {
@@ -568,7 +568,7 @@ impl SgxDhResponder {
         msg3.msg3_body.report = rsgx_create_report(&target, &report_data)?;
 
         let cmac_handle = SgxCmacHandle::new();
-        cmac_handle.init(&self.smk_aek)?;
+        cmac_handle.init(&self.smk_aek.key)?;
         if msg3.msg3_body.additional_prop.len() > 0 {
             cmac_handle.update_slice(&msg3.msg3_body.additional_prop)?;
         }
@@ -594,20 +594,20 @@ impl SgxDhResponder {
 #[derive(Copy, Clone)]
 pub struct SgxDhInitiator {
     state: SgxDhSessionState,
-    smk_aek: sgx_key_128bit_t,
+    smk_aek: sgx_align_key_128bit_t,
     pub_key: sgx_ec256_public_t,
     peer_pub_key: sgx_ec256_public_t,
-    shared_key: sgx_ec256_dh_shared_t,
+    shared_key: sgx_align_ec256_dh_shared_t,
 }
 
 impl Default for SgxDhInitiator {
     fn default() -> Self {
         SgxDhInitiator {
            state: SgxDhSessionState::SGX_DH_SESSION_INITIATOR_WAIT_M1,
-           smk_aek: sgx_key_128bit_t::default(),
+           smk_aek: sgx_align_key_128bit_t::default(),
            pub_key: sgx_ec256_public_t::default(),
            peer_pub_key: sgx_ec256_public_t::default(),
-           shared_key: sgx_ec256_dh_shared_t::default(),
+           shared_key: sgx_align_ec256_dh_shared_t::default(),
         }
     }
 }
@@ -686,12 +686,12 @@ impl SgxDhInitiator {
 
         let ecc_state = SgxEccHandle::new();
         ecc_state.open().map_err(|ret| self.set_error(ret))?;
-        let (mut prv_key, pub_key) = ecc_state.create_key_pair().map_err(|ret| self.set_error(ret))?;
-        self.shared_key = ecc_state.compute_shared_dhkey(&prv_key, &msg1.g_a).map_err(|ret| self.set_error(ret))?;
+        let (mut prv_key, pub_key) = ecc_state.create_align_key_pair().map_err(|ret| self.set_error(ret))?;
+        self.shared_key = ecc_state.compute_align_shared_dhkey(&prv_key.key, &msg1.g_a).map_err(|ret| self.set_error(ret))?;
 
-        prv_key = sgx_ec256_private_t::default();
+        prv_key = sgx_align_ec256_private_t::default();
         self.pub_key = pub_key;
-        self.smk_aek = derive_key(&self.shared_key, &EC_SMK_LABEL).map_err(|ret| self.set_error(ret))?;
+        self.smk_aek = derive_key(&self.shared_key.key, &EC_SMK_LABEL).map_err(|ret| self.set_error(ret))?;
 
         #[cfg(feature = "use_lav2")]
         self.lav2_generate_message2(msg1, msg2).map_err(|ret| self.set_error(ret))?;
@@ -797,7 +797,8 @@ impl SgxDhInitiator {
         #[cfg(not(feature = "use_lav2"))]
         self.dh_verify_message3(msg3).map_err(|ret| self.set_error(ret))?;
 
-        * aek = derive_key(&self.shared_key, &EC_AEK_LABEL).map_err(|ret| self.set_error(ret))?;
+        let align_aek = derive_key(&self.shared_key.key, &EC_AEK_LABEL).map_err(|ret| self.set_error(ret))?;
+        *aek = align_aek.key;
 
         *self = Self::default();
         self.state = SgxDhSessionState::SGX_DH_SESSION_ACTIVE;
@@ -832,7 +833,7 @@ impl SgxDhInitiator {
         let target = msg1.target;
         msg2.report = rsgx_create_report(&target, &report_data)?;
         let report = msg2.report;
-        msg2.cmac = rsgx_rijndael128_cmac_msg(&self.smk_aek, &report)?;
+        msg2.cmac = rsgx_rijndael128_cmac_msg(&self.smk_aek.key, &report)?;
 
         Ok(())
     }
@@ -856,7 +857,7 @@ impl SgxDhInitiator {
         msg2.report = rsgx_create_report(&target, &report_data)?;
         // Replace report_data with proto_spec
         unsafe {msg2.report.body.report_data = SGX_LAV2_PROTO_SPEC.to_report_data();}
-        msg2.cmac = rsgx_rijndael128_cmac_msg(&self.smk_aek, &msg2.g_b)?;
+        msg2.cmac = rsgx_rijndael128_cmac_msg(&self.smk_aek.key, &msg2.g_b)?;
 
         Ok(())
     }
@@ -866,7 +867,7 @@ impl SgxDhInitiator {
         let add_prop_len = msg3.msg3_body.additional_prop.len() as u32;
 
         let cmac_handle = SgxCmacHandle::new();
-        cmac_handle.init(&self.smk_aek)?;
+        cmac_handle.init(&self.smk_aek.key)?;
         cmac_handle.update_msg(&msg3.msg3_body.report)?;
         cmac_handle.update_msg(&add_prop_len)?;
         if add_prop_len > 0 {
@@ -913,7 +914,7 @@ impl SgxDhInitiator {
         rsgx_verify_report(&report)?;
 
         let cmac_handle = SgxCmacHandle::new();
-        cmac_handle.init(&self.smk_aek)?;
+        cmac_handle.init(&self.smk_aek.key)?;
         if msg3.msg3_body.additional_prop.len() > 0 {
             cmac_handle.update_slice(&msg3.msg3_body.additional_prop)?;
         }
diff --git a/sgx_tdh/src/ecp.rs b/sgx_tdh/src/ecp.rs
index 1a5f362..04d96e8 100644
--- a/sgx_tdh/src/ecp.rs
+++ b/sgx_tdh/src/ecp.rs
@@ -37,7 +37,7 @@ pub const EC_DERIVATION_BUFFER_SIZE: usize = 7;
 
 #[allow(clippy::trivially_copy_pass_by_ref)]
 pub fn derive_key(shared_key: &sgx_ec256_dh_shared_t,
-                  label: &[u8; EC_LABEL_LENGTH]) -> SgxResult<sgx_ec_key_128bit_t> {
+                  label: &[u8; EC_LABEL_LENGTH]) -> SgxResult<sgx_align_key_128bit_t> {
 
     let cmac_key = sgx_cmac_128bit_key_t::default();
     let mut key_derive_key = rsgx_rijndael128_cmac_msg(&cmac_key, shared_key).map_err(set_error)?;
@@ -52,13 +52,18 @@ pub fn derive_key(shared_key: &sgx_ec256_dh_shared_t,
     derivation_buffer[5] = 0x80;
     derivation_buffer[6] = 0x00;
 
-    let result = rsgx_rijndael128_cmac_slice(&key_derive_key, &derivation_buffer).map_err(set_error);
+    let result = rsgx_rijndael128_align_cmac_slice(&key_derive_key, &derivation_buffer)
+        .map(|align_mac| {
+            let mut align_key = sgx_align_key_128bit_t::default();
+            align_key.key = align_mac.mac;
+            align_key
+        })
+        .map_err(set_error);
     key_derive_key = Default::default();
     result
 }
 
 fn set_error(sgx_ret: sgx_status_t) -> sgx_status_t {
-
     match sgx_ret {
         sgx_status_t::SGX_ERROR_OUT_OF_MEMORY => sgx_status_t::SGX_ERROR_OUT_OF_MEMORY,
         _ => sgx_status_t::SGX_ERROR_UNEXPECTED,
diff --git a/sgx_tprotected_fs/src/fs.rs b/sgx_tprotected_fs/src/fs.rs
index 154d67d..100baf2 100644
--- a/sgx_tprotected_fs/src/fs.rs
+++ b/sgx_tprotected_fs/src/fs.rs
@@ -38,7 +38,6 @@ fn max_len() -> usize {
 }
 
 unsafe fn rsgx_fopen(filename: &CStr, mode: &CStr, key: &sgx_key_128bit_t) -> SysResult<SGX_FILE> {
-
     let file = sgx_fopen(filename.as_ptr(), mode.as_ptr(), key as * const sgx_key_128bit_t);
     if file.is_null() {
         Err(errno())
@@ -48,7 +47,6 @@ unsafe fn rsgx_fopen(filename: &CStr, mode: &CStr, key: &sgx_key_128bit_t) -> Sy
 }
 
 unsafe fn rsgx_fopen_auto_key(filename: &CStr, mode: &CStr) -> SysResult<SGX_FILE> {
-
     let file = sgx_fopen_auto_key(filename.as_ptr(), mode.as_ptr());
     if file.is_null() {
         Err(errno())
@@ -58,7 +56,6 @@ unsafe fn rsgx_fopen_auto_key(filename: &CStr, mode: &CStr) -> SysResult<SGX_FIL
 }
 
 unsafe fn rsgx_fwrite(stream: SGX_FILE, buf: &[u8]) -> SysResult<usize> {
-
     if stream.is_null() || buf.is_empty() {
         return Err(libc::EINVAL);
     }
@@ -73,7 +70,6 @@ unsafe fn rsgx_fwrite(stream: SGX_FILE, buf: &[u8]) -> SysResult<usize> {
 }
 
 unsafe fn rsgx_fread(stream: SGX_FILE, buf: &mut [u8]) -> SysResult<usize> {
-
     if stream.is_null() || buf.is_empty() {
         return Err(libc::EINVAL);
     }
@@ -95,7 +91,6 @@ unsafe fn rsgx_fread(stream: SGX_FILE, buf: &mut [u8]) -> SysResult<usize> {
 }
 
 unsafe fn rsgx_ftell(stream: SGX_FILE) -> SysResult<i64> {
-
     if stream.is_null() {
         return Err(libc::EINVAL);
     }
@@ -109,7 +104,6 @@ unsafe fn rsgx_ftell(stream: SGX_FILE) -> SysResult<i64> {
 }
 
 unsafe fn rsgx_fseek(stream: SGX_FILE, offset: i64, origin: i32) -> SysError {
-
     if stream.is_null() {
         return Err(libc::EINVAL);
     }
@@ -123,7 +117,6 @@ unsafe fn rsgx_fseek(stream: SGX_FILE, offset: i64, origin: i32) -> SysError {
 }
 
 unsafe fn rsgx_fflush(stream: SGX_FILE) -> SysError {
-
     let ret = sgx_fflush(stream);
     if ret == 0 {
         Ok(())
@@ -135,7 +128,6 @@ unsafe fn rsgx_fflush(stream: SGX_FILE) -> SysError {
 }
 
 unsafe fn rsgx_ferror(stream: SGX_FILE) -> i32 {
-
     let mut err = sgx_ferror(stream);
     if err == -1 {
         err = libc::EINVAL;
@@ -144,7 +136,6 @@ unsafe fn rsgx_ferror(stream: SGX_FILE) -> i32 {
 }
 
 unsafe fn rsgx_feof(stream: SGX_FILE) -> SysResult<bool> {
-
     if stream.is_null() {
         return Err(libc::EINVAL);
     }
@@ -161,7 +152,6 @@ unsafe fn rsgx_clearerr(stream: SGX_FILE) {
 }
 
 unsafe fn rsgx_fclose(stream: SGX_FILE) -> SysError {
-
     if stream.is_null() {
         return Err(libc::EINVAL);
     }
@@ -175,7 +165,6 @@ unsafe fn rsgx_fclose(stream: SGX_FILE) -> SysError {
 }
 
 unsafe fn rsgx_fclear_cache(stream: SGX_FILE) -> SysError {
-
     if stream.is_null() {
         return Err(libc::EINVAL);
     }
@@ -189,7 +178,6 @@ unsafe fn rsgx_fclear_cache(stream: SGX_FILE) -> SysError {
 }
 
 unsafe fn rsgx_remove(filename: &CStr) -> SysError {
-
     let ret = sgx_remove(filename.as_ptr());
     if ret == 0 {
         Ok(())
@@ -199,7 +187,6 @@ unsafe fn rsgx_remove(filename: &CStr) -> SysError {
 }
 
 unsafe fn rsgx_fexport_auto_key(filename: &CStr, key: &mut sgx_key_128bit_t) -> SysError {
-
     let ret = sgx_fexport_auto_key(filename.as_ptr(), key as * mut sgx_key_128bit_t);
     if ret == 0 {
         Ok(())
@@ -209,7 +196,6 @@ unsafe fn rsgx_fexport_auto_key(filename: &CStr, key: &mut sgx_key_128bit_t) ->
 }
 
 unsafe fn rsgx_fimport_auto_key(filename: &CStr, key: &sgx_key_128bit_t) -> SysError {
-
     let ret = sgx_fimport_auto_key(filename.as_ptr(), key as * const sgx_key_128bit_t);
     if ret == 0 {
         Ok(())
@@ -597,13 +583,19 @@ pub fn remove(filename: &CStr) -> SysError {
 /// otherwise, error code is returned.
 ///
 pub fn export_auto_key(filename: &CStr) -> SysResult<sgx_key_128bit_t> {
-
     let mut key: sgx_key_128bit_t = Default::default();
     unsafe {
         rsgx_fexport_auto_key(filename, &mut key).map(|_| key)
     }
 }
 
+pub fn export_align_auto_key(filename: &CStr) -> SysResult<sgx_align_key_128bit_t> {
+    let mut align_key: sgx_align_key_128bit_t = Default::default();
+    unsafe {
+        rsgx_fexport_auto_key(filename, &mut align_key.key).map(|_| align_key)
+    }
+}
+
 ///
 /// The import_auto_key function is used for importing a Protected FS auto key file created on
 /// a different enclave or platform.
diff --git a/sgx_tse/src/alignalloc.rs b/sgx_tse/src/alignalloc.rs
new file mode 100644
index 0000000..b46c4c7
--- /dev/null
+++ b/sgx_tse/src/alignalloc.rs
@@ -0,0 +1,363 @@
+// Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+//
+//  * Redistributions of source code must retain the above copyright
+//    notice, this list of conditions and the following disclaimer.
+//  * Redistributions in binary form must reproduce the above copyright
+//    notice, this list of conditions and the following disclaimer in
+//    the documentation and/or other materials provided with the
+//    distribution.
+//  * Neither the name of Baidu, Inc., nor the names of its
+//    contributors may be used to endorse or promote products derived
+//    from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+//! # align alloc crate for Rust SGX SDK
+//!
+
+use sgx_types::*;
+use core::alloc::Layout;
+use core::ptr::NonNull;
+use core::fmt;
+pub use self::platform::*;
+
+pub struct AlignAlloc;
+
+impl AlignAlloc {
+    #[inline]
+    pub unsafe fn alloc(&mut self, layout: Layout) -> Result<NonNull<u8>, AlighAllocErr> {
+        NonNull::new(platform::alloc(layout)).ok_or(AlighAllocErr)
+    }
+
+    #[inline]
+    pub unsafe fn alloc_zeroed(&mut self, layout: Layout)
+        -> Result<NonNull<u8>, AlighAllocErr> {
+        NonNull::new(platform::alloc_zeroed(layout)).ok_or(AlighAllocErr)
+    }
+
+    #[inline]
+    pub unsafe fn alloc_with_req(&mut self, layout: Layout, align_req: &[align_req_t]) -> Result<NonNull<u8>, AlighAllocErr> {
+        NonNull::new(platform::alloc_with_req(layout, align_req)).ok_or(AlighAllocErr)
+    }
+
+    #[inline]
+    pub unsafe fn alloc_with_req_zeroed(&mut self, layout: Layout, align_req: &[align_req_t])
+        -> Result<NonNull<u8>, AlighAllocErr> {
+        NonNull::new(platform::alloc_with_req_zeroed(layout, align_req)).ok_or(AlighAllocErr)
+    }
+
+    #[inline]
+    pub unsafe fn alloc_with_pad_align(&mut self, layout: Layout, align_layout: Layout) -> Result<NonNull<u8>, AlighAllocErr> {
+        NonNull::new(platform::alloc_with_pad_align(layout, align_layout)).ok_or(AlighAllocErr)
+    }
+
+    #[inline]
+    pub unsafe fn alloc_with_pad_align_zeroed(&mut self, layout: Layout, align_layout: Layout)
+        -> Result<NonNull<u8>, AlighAllocErr> {
+        NonNull::new(platform::alloc_with_pad_align_zeroed(layout, align_layout)).ok_or(AlighAllocErr)
+    }
+
+    #[inline]
+    pub unsafe fn dealloc(&mut self, ptr: core::ptr::NonNull<u8>, layout: Layout) {
+        platform::dealloc(ptr.as_ptr(), layout)
+    }
+
+    #[inline]
+    pub fn pad_align_to(&self, layout: Layout, align_req: &[align_req_t]) -> Result<Layout, AlignLayoutErr> {
+        platform::pad_align_to(layout, align_req)
+    }
+}
+
+#[derive(Clone, PartialEq, Eq, Debug)]
+pub struct AlighAllocErr;
+
+impl fmt::Display for AlighAllocErr {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.write_str("memory allocation failed")
+    }
+}
+
+#[derive(Clone, PartialEq, Eq, Debug)]
+pub struct AlignLayoutErr;
+
+impl fmt::Display for AlignLayoutErr {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.write_str("invalid parameters to align Layout")
+    }
+}
+
+mod platform {
+    use sgx_types::*;
+    use super::AlignLayoutErr;
+    use core::ffi::c_void;
+    use core::ptr;
+    use core::mem;
+    use core::slice;
+    use core::alloc::Layout;
+
+    #[inline]
+    pub unsafe fn alloc(layout: Layout) -> *mut u8 {
+        let req: [align_req_t; 1] = [align_req_t{offset: 0, len: layout.size()}];
+        let align_req = &req[..];
+        alloc_with_req(layout, align_req)
+    }
+
+    pub unsafe fn alloc_with_req(layout: Layout, align_req: &[align_req_t]) -> *mut u8 {
+        if !check_layout(&layout) {
+            return ptr::null_mut();
+        }
+        let align_layout = match
+            if align_req.len() == 0 {
+                let req: [align_req_t; 1] = [align_req_t{offset: 0, len: layout.size()}];
+                pad_align_to(layout, &req[..])
+            } else {
+                pad_align_to(layout, align_req)
+            }
+        {
+            Ok(l) => l,
+            Err(_) => return ptr::null_mut(),
+        };
+        alloc_with_pad_align(layout, align_layout)
+    }
+
+    #[inline]
+    pub unsafe fn alloc_with_pad_align(layout: Layout, align_layout: Layout) -> *mut u8 {
+        alloc_with_pad_align_in(false, layout, align_layout)
+    }
+
+    #[inline]
+    pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8 {
+        let req: [align_req_t; 1] = [align_req_t{offset: 0, len: layout.size()}];
+        let align_req = &req[..];
+        alloc_with_req_zeroed(layout, align_req)
+    }
+
+    pub unsafe fn alloc_with_req_zeroed(layout: Layout, align_req: &[align_req_t]) -> *mut u8 {
+        if !check_layout(&layout) {
+            return ptr::null_mut();
+        }
+        let align_layout = match
+            if align_req.len() == 0 {
+                let req: [align_req_t; 1] = [align_req_t{offset: 0, len: layout.size()}];
+                pad_align_to(layout, &req[..])
+            } else {
+                pad_align_to(layout, align_req)
+            }
+        {
+            Ok(l) => l,
+            Err(_) => return ptr::null_mut(),
+        };
+        alloc_with_pad_align_zeroed(layout, align_layout)
+    }
+
+    #[inline]
+    pub unsafe fn alloc_with_pad_align_zeroed(layout: Layout, align_layout: Layout) -> *mut u8 {
+        alloc_with_pad_align_in(true, layout, align_layout)
+    }
+
+    unsafe fn alloc_with_pad_align_in(zeroed: bool, layout: Layout, align_layout: Layout) -> *mut u8 {
+        if !check_layout(&layout) {
+            return ptr::null_mut();
+        }
+        if !check_layout(&align_layout) {
+            return ptr::null_mut();
+        }
+        if align_layout.size() < layout.size() + align_layout.align() {
+            return ptr::null_mut();
+        }
+        let pad = align_layout.size() - align_layout.align() - layout.size();
+
+        let raw = libc::malloc(align_layout.size() + mem::size_of::<*mut u8>()) as *mut u8;
+        let aligned_ptr = if raw.is_null() {
+            raw
+        } else {
+            if zeroed == true {
+                ptr::write_bytes(raw, 0, align_layout.size());
+            }
+            let ptr = make_aligned_ptr(raw, align_layout.align(), pad);
+            let p = ptr as *mut *mut u8;
+            p.sub(1).write(raw);
+            ptr
+        };
+        aligned_ptr
+    }
+
+    #[inline]
+    pub unsafe fn dealloc(ptr: *mut u8, _layout: Layout) {
+        let p = ptr as *mut *mut u8;
+        let raw = ptr::read(p.sub(1));
+        libc::free(raw as *mut c_void)
+    }
+
+    pub fn pad_align_to(layout: Layout, align_req: &[align_req_t]) -> Result<Layout, AlignLayoutErr> {
+        let pad = padding_needed_for(layout, align_req)?;
+        let align = align_needed_for(layout, pad)?;
+        Layout::from_size_align(pad + align + layout.size(), align).map_err(|_|AlignLayoutErr)
+    }
+
+    fn padding_needed_for(layout: Layout, align_req: &[align_req_t]) -> Result<usize, AlignLayoutErr> {
+        if !check_layout(&layout) {
+            return Err(AlignLayoutErr);
+        }
+        if !check_align_req(layout.size(), align_req) {
+            return Err(AlignLayoutErr);
+        }
+        let bmp = make_bitmap(align_req);
+        let offset = calc_lspc(layout.align(), bmp);
+        if offset < 0 {
+            Err(AlignLayoutErr)
+        } else {
+            Ok(offset as usize)
+        }
+    }
+
+    fn align_needed_for(layout: Layout, offset: usize) -> Result<usize, AlignLayoutErr> {
+        Ok(calc_algn(layout.align(), layout.size() + offset))
+    }
+
+    #[inline]
+    fn make_aligned_ptr(raw: *mut u8, align: usize, offset: usize) -> *mut u8 {
+        ((((raw as usize) + align - 1) & !(align - 1)) + offset) as *mut u8
+    }
+
+    #[inline]
+    fn check_overflow(buf: usize, len: usize) -> bool {
+        ((buf + len < len) || (buf + len < buf))
+    }
+
+    fn check_layout(layout: &Layout) -> bool {
+        if layout.size() == 0 || !layout.align().is_power_of_two() ||
+           layout.size() > usize::max_value() - (layout.align() - 1) {
+            false
+        } else {
+            true
+        }
+    }
+
+    fn check_align_req(size: usize, align_req: &[align_req_t]) -> bool {
+        if align_req.len() == 0 {
+            return false;
+        }
+        let len: usize = (size + 7) / 8;
+        let bmp: &mut [u8] = unsafe {
+            let ptr = libc::malloc(len) as *mut u8;
+            if ptr.is_null() {
+                return false;
+            }
+            ptr::write_bytes(ptr, 0, len);
+            slice::from_raw_parts_mut(ptr, len)
+        };
+
+        for req in align_req {
+            if check_overflow(req.offset, req.len) || (req.offset + req.len) > size {
+                unsafe{ libc::free(bmp.as_mut_ptr() as *mut c_void); }
+                return false;
+            } else {
+                for i in 0..req.len {
+                    let offset = req.offset + i;
+                    if (bmp[offset / 8] & 1 << (offset % 8)) != 0 {
+                        // overlap in req data
+                        unsafe{ libc::free(bmp.as_mut_ptr() as *mut c_void); }
+                        return false;
+                    }
+                    let tmp: u8 = (1 << (offset % 8)) as u8;
+                    bmp[offset / 8] |= tmp;
+                }
+            }
+        }
+        true
+    }
+
+    fn gen_alignmask(al: usize, a: usize, m: u64) -> i64 {
+        if a  > al {
+            gen_alignmask(al, (a >> 1) as usize, m | (m >> (a >> 1)))
+        } else {
+            m as i64
+        }
+    }
+
+    #[inline]
+    fn __rol(v: u64, c: usize, m: usize) -> u64  {
+        (v << (c & m)) | (v >> (((0 - c as isize) as usize) & m))
+    }
+
+    #[inline]
+    fn rol(v: i64, c: usize) -> i64 {
+        __rol(v as u64 , c, mem::size_of::<i64>() * 8 - 1) as i64
+    }
+
+    fn ror(v: i64, c: usize) -> i64 {
+        rol(v, (0 - c as isize) as usize)
+    }
+
+    fn count_lzb(bmp: i64) -> i32 {
+        if bmp == 0 {
+            -1
+        } else if bmp < 0 {
+            0
+        } else {
+            count_lzb(bmp << 1) + 1
+        }
+    }
+
+    fn calc_lspc(al: usize, bmp: i64) -> i32 {
+        if !al.is_power_of_two() {
+            -2
+        } else {
+            count_lzb(
+                !(ror(bmp | ror(bmp, 1) | ror(bmp, 2) | ror(bmp, 3), 5) | ror(bmp, 1)) &
+                gen_alignmask(al, mem::size_of::<u64>() * 8, 1_u64 << (mem::size_of::<u64>() * 8 - 1)))
+        }
+    }
+
+    fn __calc_algn(size: usize, a: usize) -> usize {
+        if a > 8 && size <= a / 2 {
+            __calc_algn(size, a / 2)
+        } else {
+            a
+        }
+    }
+
+    fn calc_algn(al: usize, size: usize) -> usize {
+        if al > 64  {
+            al
+        } else {
+            __calc_algn(size, mem::size_of::<u64>() * 8)
+        }
+    }
+
+    fn make_bitmap(align_req: &[align_req_t]) -> i64 {
+        let mut bmp: i64 = 0;
+        for req in align_req {
+            if req.len > 63 {
+                return -1;
+            } else {
+                bmp |= rol(((1 as i64) << req.len) - 1, req.offset);
+            }
+        }
+        bmp
+    }
+
+    mod libc {
+        use core::ffi::c_void;
+        type size_t = usize;
+        extern {
+            pub fn malloc(size: size_t) -> * mut c_void;
+            pub fn free(p: *mut c_void);
+        }
+    }
+}
\ No newline at end of file
diff --git a/sgx_tse/src/alignbox.rs b/sgx_tse/src/alignbox.rs
new file mode 100644
index 0000000..31ee711
--- /dev/null
+++ b/sgx_tse/src/alignbox.rs
@@ -0,0 +1,260 @@
+// Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+//
+//  * Redistributions of source code must retain the above copyright
+//    notice, this list of conditions and the following disclaimer.
+//  * Redistributions in binary form must reproduce the above copyright
+//    notice, this list of conditions and the following disclaimer in
+//    the documentation and/or other materials provided with the
+//    distribution.
+//  * Neither the name of Baidu, Inc., nor the names of its
+//    contributors may be used to endorse or promote products derived
+//    from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+//! # align box crate for Rust SGX SDK
+//!
+use sgx_types::*;
+use core::ptr::{Unique, NonNull};
+use core::ops::{DerefMut, Deref};
+use core::mem;
+use core::ptr;
+use core::fmt;
+use core::borrow;
+use alloc::alloc::{Layout, handle_alloc_error};
+use super::alignalloc::AlignAlloc;
+
+pub struct AlignBox<T> {
+    ptr: Unique<T>,
+    align_layout: Layout,
+    origin_layout: Layout,
+}
+
+impl<T> AlignBox<T> {
+    /// Gets a raw pointer to the start of the allocation. Note that this is
+    /// Unique::empty() if `cap = 0` or T is zero-sized. In the former case, you must
+    /// be careful.
+    pub fn as_ptr(&self) -> *mut T {
+        self.ptr.as_ptr()
+    }
+}
+
+impl<T> Deref for AlignBox<T> {
+    type Target = T;
+
+    fn deref(&self) -> &T {
+        unsafe{self.ptr.as_ref()}
+    }
+}
+
+impl<T> DerefMut for AlignBox<T> {
+    fn deref_mut(&mut self) -> &mut T {
+       unsafe{self.ptr.as_mut()}
+    }
+}
+
+impl<T> AsRef<T> for AlignBox<T> {
+    fn as_ref(&self) -> &T {
+        &**self
+    }
+}
+
+impl<T> AsMut<T> for AlignBox<T> {
+    fn as_mut(&mut self) -> &mut T {
+        &mut **self
+    }
+}
+
+impl<T> borrow::Borrow<T> for AlignBox<T> {
+    fn borrow(&self) -> &T {
+        &**self
+    }
+}
+
+impl<T> borrow::BorrowMut<T> for AlignBox<T> {
+    fn borrow_mut(&mut self) -> &mut T {
+        &mut **self
+    }
+}
+
+impl<T: fmt::Display> fmt::Display for AlignBox<T> {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        fmt::Display::fmt(&**self, f)
+    }
+}
+
+impl<T: fmt::Debug> fmt::Debug for AlignBox<T> {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.debug_struct("AlignBox")
+            .field("align_layout", &self.align_layout)
+            .field("data", &**self)
+            .finish()
+    }
+}
+
+impl<T: Clone> Clone for AlignBox<T> {
+    #[rustfmt::skip]
+    #[inline]
+    fn clone(&self) -> AlignBox<T> {
+        let ptr = match unsafe{AlignAlloc.alloc_with_pad_align_zeroed(self.origin_layout, self.align_layout)} {
+            Ok(p) => p,
+            Err(_) => handle_alloc_error(self.align_layout),
+        };
+        unsafe{ptr::copy_nonoverlapping(&(**self).clone() as *const _ as *const u8, ptr.as_ptr() , self.origin_layout.size())};
+        AlignBox {ptr: ptr.cast().into(), align_layout: self.align_layout, origin_layout: self.origin_layout}
+    }
+
+    #[inline]
+    fn clone_from(&mut self, source: &AlignBox<T>) {
+        if source.align_layout.size() != self.align_layout.size() {
+            let ptr = match unsafe{AlignAlloc.alloc_with_pad_align_zeroed(source.origin_layout, source.align_layout)} {
+                Ok(p) => p,
+                Err(_) => handle_alloc_error(source.align_layout),
+            };
+            unsafe {
+                ptr::copy_nonoverlapping(&(**source).clone() as *const _ as *const u8, ptr.as_ptr(), source.origin_layout.size());
+                self.dealloc_buffer();
+            }
+            self.ptr = ptr.cast().into();
+        }  else   {
+            (**self).clone_from(&(**source));
+        }
+        self.align_layout = source.align_layout;
+        self.origin_layout = source.origin_layout;
+    }
+}
+
+impl<T> AlignBox<T> {
+    unsafe fn dealloc_buffer(&mut self) {
+        let elem_size = mem::size_of::<T>();
+        if elem_size != 0 {
+            AlignAlloc.dealloc(NonNull::from(self.ptr).cast(), self.origin_layout)
+        }
+    }
+}
+
+unsafe impl<#[may_dangle] T> Drop for AlignBox<T> {
+    fn drop(&mut self) {
+        unsafe {
+            self.dealloc_buffer();
+        }
+    }
+}
+
+impl<T> AlignBox<T> {
+
+    fn new_with_req_in(align: usize, align_req: &[align_req_t]) -> Option<Self> {
+        if align_req.len() == 0 {
+            AlignBox::new_in()
+        } else {
+            AlignBox::allocate_in(true, align, align_req)
+        }
+    }
+
+    fn new_with_align_in(align: usize) -> Option<Self> {
+        let v: [align_req_t; 1] = [align_req_t{offset:0, len:mem::size_of::<T>()}];
+        AlignBox::allocate_in(true, align, &v)
+    }
+
+    fn new_in() -> Option<Self> {
+        let v: [align_req_t; 1] = [align_req_t{offset: 0, len:mem::size_of::<T>()}];
+        AlignBox::allocate_in(true, mem::align_of::<T>(), &v)
+    }
+
+    fn allocate_in(zeroed: bool, align: usize, align_req: &[align_req_t]) -> Option<Self> {
+        if mem::size_of::<T>() == 0 {
+            return None;
+        }
+
+        let layout = match Layout::from_size_align(mem::size_of::<T>(), align) {
+            Ok(n) => {n},
+            Err(_) => {return None},
+        };
+    
+        let align_layout = match AlignAlloc.pad_align_to(layout, align_req) {
+            Ok(n) => {n},
+            Err(_) => {return None},
+        };
+       
+        // handles ZSTs and `cap = 0` alike
+        let result = if zeroed {
+            unsafe{AlignAlloc.alloc_with_req_zeroed(layout, align_req)}
+        } else {
+            unsafe{AlignAlloc.alloc_with_req(layout, align_req)}
+        };
+        let ptr = match result {
+            Ok(r) => r.cast(),
+            Err(_) => handle_alloc_error(align_layout),
+        };
+
+        Some(AlignBox{ptr: ptr.into(), align_layout: align_layout, origin_layout: layout})
+    }
+}
+
+impl<T> AlignBox<T> {
+    pub fn new() -> Option<Self> {
+        Self::new_in()
+    }
+     pub fn new_with_align(align: usize) -> Option<Self> {
+        Self::new_with_align_in(align)
+    }
+    pub fn new_with_req(align: usize, align_req: &[align_req_t]) -> Option<Self> {
+        Self::new_with_req_in(align, align_req)
+    }
+}
+
+impl<T> AlignBox<T> {
+    pub fn heap_init<F>(initialize: F) -> Option<Self>
+    where
+        F: Fn(&mut T),
+    {
+        unsafe {
+            let mut t = Self::new_in();
+            match t {
+                Some(ref mut b) => initialize(b.ptr.as_mut()),
+                None => (),
+            }
+            t
+        }
+    }
+    pub fn heap_init_with_align<F>(initialize: F, align: usize) -> Option<Self>
+    where
+        F: Fn(&mut T),
+    {
+        unsafe {
+            let mut t = Self::new_with_align(align);
+            match t {
+                Some(ref mut b) => initialize(b.ptr.as_mut()),
+                None => (),
+            }
+            t
+        }
+    }
+    pub fn heap_init_with_req<F>(initialize: F, align: usize, data: &[align_req_t]) -> Option<Self>
+    where
+        F: Fn(&mut T),
+    {
+      unsafe {
+            let mut t = Self::new_with_req(align, data);
+            match t {
+                Some(ref mut b) => initialize(b.ptr.as_mut()),
+                None => (),
+            }
+            t
+        }
+    }
+}
diff --git a/sgx_tse/src/alloc.rs b/sgx_tse/src/alloc.rs
new file mode 100644
index 0000000..2ecc866
--- /dev/null
+++ b/sgx_tse/src/alloc.rs
@@ -0,0 +1,350 @@
+// Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions
+// are met:
+//
+//  * Redistributions of source code must retain the above copyright
+//    notice, this list of conditions and the following disclaimer.
+//  * Redistributions in binary form must reproduce the above copyright
+//    notice, this list of conditions and the following disclaimer in
+//    the documentation and/or other materials provided with the
+//    distribution.
+//  * Neither the name of Baidu, Inc., nor the names of its
+//    contributors may be used to endorse or promote products derived
+//    from this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+//! # align alloc crate for Rust SGX SDK
+//!
+
+use sgx_types::*;
+use core::alloc::Layout;
+use core::ptr::NonNull;
+use core::fmt;
+pub use self::platform::*;
+
+pub struct AlignAlloc;
+
+impl AlignAlloc {
+    #[inline]
+    pub unsafe fn alloc(&mut self, layout: Layout) -> Result<NonNull<u8>, AlighAllocErr> {
+        NonNull::new(platform::alloc(layout)).ok_or(AlighAllocErr)
+    }
+
+    #[inline]
+    pub unsafe fn alloc_zeroed(&mut self, layout: Layout)
+        -> Result<NonNull<u8>, AlighAllocErr> {
+        NonNull::new(platform::alloc_zeroed(layout)).ok_or(AlighAllocErr)
+    }
+
+    #[inline]
+    pub unsafe fn alloc_with_req(&mut self, layout: Layout, align_req: &[align_req_t]) -> Result<NonNull<u8>, AlighAllocErr> {
+        NonNull::new(platform::alloc_with_req(layout, align_req)).ok_or(AlighAllocErr)
+    }
+
+    #[inline]
+    pub unsafe fn alloc_with_req_zeroed(&mut self, layout: Layout, align_req: &[align_req_t])
+        -> Result<NonNull<u8>, AlighAllocErr> {
+        NonNull::new(platform::alloc_with_req_zeroed(layout, align_req)).ok_or(AlighAllocErr)
+    }
+
+    #[inline]
+    pub unsafe fn alloc_with_pad_align(&mut self, layout: Layout, align_layout: Layout) -> Result<NonNull<u8>, AlighAllocErr> {
+        NonNull::new(platform::alloc_with_pad_align(layout, align_layout)).ok_or(AlighAllocErr)
+    }
+
+    #[inline]
+    pub unsafe fn alloc_with_pad_align_zeroed(&mut self, layout: Layout, align_layout: Layout)
+        -> Result<NonNull<u8>, AlighAllocErr> {
+        NonNull::new(platform::alloc_with_pad_align_zeroed(layout, align_layout)).ok_or(AlighAllocErr)
+    }
+
+    #[inline]
+    pub unsafe fn dealloc(&mut self, ptr: core::ptr::NonNull<u8>, layout: Layout) {
+        platform::dealloc(ptr.as_ptr(), layout)
+    }
+
+    #[inline]
+    pub fn pad_align_to(&self, layout: Layout, align_req: &[align_req_t]) -> Result<Layout, AlignLayoutErr> {
+        platform::pad_align_to(layout, align_req)
+    }
+}
+
+pub struct AlighAllocErr;
+
+impl fmt::Display for AlighAllocErr {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.write_str("memory allocation failed")
+    }
+}
+
+pub struct AlignLayoutErr;
+
+impl fmt::Display for AlignLayoutErr {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.write_str("invalid parameters to align Layout")
+    }
+}
+
+mod platform {
+    use sgx_types::*;
+    use super::AlignLayoutErr;
+    use core::ffi::c_void;
+    use core::ptr;
+    use core::mem;
+    use core::slice;
+    use core::alloc::Layout;
+
+    pub unsafe fn alloc(layout: Layout) -> *mut u8 {
+        let req: [align_req_t; 1] = [align_req_t{offset: 0, len: layout.size()}];
+        let align_req = &req[..];
+        alloc_with_req(layout, align_req)
+    }
+
+    pub unsafe fn alloc_with_req(layout: Layout, align_req: &[align_req_t]) -> *mut u8 {
+        if !check_layout(&layout) {
+            return ptr::null_mut();
+        }
+
+        let align_layout = match
+            if align_req.len() == 0 {
+                let req: [align_req_t; 1] = [align_req_t{offset: 0, len: layout.size()}];
+                pad_align_to(layout, &req[..])
+            } else {
+                pad_align_to(layout, align_req)
+            }
+        {
+            Ok(l) => l,
+            Err(_) => return ptr::null_mut(),
+        };
+        alloc_with_pad_align(layout, align_layout)
+    }
+
+    pub unsafe fn alloc_with_pad_align(layout: Layout, align_layout: Layout) -> *mut u8 {
+        if !check_layout(&layout) {
+            return ptr::null_mut();
+        }
+        if !check_layout(&align_layout) {
+            return ptr::null_mut();
+        }
+        if align_layout.size() < layout.size() + align_layout.align() {
+            return ptr::null_mut();
+        }
+        let pad = align_layout.size() - align_layout.align() - layout.size();
+
+        let raw = libc::malloc(align_layout.size() + mem::size_of::<*mut u8>()) as *mut u8;
+        let aligned_ptr = if raw.is_null() {
+            raw
+        } else {
+            let ptr = make_aligned_ptr(raw, align_layout.align(), pad);
+            let p = ptr as *mut *mut u8;
+            p.sub(1).write(raw);
+            ptr
+        };
+        aligned_ptr
+    }
+
+    #[inline]
+    pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8 { 
+        let ptr = alloc(layout);
+        if !ptr.is_null() {
+            ptr::write_bytes(ptr, 0, layout.size());
+        }
+        ptr
+    }
+
+    #[inline]
+    pub unsafe fn alloc_with_req_zeroed(layout: Layout, align_req: &[align_req_t]) -> *mut u8 {
+        let ptr = alloc_with_req(layout, align_req);
+        if !ptr.is_null() {
+            ptr::write_bytes(ptr, 0, layout.size());
+        }
+        ptr
+    }
+
+    #[inline]
+    pub unsafe fn alloc_with_pad_align_zeroed(layout: Layout, align_layout: Layout) -> *mut u8 {
+        let ptr = alloc_with_pad_align(align_layout, layout);
+        if !ptr.is_null() {
+            ptr::write_bytes(ptr, 0, align_layout.size());
+        }
+        ptr
+    }
+
+    #[inline]
+    pub unsafe fn dealloc(ptr: *mut u8, _layout: Layout) {
+        let p = ptr as *mut *mut u8;
+        let raw = ptr::read(p.sub(1));
+        libc::free(raw as *mut c_void)
+    }
+
+    pub fn pad_align_to(layout: Layout, align_req: &[align_req_t]) -> Result<Layout, AlignLayoutErr> {
+        let pad = padding_needed_for(layout, align_req)?;
+        let align = align_needed_for(layout, pad)?;
+        Layout::from_size_align(pad + align + layout.size(), align).map_err(|_|AlignLayoutErr)
+    }
+
+    fn padding_needed_for(layout: Layout, align_req: &[align_req_t]) -> Result<usize, AlignLayoutErr> {
+        if !check_layout(&layout) {
+            return Err(AlignLayoutErr);
+        }
+        if !check_align_req(layout.size(), align_req) {
+            return Err(AlignLayoutErr);
+        }
+        let bmp = make_bitmap(align_req);
+        let offset = calc_lspc(layout.align(), bmp);
+        if offset < 0 {
+            Err(AlignLayoutErr)
+        } else {
+            Ok(offset as usize)
+        }
+    }
+
+    fn align_needed_for(layout: Layout, offset: usize) -> Result<usize, AlignLayoutErr> {
+        Ok(calc_algn(layout.align(), layout.size() + offset))
+    }
+
+    #[inline]
+    fn make_aligned_ptr(raw: *mut u8, align: usize, offset: usize) -> *mut u8 {
+        ((((raw as usize) + align - 1) & !(align - 1)) + offset) as *mut u8
+    }
+
+    #[inline]
+    fn check_overflow(buf: usize, len: usize) -> bool {
+        ((buf + len < len) || (buf + len < buf))
+    }
+
+    fn check_layout(layout: &Layout) -> bool {
+        if layout.size() == 0 || !layout.align().is_power_of_two() ||
+           layout.size() > usize::max_value() - (layout.align() - 1) {
+            false
+        } else {
+            true
+        }
+    }
+
+    fn check_align_req(size: usize, align_req: &[align_req_t]) -> bool {
+        if align_req.len() == 0 {
+            return false;
+        }
+        let len: usize = (size + 7) / 8;
+        let bmp: &mut [u8] = unsafe {
+            let ptr = libc::malloc(len) as *mut u8;
+            if ptr.is_null() {
+                return false;
+            }
+            ptr::write_bytes(ptr, 0, len);
+            slice::from_raw_parts_mut(ptr, len)
+        };
+
+        for req in align_req {
+            if check_overflow(req.offset, req.len) || (req.offset + req.len) > size {
+                unsafe{ libc::free(bmp.as_mut_ptr() as *mut c_void); }
+                return false;
+            } else {
+                for i in 0..req.len {
+                    let offset = req.offset + i;
+                    if (bmp[offset / 8] & 1 << (offset % 8)) != 0 {
+                        // overlap in req data
+                        unsafe{ libc::free(bmp.as_mut_ptr() as *mut c_void); }
+                        return false;
+                    }
+                    let tmp: u8 = (1 << (offset % 8)) as u8;
+                    bmp[offset / 8] |= tmp;
+                }
+            }
+        }
+        true
+    }
+
+    fn gen_alignmask(al: usize, a: usize, m: u64) -> i64 {
+        if a  > al {
+            gen_alignmask(al, (a >> 1) as usize, m | (m >> (a >> 1)))
+        } else {
+            m as i64
+        }
+    }
+
+    #[inline]
+    fn __rol(v: u64, c: usize, m: usize) -> u64  {
+        (v << (c & m)) | (v >> (((0 - c as isize) as usize) & m))
+    }
+
+    #[inline]
+    fn rol(v: i64, c: usize) -> i64 {
+        __rol(v as u64 , c, mem::size_of::<i64>() * 8 - 1) as i64
+    }
+
+    fn ror(v: i64, c: usize) -> i64 {
+        rol(v, (0 - c as isize) as usize)
+    }
+
+    fn count_lzb(bmp: i64) -> i32 {
+        if bmp == 0 {
+            -1
+        } else if bmp < 0 {
+            0
+        } else {
+            count_lzb(bmp << 1) + 1
+        }
+    }
+
+    fn calc_lspc(al: usize, bmp: i64) -> i32 {
+        if !al.is_power_of_two() {
+            -2
+        } else {
+            count_lzb(
+                !(ror(bmp | ror(bmp, 1) | ror(bmp, 2) | ror(bmp, 3), 5) | ror(bmp, 1)) &
+                gen_alignmask(al, mem::size_of::<u64>() * 8, 1_u64 << (mem::size_of::<u64>() * 8 - 1)))
+        }
+    }
+
+    fn __calc_algn(size: usize, a: usize) -> usize {
+        if a > 8 && size <= a / 2 {
+            __calc_algn(size, a / 2)
+        } else {
+            a
+        }
+    }
+
+    fn calc_algn(al: usize, size: usize) -> usize {
+        if al > 64  {
+            al
+        } else {
+            __calc_algn(size, mem::size_of::<u64>() * 8)
+        }
+    }
+
+    fn make_bitmap(align_req: &[align_req_t]) -> i64 {
+        let mut bmp: i64 = 0;
+        for req in align_req {
+            if req.len > 63 {
+                return -1;
+            } else {
+                bmp |= rol(((1 as i64) << req.len) - 1, req.offset);
+            }
+        }
+        bmp
+    }
+
+    mod libc {
+        use core::ffi::c_void;
+        type size_t = usize;
+        extern {
+            pub fn malloc(size: size_t) -> * mut c_void;
+            pub fn free(p: *mut c_void);
+        }
+    }
+}
\ No newline at end of file
diff --git a/sgx_tse/src/lib.rs b/sgx_tse/src/lib.rs
index 7100ad6..4cccf0d 100644
--- a/sgx_tse/src/lib.rs
+++ b/sgx_tse/src/lib.rs
@@ -33,192 +33,14 @@
 
 #![no_std]
 #![cfg_attr(target_env = "sgx", feature(rustc_private))]
+#![allow(non_camel_case_types)]
+#![feature(ptr_internals)]
+#![feature(dropck_eyepatch)]
 
+extern crate alloc;
 extern crate sgx_types;
-use sgx_types::*;
-
-///
-/// The rsgx_create_report function tries to use the information of the target enclave and other information
-/// to create a cryptographic report of the enclave.
-///
-/// This function is a wrapper for the SGX EREPORT instruction.
-///
-/// # Description
-///
-/// Use the function rsgx_create_report to create a cryptographic report that describes the contents of the
-/// calling enclave. The report can be used by other enclaves to verify that the enclave is running on the
-/// same platform. When an enclave calls rsgx_verify_report to verify a report, it will succeed only if
-/// the report was generated using the target_info for said enclave. This function is a wrapper for the SGX EREPORT
-/// instruction.
-///
-/// Before the source enclave calls rsgx_create_report to generate a report, it needs to populate target_info with
-/// information about the target enclave that will verify the report. The target enclave may obtain this information
-/// calling rsgx_create_report with a default value for target_info and pass it to the source enclave at the beginning
-/// of the inter-enclave attestation process.
-///
-/// # Parameters
-///
-/// **target_info**
-///
-/// A pointer to the sgx_target_info_t object that contains the information of the target enclave,
-/// which will be able to cryptographically verify the report calling rsgx_verify_report.efore calling this function.
-///
-/// If value is default, sgx_create_report retrieves information about the calling enclave,
-/// but the generated report cannot be verified by any enclave.
-///
-/// **report_data**
-///
-/// A pointer to the sgx_report_data_t object which contains a set of data used for communication between the enclaves.
-///
-/// # Requirements
-///
-/// Library: libsgx_tservice.a
-///
-/// # Return value
-///
-/// Cryptographic report of the enclave
-///
-/// # Errors
-///
-/// **SGX_ERROR_INVALID_PARAMETER**
-///
-/// An error is reported if any of the parameters memory is not within the enclave or the reserved fields
-/// of the data structure are not set to zero.
-///
-/// **SGX_ERROR_OUT_OF_MEMORY**
-///
-/// Indicates that the enclave is out of memory.
-///
-pub fn rsgx_create_report(target_info: &sgx_target_info_t, report_data: &sgx_report_data_t) -> SgxResult<sgx_report_t> {
-
-    let mut report = sgx_report_t::default();
-    let ret = unsafe {
-        sgx_create_report(target_info as * const sgx_target_info_t,
-                          report_data as * const sgx_report_data_t,
-                          &mut report as * mut sgx_report_t)
-
-    };
-    match ret {
-        sgx_status_t::SGX_SUCCESS => Ok(report),
-        _ => Err(ret),
-    }
-}
-
-///
-/// The rsgx_verify_report function provides software verification for the report which is expected to be
-/// generated by the rsgx_create_report function.
-///
-/// # Description
-///
-/// The rsgx_verify_report performs a cryptographic CMAC function of the input sgx_report_data_t object
-/// in the report using the report key. Then the function compares the input report MAC value with the
-/// calculated MAC value to determine whether the report is valid or not.
-///
-/// # Parameters
-///
-/// **report**
-///
-/// A pointer to an sgx_report_t object that contains the cryptographic report to be verified.
-/// The report buffer must be within the enclave.
-///
-/// # Requirements
-///
-/// Library: libsgx_tservice.a
-///
-/// # Errors
-///
-/// **SGX_ERROR_INVALID_PARAMETER**
-///
-/// The report object is invalid.
-///
-/// **SGX_ERROR_MAC_MISMATCH**
-///
-/// Indicates report verification error.
-///
-/// **SGX_ERROR_UNEXPECTED**
-///
-/// Indicates an unexpected error occurs during the report verification process.
-///
-pub fn rsgx_verify_report(report: &sgx_report_t) -> SgxError {
-
-    let ret = unsafe { sgx_verify_report(report as * const sgx_report_t) };
-    match ret {
-        sgx_status_t::SGX_SUCCESS => Ok(()),
-        _ => Err(ret),
-    }
-}
-
-///
-/// The rsgx_get_key function generates a 128-bit secret key using the input information.
-///
-/// This function is a wrapper for the SGX EGETKEY instruction.
-///
-/// # Description
-///
-/// The rsgx_get_key function generates a 128-bit secret key from the processor specific key hierarchy with
-/// the key_request information. If the function fails with an error code, the key buffer will be filled with
-/// random numbers. The key_request structure needs to be initialized properly to obtain the requested key type.
-/// See sgx_key_request_t for structure details.
-///
-/// # Parameters
-///
-/// **key_request**
-///
-/// A pointer to a sgx_key_request_t object used for selecting the appropriate key and any additional parameters
-/// required in the derivation of that key. The pointer must be located within the enclave.
-///
-/// See details on the sgx_key_request_t to understand initializing this structure before calling this function.
-///
-/// # Requirements
-///
-/// Library: libsgx_tservice.a
-///
-/// # Return value
-///
-/// Cryptographic key
-///
-/// # Errors
-///
-/// **SGX_ERROR_INVALID_PARAMETER**
-///
-/// Indicates an error that the input parameters are invalid.
-///
-/// **SGX_ERROR_OUT_OF_MEMORY**
-///
-/// Indicates an error that the enclave is out of memory.
-///
-/// **SGX_ERROR_INVALID_ATTRIBUTE**
-///
-/// Indicates the key_request requests a key for a KEYNAME which the enclave is not authorized.
-///
-/// **SGX_ERROR_INVALID_CPUSVN**
-///
-/// Indicates key_request->cpu_svn is beyond platform CPUSVN value
-///
-/// **SGX_ERROR_INVALID_ISVSVN**
-///
-/// Indicates key_request->isv_svn is greater than the enclave’s ISVSVN
-///
-/// **SGX_ERROR_INVALID_KEYNAME**
-///
-/// Indicates key_request->key_name is an unsupported value
-///
-/// **SGX_ERROR_UNEXPECTED**
-///
-/// Indicates an unexpected error occurs during the key generation process.
-///
-pub fn rsgx_get_key(key_request: &sgx_key_request_t) -> SgxResult<sgx_key_128bit_t> {
-
-    let mut key = sgx_key_128bit_t::default();
-    let ret = unsafe { sgx_get_key(key_request as * const sgx_key_request_t, &mut key as * mut sgx_key_128bit_t) };
-    match ret {
-        sgx_status_t::SGX_SUCCESS => Ok(key),
-        _ => Err(ret),
-    }
-}
-
-pub fn rsgx_self_report() -> sgx_report_t {
-
-    unsafe { * sgx_self_report() }
-}
 
+mod se;
+pub use self::se::*;
+pub mod alignalloc;
+pub mod alignbox;
diff --git a/sgx_tse/src/lib.rs b/sgx_tse/src/se.rs
similarity index 95%
copy from sgx_tse/src/lib.rs
copy to sgx_tse/src/se.rs
index 7100ad6..fabd902 100644
--- a/sgx_tse/src/lib.rs
+++ b/sgx_tse/src/se.rs
@@ -31,10 +31,6 @@
 //! The library provides functions for getting specific keys and for creating and verifying an enclave report.
 //!
 
-#![no_std]
-#![cfg_attr(target_env = "sgx", feature(rustc_private))]
-
-extern crate sgx_types;
 use sgx_types::*;
 
 ///
@@ -90,7 +86,6 @@ use sgx_types::*;
 /// Indicates that the enclave is out of memory.
 ///
 pub fn rsgx_create_report(target_info: &sgx_target_info_t, report_data: &sgx_report_data_t) -> SgxResult<sgx_report_t> {
-
     let mut report = sgx_report_t::default();
     let ret = unsafe {
         sgx_create_report(target_info as * const sgx_target_info_t,
@@ -140,7 +135,6 @@ pub fn rsgx_create_report(target_info: &sgx_target_info_t, report_data: &sgx_rep
 /// Indicates an unexpected error occurs during the report verification process.
 ///
 pub fn rsgx_verify_report(report: &sgx_report_t) -> SgxError {
-
     let ret = unsafe { sgx_verify_report(report as * const sgx_report_t) };
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(()),
@@ -208,7 +202,6 @@ pub fn rsgx_verify_report(report: &sgx_report_t) -> SgxError {
 /// Indicates an unexpected error occurs during the key generation process.
 ///
 pub fn rsgx_get_key(key_request: &sgx_key_request_t) -> SgxResult<sgx_key_128bit_t> {
-
     let mut key = sgx_key_128bit_t::default();
     let ret = unsafe { sgx_get_key(key_request as * const sgx_key_request_t, &mut key as * mut sgx_key_128bit_t) };
     match ret {
@@ -217,8 +210,15 @@ pub fn rsgx_get_key(key_request: &sgx_key_request_t) -> SgxResult<sgx_key_128bit
     }
 }
 
-pub fn rsgx_self_report() -> sgx_report_t {
-
-    unsafe { * sgx_self_report() }
+pub fn rsgx_get_align_key(key_request: &sgx_key_request_t) -> SgxResult<sgx_align_key_128bit_t> {
+    let mut align_key = sgx_align_key_128bit_t::default();
+    let ret = unsafe { sgx_get_key(key_request as * const sgx_key_request_t, &mut align_key.key as * mut sgx_key_128bit_t) };
+    match ret {
+        sgx_status_t::SGX_SUCCESS => Ok(align_key),
+        _ => Err(ret),
+    }
 }
 
+pub fn rsgx_self_report() -> sgx_report_t {
+    unsafe { * sgx_self_report() }
+}
\ No newline at end of file
diff --git a/sgx_tseal/src/internal.rs b/sgx_tseal/src/internal.rs
index b32a19b..76ed48b 100644
--- a/sgx_tseal/src/internal.rs
+++ b/sgx_tseal/src/internal.rs
@@ -498,8 +498,7 @@ impl SgxInternalSealedData {
                     payload_iv: &[u8],
                     key_request: &sgx_key_request_t) -> SgxResult<Self>  {
 
-
-        let mut seal_key = rsgx_get_key(key_request).map_err(|ret| {
+        let mut seal_key = rsgx_get_align_key(key_request).map_err(|ret| {
             if ret != sgx_status_t::SGX_ERROR_OUT_OF_MEMORY {
                 sgx_status_t::SGX_ERROR_UNEXPECTED
             } else {
@@ -510,14 +509,14 @@ impl SgxInternalSealedData {
         let mut sealed_data = SgxInternalSealedData::default();
         sealed_data.payload_data.encrypt = vec![0_u8; encrypt_text.len()].into_boxed_slice();
 
-        let error = rsgx_rijndael128GCM_encrypt(&seal_key,
+        let error = rsgx_rijndael128GCM_encrypt(&seal_key.key,
                                                 encrypt_text,
                                                 payload_iv,
                                                 &additional_text,
                                                 &mut sealed_data.payload_data.encrypt,
                                                 &mut sealed_data.payload_data.payload_tag);
         if error.is_err() {
-            seal_key = sgx_key_128bit_t::default();
+            seal_key.key = sgx_key_128bit_t::default();
             return Err(error.unwrap_err());
         }
 
@@ -526,14 +525,14 @@ impl SgxInternalSealedData {
             sealed_data.payload_data.additional = additional_text.to_vec().into_boxed_slice();
         }
 
-        seal_key = sgx_key_128bit_t::default();
+        seal_key.key = sgx_key_128bit_t::default();
 
         Ok(sealed_data)
     }
 
     fn unseal_data_helper(&self) -> SgxResult<SgxInternalUnsealedData> {
 
-        let mut seal_key = rsgx_get_key(self.get_key_request()).map_err(|ret| {
+        let mut seal_key = rsgx_get_align_key(self.get_key_request()).map_err(|ret| {
             if (ret == sgx_status_t::SGX_ERROR_INVALID_CPUSVN) ||
                (ret == sgx_status_t::SGX_ERROR_INVALID_ISVSVN) ||
                (ret == sgx_status_t::SGX_ERROR_OUT_OF_MEMORY) {
@@ -555,14 +554,14 @@ impl SgxInternalSealedData {
         let mut unsealed_data: SgxInternalUnsealedData = SgxInternalUnsealedData::default();
         unsealed_data.decrypt = vec![0_u8; self.payload_data.encrypt.len()].into_boxed_slice();
 
-        let error = rsgx_rijndael128GCM_decrypt(&seal_key,
+        let error = rsgx_rijndael128GCM_decrypt(&seal_key.key,
                                                 self.get_encrypt_txt(),
                                                 &payload_iv,
                                                 self.get_additional_txt(),
                                                 self.get_payload_tag(),
                                                 &mut unsealed_data.decrypt);
         if error.is_err() {
-            seal_key = sgx_key_128bit_t::default();
+            seal_key.key = sgx_key_128bit_t::default();
             return Err(error.unwrap_err());
         }
 
@@ -571,7 +570,7 @@ impl SgxInternalSealedData {
         }
         unsealed_data.payload_size = self.get_payload_size();
 
-        seal_key = sgx_key_128bit_t::default();
+        seal_key.key = sgx_key_128bit_t::default();
 
         Ok(unsealed_data)
     }
diff --git a/sgx_tstd/src/sgxfs.rs b/sgx_tstd/src/sgxfs.rs
index a3abd12..c64cb5b 100644
--- a/sgx_tstd/src/sgxfs.rs
+++ b/sgx_tstd/src/sgxfs.rs
@@ -28,7 +28,7 @@
 
 //! Filesystem manipulation operations.
 
-use sgx_types::sgx_key_128bit_t;
+use sgx_types::{sgx_key_128bit_t, sgx_align_key_128bit_t};
 use crate::io::{self, SeekFrom, Seek, Read, Initializer, Write};
 use crate::path::Path;
 use crate::sys::sgxfs as fs_imp;
@@ -307,6 +307,10 @@ pub fn export_auto_key<P: AsRef<Path>>(path: P) -> io::Result<sgx_key_128bit_t>
     fs_imp::export_auto_key(path.as_ref())
 }
 
+pub fn export_align_auto_key<P: AsRef<Path>>(path: P) -> io::Result<sgx_align_key_128bit_t> {
+    fs_imp::export_align_auto_key(path.as_ref())
+}
+
 pub fn import_auto_key<P: AsRef<Path>>(path: P, key: &sgx_key_128bit_t) -> io::Result<()> {
     fs_imp::import_auto_key(path.as_ref(), key)
 }
diff --git a/sgx_tstd/src/sys/sgxfs.rs b/sgx_tstd/src/sys/sgxfs.rs
index 267dbea..a1dc373 100644
--- a/sgx_tstd/src/sys/sgxfs.rs
+++ b/sgx_tstd/src/sys/sgxfs.rs
@@ -26,7 +26,7 @@
 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
-use sgx_types::{sgx_status_t, sgx_key_128bit_t};
+use sgx_types::{sgx_status_t, sgx_key_128bit_t, sgx_align_key_128bit_t};
 use sgx_trts::libc;
 use sgx_tprotected_fs::{self, SgxFileStream};
 use crate::os::unix::prelude::*;
@@ -271,6 +271,24 @@ pub fn export_auto_key(path: &Path) -> io::Result<sgx_key_128bit_t> {
     })
 }
 
+pub fn export_align_auto_key(path: &Path) -> io::Result<sgx_align_key_128bit_t> {
+
+    let path = cstr(path)?;
+    sgx_tprotected_fs::export_align_auto_key(&path).map_err(|err| {
+        match err {
+            1 => Error::from_sgx_error(sgx_status_t::SGX_ERROR_UNEXPECTED),
+            2 => Error::from_raw_os_error(libc::ENOENT),
+            3 => Error::from_sgx_error(sgx_status_t::SGX_ERROR_OUT_OF_MEMORY),
+            4 | 5 => Error::from_raw_os_error(err),
+            r if r > 4096 => {
+                let status = sgx_status_t::from_repr(r as u32).unwrap_or(sgx_status_t::SGX_ERROR_UNEXPECTED);
+                Error::from_sgx_error(status)
+            },
+            _ => Error::from_raw_os_error(err),
+        }
+    })
+}
+
 pub fn import_auto_key(path: &Path, key: &sgx_key_128bit_t) -> io::Result<()> {
 
     let path = cstr(path)?;
diff --git a/sgx_types/src/function.rs b/sgx_types/src/function.rs
index fcdd485..ed25827 100644
--- a/sgx_types/src/function.rs
+++ b/sgx_types/src/function.rs
@@ -174,9 +174,9 @@ extern {
     //
     // sgx_secure_align_api.h
     //
-    pub fn sgx_aligned_malloc(size: size_t, alignment: size_t, data: * mut align_req_t, count: size_t) -> * mut c_void;
+    pub fn sgx_aligned_malloc(size: size_t, alignment: size_t, data: * const align_req_t, count: size_t) -> * mut c_void;
     pub fn sgx_aligned_free(ptr: * mut c_void);
-    pub fn sgx_get_aligned_ptr(raw: * mut c_void, raw_size: size_t, allocate_size: size_t, alignment: size_t, data: * mut align_req_t, count: size_t) -> * mut c_void;
+    pub fn sgx_get_aligned_ptr(raw: * mut c_void, raw_size: size_t, allocate_size: size_t, alignment: size_t, data: * const align_req_t, count: size_t) -> * mut c_void;
 }
 
 //#[link(name = "sgx_tcrypto")]
diff --git a/sgx_types/src/metadata.rs b/sgx_types/src/metadata.rs
index 6cc8091..7bbe5c1 100644
--- a/sgx_types/src/metadata.rs
+++ b/sgx_types/src/metadata.rs
@@ -7,7 +7,7 @@ pub const SE_KEY_SIZE       :usize =  384;
 pub const SE_EXPONENT_SIZE  :usize =  4;
 
 /* arch.h */
-#[repr(packed)]
+#[repr(C, packed)]
 pub struct tcs_t {
     pub reserved0      :u64,
     pub flags          :u64,
@@ -24,7 +24,7 @@ pub struct tcs_t {
 }
 
 /* arch.h */
-#[repr(packed)]
+#[repr(C, packed)]
 pub struct css_header_t {
     pub header          :[u8; 12],
     pub css_type        :u32,  // type
@@ -35,14 +35,14 @@ pub struct css_header_t {
     pub reserved        :[u8; 84],
 }
 
-#[repr(packed)]
+#[repr(C, packed)]
 pub struct css_key_t {
     pub modulus         :[u8; SE_KEY_SIZE],
     pub exponent        :[u8; SE_EXPONENT_SIZE],
     pub signature       :[u8; SE_KEY_SIZE],
 }
 
-#[repr(packed)]
+#[repr(C, packed)]
 pub struct css_body_t {
     pub misc_select     :sgx_misc_select_t,
     pub misc_mask       :sgx_misc_select_t,
@@ -57,14 +57,14 @@ pub struct css_body_t {
     pub isv_svn         :u16,
 }
 
-#[repr(packed)]
+#[repr(C, packed)]
 pub struct css_buffer_t {
     pub reserved        :[u8; 12],
     pub q1              :[u8; SE_KEY_SIZE],
     pub q2              :[u8; SE_KEY_SIZE],
 }
 
-#[repr(packed)]
+#[repr(C, packed)]
 pub struct enclave_css_t {
     pub header          :css_header_t,
     pub key             :css_key_t,
diff --git a/sgx_types/src/types.rs b/sgx_types/src/types.rs
index 05188a8..b818ef1 100644
--- a/sgx_types/src/types.rs
+++ b/sgx_types/src/types.rs
@@ -74,6 +74,7 @@ impl_struct! {
 //
 // tseal_migration_attr.h
 //
+
 pub const FLAGS_NON_SECURITY_BITS: uint64_t   = (0x00FF_FFFF_FFFF_FFC0
                                                 | SGX_FLAGS_MODE64BIT
                                                 | SGX_FLAGS_PROVISION_KEY
@@ -172,7 +173,6 @@ impl_enum! {
 // sgx_ecp_types.h
 //
 
-
 pub const SGX_FEBITSIZE: uint32_t = 256;
 
 impl_struct!{
@@ -192,14 +192,12 @@ pub type sgx_ec_key_128bit_t = [uint8_t; SGX_CMAC_KEY_SIZE];
 // sgx_eid.h
 //
 
-
 pub type sgx_enclave_id_t = uint64_t;
 
 //
 // sgx_key.h
 //
 
-
 // Key Name
 pub const SGX_KEYSELECT_LICENSE: uint16_t          = 0x0000;
 pub const SGX_KEYSELECT_PROVISION: uint16_t        = 0x0001;
@@ -262,7 +260,6 @@ impl_struct_ContiguousMemory! {
 // sgx_key_exchange.h
 //
 
-
 pub type sgx_ra_context_t = uint32_t;
 pub type sgx_ra_key_128_t = sgx_key_128bit_t;
 
@@ -314,7 +311,6 @@ impl_struct_ContiguousMemory! {
 // sgx_quote.h
 //
 
-
 pub type sgx_epid_group_id_t = [uint8_t; 4];
 pub const SGX_PLATFORM_INFO_SIZE: size_t = 101;
 
@@ -403,7 +399,6 @@ impl_struct_ContiguousMemory! {
 // sgx_report.h
 //
 
-
 pub const SGX_HASH_SIZE: size_t   = 32;
 pub const SGX_MAC_SIZE: size_t    = 16;
 
@@ -502,7 +497,6 @@ impl_struct_ContiguousMemory! {
 // sgx_spinlock.h
 //
 
-// typedef volatile uint32_t sgx_spinlock_t;
 pub type sgx_spinlock_t = uint32_t;
 
 pub const SGX_SPINLOCK_INITIALIZER: uint32_t    = 0;
@@ -843,7 +837,6 @@ pub const SGX_THREAD_COND_INITIALIZER: sgx_thread_cond_t = sgx_thread_cond_t {
 // sgx_tkey_exchange.h
 //
 
-
 pub type sgx_ra_derive_secret_keys_t = extern "C" fn(p_shared_key: * const sgx_ec256_dh_shared_t,
                                                      kdf_id: uint16_t,
                                                      p_smk_key: * mut sgx_ec_key_128bit_t,
@@ -1252,6 +1245,7 @@ pub struct sgx_ql_qve_collateral_t {
 //
 // sgx_quote_3.h
 //
+
 pub const REF_QUOTE_MAX_AUTHENTICATON_DATA_SIZE: uint16_t = 64;
 
 impl_enum! {
@@ -1390,6 +1384,7 @@ impl_struct_ContiguousMemory! {
 //
 // sgx_ql_quote.h
 //
+
 impl_copy_clone! {
     #[repr(packed)]
     pub struct sgx_ql_qe_report_info_t {
@@ -1460,3 +1455,56 @@ impl_struct! {
         pub len: size_t,
     }
 }
+
+pub type sgx_mac_128bit_t = [uint8_t; 16];
+pub type sgx_key_256bit_t = [uint8_t; 32];
+pub type sgx_mac_256bit_t = [uint8_t; 32];
+
+#[repr(C, align(32))]
+#[derive(Copy, Clone, Default)]
+pub struct sgx_align_key_128bit_t {
+    _pad: [uint8_t; 16],
+    pub key: sgx_key_128bit_t,
+}
+
+#[repr(C, align(32))]
+#[derive(Copy, Clone, Default)]
+pub struct sgx_align_mac_128bit_t {
+    _pad: [uint8_t; 16],
+    pub mac: sgx_mac_128bit_t,
+}
+
+#[repr(C, align(64))]
+#[derive(Copy, Clone, Default)]
+pub struct sgx_align_key_256bit_t {
+    _pad: [uint8_t; 8],
+    pub key: sgx_key_256bit_t,
+}
+
+#[repr(C, align(64))]
+#[derive(Copy, Clone, Default)]
+pub struct sgx_align_mac_256bit_t {
+    _pad: [uint8_t; 8],
+    pub mac: sgx_mac_256bit_t,
+}
+
+#[repr(C, align(64))]
+#[derive(Copy, Clone, Default)]
+pub struct sgx_align_ec256_dh_shared_t {
+    _pad: [uint8_t; 8],
+    pub key: sgx_ec256_dh_shared_t,
+}
+
+#[repr(C, align(64))]
+#[derive(Copy, Clone, Default)]
+pub struct sgx_align_ec256_private_t {
+    _pad: [uint8_t; 8],
+    pub key: sgx_ec256_private_t,
+}
+
+unsafe impl ContiguousMemory for sgx_align_key_128bit_t {}
+unsafe impl ContiguousMemory for sgx_align_mac_128bit_t {}
+unsafe impl ContiguousMemory for sgx_align_key_256bit_t {}
+unsafe impl ContiguousMemory for sgx_align_mac_256bit_t {}
+unsafe impl ContiguousMemory for sgx_align_ec256_dh_shared_t {}
+unsafe impl ContiguousMemory for sgx_align_ec256_private_t {}
\ No newline at end of file
diff --git a/sgx_ucrypto/src/crypto.rs b/sgx_ucrypto/src/crypto.rs
index 0a779c6..73a8a0c 100644
--- a/sgx_ucrypto/src/crypto.rs
+++ b/sgx_ucrypto/src/crypto.rs
@@ -119,7 +119,6 @@ pub fn rsgx_sha256_slice<T>(src: &[T]) -> SgxResult<sgx_sha256_hash_t>
 }
 
 fn rsgx_sha256_init(sha_handle: &mut sgx_sha_state_handle_t) -> sgx_status_t {
-
     unsafe {
         sgx_sha256_init(sha_handle as * mut sgx_sha_state_handle_t)
     }
@@ -157,12 +156,10 @@ fn rsgx_sha256_update_slice<T>(src: &[T], sha_handle: sgx_sha_state_handle_t) ->
 }
 
 fn rsgx_sha256_get_hash(sha_handle: sgx_sha_state_handle_t, hash: &mut sgx_sha256_hash_t) -> sgx_status_t {
-
     unsafe { sgx_sha256_get_hash(sha_handle, hash as * mut sgx_sha256_hash_t) }
 }
 
 fn rsgx_sha256_close(sha_handle: sgx_sha_state_handle_t) -> sgx_status_t {
-
      unsafe { sgx_sha256_close(sha_handle) }
 }
 
@@ -205,7 +202,6 @@ pub fn rsgx_sha1_slice<T>(src: &[T]) -> SgxResult<sgx_sha1_hash_t>
 }
 
 fn rsgx_sha1_init(sha_handle: &mut sgx_sha_state_handle_t) -> sgx_status_t {
-
     unsafe {
         sgx_sha1_init(sha_handle as * mut sgx_sha_state_handle_t)
     }
@@ -243,12 +239,10 @@ fn rsgx_sha1_update_slice<T>(src: &[T], sha_handle: sgx_sha_state_handle_t) -> s
 }
 
 fn rsgx_sha1_get_hash(sha_handle: sgx_sha_state_handle_t, hash: &mut sgx_sha1_hash_t) -> sgx_status_t {
-
     unsafe { sgx_sha1_get_hash(sha_handle, hash as * mut sgx_sha1_hash_t) }
 }
 
 fn rsgx_sha1_close(sha_handle: sgx_sha_state_handle_t) -> sgx_status_t {
-
      unsafe { sgx_sha1_close(sha_handle) }
 }
 
@@ -309,7 +303,6 @@ impl SgxShaHandle {
     /// The SHA256 state is not initialized properly due to an internal cryptography library failure.
     ///
     pub fn init(&self) -> SgxError {
-
         if self.initflag.get() {
             return Ok(());
         }
@@ -425,7 +418,6 @@ impl SgxShaHandle {
     /// The SHA256 state passed in is likely problematic causing an internal cryptography library failure.
     ///
     pub fn get_hash(&self) -> SgxResult<sgx_sha256_hash_t> {
-
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
@@ -457,7 +449,6 @@ impl SgxShaHandle {
     /// The input handle is invalid.
     ///
     pub fn close(&self) -> SgxError {
-
         if !self.initflag.get() {
             return Ok(());
         }
@@ -513,7 +504,6 @@ impl SgxSha1Handle {
     }
 
     pub fn init(&self) -> SgxError {
-
         if self.initflag.get() {
             return Ok(());
         }
@@ -557,7 +547,6 @@ impl SgxSha1Handle {
     }
 
     pub fn get_hash(&self) -> SgxResult<sgx_sha1_hash_t> {
-
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
@@ -571,7 +560,6 @@ impl SgxSha1Handle {
     }
 
     pub fn close(&self) -> SgxError {
-
         if !self.initflag.get() {
             return Ok(());
         }
@@ -819,7 +807,6 @@ pub fn rsgx_rijndael128GCM_decrypt(key: &sgx_aes_gcm_128bit_key_t,
                                    aad: &[u8],
                                    mac: &sgx_aes_gcm_128bit_tag_t,
                                    dst: &mut [u8]) -> SgxError {
-
     let src_len = src.len();
     if src_len > u32::max_value() as usize {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
@@ -961,7 +948,6 @@ pub fn rsgx_rijndael128_cmac_slice<T>(key: &sgx_cmac_128bit_key_t, src: &[T]) ->
 }
 
 fn rsgx_cmac128_init(key: &sgx_cmac_128bit_key_t, cmac_handle: &mut sgx_cmac_state_handle_t) -> sgx_status_t {
-
     unsafe {
         sgx_cmac128_init(key as * const sgx_cmac_128bit_key_t,
                          cmac_handle as * mut sgx_cmac_state_handle_t)
@@ -999,12 +985,10 @@ fn rsgx_cmac128_update_slice<T>(src: &[T], cmac_handle: sgx_cmac_state_handle_t)
 }
 
 fn rsgx_cmac128_final(cmac_handle: sgx_cmac_state_handle_t, hash: &mut sgx_cmac_128bit_tag_t) -> sgx_status_t {
-
     unsafe { sgx_cmac128_final(cmac_handle, hash as * mut sgx_cmac_128bit_tag_t) }
 }
 
 fn rsgx_cmac128_close(cmac_handle: sgx_cmac_state_handle_t) -> sgx_status_t {
-
     unsafe { sgx_cmac128_close(cmac_handle) }
 }
 
@@ -1073,7 +1057,6 @@ impl SgxCmacHandle {
     /// An internal cryptography library failure occurred.
     ///
     pub fn init(&self, key: &sgx_cmac_128bit_key_t) -> SgxError {
-
         if self.initflag.get() {
             return Ok(());
         }
@@ -1194,7 +1177,6 @@ impl SgxCmacHandle {
     /// The CMAC state passed in is likely problematic causing an internal cryptography library failure.
     ///
     pub fn get_hash(&self) -> SgxResult<sgx_cmac_128bit_tag_t> {
-
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
@@ -1226,7 +1208,6 @@ impl SgxCmacHandle {
     /// The input handle is invalid.
     ///
     pub fn close(&self) -> SgxError {
-
         if !self.initflag.get() {
             return Ok(());
         }
@@ -1319,7 +1300,6 @@ pub fn rsgx_hmac_sha256_slice<T>(key: &sgx_hmac_256bit_key_t, src: &[T]) -> SgxR
 }
 
 fn rsgx_hmac256_init(key: &sgx_hmac_256bit_key_t, hmac_handle: &mut sgx_hmac_state_handle_t) -> sgx_status_t {
-
     unsafe {
         sgx_hmac256_init(key as * const sgx_hmac_256bit_key_t as * const u8,
                          SGX_HMAC256_KEY_SIZE as i32,
@@ -1358,7 +1338,6 @@ fn rsgx_hmac256_update_slice<T>(src: &[T], hmac_handle: sgx_hmac_state_handle_t)
 }
 
 fn rsgx_hmac256_final(hmac_handle: sgx_hmac_state_handle_t, hash: &mut sgx_hmac_256bit_tag_t) -> sgx_status_t {
-
     unsafe {
         sgx_hmac256_final(hash as * mut sgx_hmac_256bit_tag_t as * mut u8,
                           SGX_HMAC256_MAC_SIZE as i32,
@@ -1367,7 +1346,6 @@ fn rsgx_hmac256_final(hmac_handle: sgx_hmac_state_handle_t, hash: &mut sgx_hmac_
 }
 
 fn rsgx_hmac256_close(hmac_handle: sgx_hmac_state_handle_t) -> sgx_status_t {
-
     unsafe { sgx_hmac256_close(hmac_handle) }
 }
 
@@ -1386,7 +1364,6 @@ impl SgxHmacHandle {
     }
 
     pub fn init(&self, key: &sgx_hmac_256bit_key_t) -> SgxError {
-
         if self.initflag.get() {
             return Ok(());
         }
@@ -1430,7 +1407,6 @@ impl SgxHmacHandle {
     }
 
     pub fn get_hash(&self) -> SgxResult<sgx_hmac_256bit_tag_t> {
-
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
@@ -1444,7 +1420,6 @@ impl SgxHmacHandle {
     }
 
     pub fn close(&self) -> SgxError {
-
         if !self.initflag.get() {
             return Ok(());
         }
@@ -1671,12 +1646,10 @@ pub fn rsgx_aes_ctr_decrypt(key: &sgx_aes_ctr_128bit_key_t,
 }
 
 fn rsgx_ecc256_open_context(ecc_handle: &mut sgx_ecc_state_handle_t) -> sgx_status_t {
-
     unsafe { sgx_ecc256_open_context(ecc_handle as * mut _ as * mut sgx_ecc_state_handle_t) }
 }
 
 fn rsgx_ecc256_close_context(ecc_handle: sgx_ecc_state_handle_t) -> sgx_status_t {
-
     unsafe { sgx_ecc256_close_context(ecc_handle) }
 }
 
@@ -1691,7 +1664,6 @@ fn rsgx_ecc256_create_key_pair(private: &mut sgx_ec256_private_t,
 }
 
 fn rsgx_ecc256_check_point(point: &sgx_ec256_public_t, ecc_handle: sgx_ecc_state_handle_t, valid: &mut i32) -> sgx_status_t {
-
     unsafe { sgx_ecc256_check_point(point as * const sgx_ec256_public_t, ecc_handle, valid as * mut i32) }
 }
 
@@ -1712,7 +1684,6 @@ fn rsgx_ecc256_compute_shared_dhkey512(private_b: &sgx_ec256_private_t,
                                        public_ga: &sgx_ec256_public_t,
                                        shared_key: &mut sgx_ec256_dh_shared512_t,
                                        ecc_handle: sgx_ecc_state_handle_t) -> sgx_status_t {
-
     unsafe {
         sgx_ecc256_compute_shared_dhkey512(private_b as * const _ as * mut sgx_ec256_private_t,
                                            public_ga as * const _ as * mut sgx_ec256_public_t,
@@ -1784,7 +1755,6 @@ fn rsgx_ecdsa_verify_msg<T>(data: &T,
     }
 
     unsafe {
-
         let mut verify: u8 = 0;
         let ret = sgx_ecdsa_verify(data as * const _ as * const u8,
                                    size as u32,
@@ -1819,7 +1789,6 @@ fn rsgx_ecdsa_verify_slice<T>(data: &[T],
     }
 
     unsafe {
-
         let mut verify: u8 = 0;
         let ret = sgx_ecdsa_verify(data.as_ptr() as * const _ as * const u8,
                                    size as u32,
@@ -1843,9 +1812,7 @@ fn rsgx_ecdsa_verify_hash(hash: &sgx_sha256_hash_t,
                           signature: &sgx_ec256_signature_t,
                           result: &mut sgx_generic_ecresult_t,
                           ecc_handle: sgx_ecc_state_handle_t) -> sgx_status_t {
-
     unsafe {
-
         let mut verify: u8 = 0;
         let ret = sgx_ecdsa_verify_hash(hash as * const sgx_sha256_hash_t as * const u8,
                                         public as * const sgx_ec256_public_t,
@@ -1945,7 +1912,6 @@ impl SgxEccHandle {
     /// The ECC context state was not initialized properly due to an internal cryptography library failure.
     ///
     pub fn open(&self) -> SgxError {
-
         if self.initflag.get() {
             return Ok(());
         }
@@ -2016,7 +1982,6 @@ impl SgxEccHandle {
     /// The key creation process failed due to an internal cryptography library failure.
     ///
     pub fn create_key_pair(&self) -> SgxResult<(sgx_ec256_private_t, sgx_ec256_public_t)> {
-
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
@@ -2079,7 +2044,6 @@ impl SgxEccHandle {
     /// An internal cryptography library failure occurred.
     ///
     pub fn check_point(&self, point: &sgx_ec256_public_t) -> SgxResult<bool> {
-
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
@@ -2189,7 +2153,6 @@ impl SgxEccHandle {
     /// The key creation process failed due to an internal cryptography library failure.
     ///
     pub fn compute_shared_dhkey(&self, private_b: &sgx_ec256_private_t, public_ga: &sgx_ec256_public_t) -> SgxResult<sgx_ec256_dh_shared_t> {
-
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
@@ -2424,7 +2387,6 @@ impl SgxEccHandle {
                              hash: &sgx_sha256_hash_t,
                              public: &sgx_ec256_public_t,
                              signature: &sgx_ec256_signature_t) -> SgxResult<bool> {
-
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
@@ -2461,7 +2423,6 @@ impl SgxEccHandle {
     /// The input handle is invalid.
     ///
     pub fn close(&self) -> SgxError {
-
         if !self.initflag.get() {
             return Ok(());
         }
@@ -2730,7 +2691,6 @@ pub fn rsgx_create_rsa_key_pair(n_byte_size: i32,
                                 dmp1: &mut [u8],
                                 dmq1: &mut [u8],
                                 iqmp: &mut [u8]) -> SgxError {
-
     if (n_byte_size <= 0) || (e_byte_size <= 0) {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
@@ -2786,7 +2746,6 @@ fn rsgx_create_rsa_priv2_key(mod_size: i32,
                              dmq1: &[u8],
                              iqmp: &[u8],
                              new_pri_key: &mut sgx_rsa_key_t) -> sgx_status_t {
-
     if (mod_size <= 0) || (exp_size <= 0) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
@@ -2829,7 +2788,6 @@ fn rsgx_create_rsa_priv1_key(n_size: i32,
                             e: &[u8],
                             d: &[u8],
                             new_pri_key: &mut sgx_rsa_key_t) -> sgx_status_t {
-
     if (n_size <= 0) || (e_size <= 0) || (d_size <= 0) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
@@ -2859,7 +2817,6 @@ fn rsgx_create_rsa_pub1_key(mod_size: i32,
                            n: &[u8],
                            e: &[u8],
                            new_pub_key: &mut sgx_rsa_key_t) -> sgx_status_t {
-
     if (mod_size <= 0) || (exp_size <= 0) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
@@ -2883,7 +2840,6 @@ fn rsgx_free_rsa_key(rsa_key: sgx_rsa_key_t,
                      key_type: sgx_rsa_key_type_t,
                      mod_size: i32,
                      exp_size: i32) -> sgx_status_t {
-
     if (mod_size <= 0) || (exp_size <= 0) {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
@@ -2897,7 +2853,6 @@ fn rsgx_rsa_priv_decrypt_sha256(rsa_key: sgx_rsa_key_t,
                                 out_data: &mut [u8],
                                 out_len: &mut usize,
                                 in_data: &[u8]) -> sgx_status_t {
-
     if in_data.is_empty() {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
@@ -2924,7 +2879,6 @@ fn rsgx_rsa_pub_encrypt_sha256(rsa_key: sgx_rsa_key_t,
                                out_data: &mut [u8],
                                out_len: &mut usize,
                                in_data: &[u8]) -> sgx_status_t {
-
     if in_data.is_empty() {
         return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
@@ -2975,7 +2929,6 @@ impl SgxRsaPrivKey {
                   dmp1: &[u8],
                   dmq1: &[u8],
                   iqmp: &[u8]) -> SgxError {
-
         self.create2(mod_size, exp_size, e, p, q, dmp1, dmq1, iqmp)
     }
 
@@ -2988,7 +2941,6 @@ impl SgxRsaPrivKey {
                    dmp1: &[u8],
                    dmq1: &[u8],
                    iqmp: &[u8]) -> SgxError {
-
         if self.createflag.get() {
             return Ok(());
         }
@@ -3020,7 +2972,6 @@ impl SgxRsaPrivKey {
                    n: &[u8],
                    e: &[u8],
                    d: &[u8]) -> SgxError {
-
         if self.createflag.get() {
             return Ok(());
         }
@@ -3047,7 +2998,6 @@ impl SgxRsaPrivKey {
                           out_data: &mut [u8],
                           out_len: &mut usize,
                           in_data: &[u8]) -> SgxError {
-
         if !self.createflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
@@ -3065,7 +3015,6 @@ impl SgxRsaPrivKey {
     }
 
     pub fn free(&self) -> SgxError {
-
         if !self.createflag.get() {
             return Ok(());
         }
@@ -3128,7 +3077,6 @@ impl SgxRsaPubKey {
                   exp_size: i32,
                   n: &[u8],
                   e: &[u8]) -> SgxError {
-
         if self.createflag.get() {
             return Ok(());
         }
@@ -3153,7 +3101,6 @@ impl SgxRsaPubKey {
                           out_data: &mut [u8],
                           out_len: &mut usize,
                           in_data: &[u8]) -> SgxError {
-
         if !self.createflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
@@ -3171,7 +3118,6 @@ impl SgxRsaPubKey {
     }
 
     pub fn free(&self) -> SgxError {
-
         if !self.createflag.get() {
             return Ok(());
         }
@@ -3249,7 +3195,6 @@ impl Drop for SgxRsaPubKey {
 pub fn rsgx_calculate_ecdsa_priv_key(hash_drg: &[u8],
                                      sgx_nistp256_r_m1: &[u8],
                                      out_key: &mut [u8]) -> SgxError {
-
     if (hash_drg.is_empty()) || (hash_drg.len() > i32::max_value() as usize) {
         return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
     }
@@ -3268,7 +3213,6 @@ pub fn rsgx_calculate_ecdsa_priv_key(hash_drg: &[u8],
                                      out_key.as_mut_ptr(),
                                      out_key.len() as i32)
     };
-
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(()),
         _ => Err(ret),
@@ -3277,33 +3221,65 @@ pub fn rsgx_calculate_ecdsa_priv_key(hash_drg: &[u8],
 
 pub fn rsgx_ecc256_calculate_pub_from_priv(priv_key: &sgx_ec256_private_t,
                                            pub_key: &mut sgx_ec256_public_t) -> SgxError {
-
     let ret = unsafe {
         sgx_ecc256_calculate_pub_from_priv(priv_key as * const sgx_ec256_private_t,
                                            pub_key as * mut sgx_ec256_public_t)
     };
-
     match ret {
         sgx_status_t::SGX_SUCCESS => Ok(()),
         _ => Err(ret),
     }
 }
 
+pub fn rsgx_ecc256_priv_key(hash_drg: &[u8], sgx_nistp256_r_m1: &[u8]) -> SgxResult<sgx_ec256_private_t> {
+    if (hash_drg.is_empty()) || (hash_drg.len() > i32::max_value() as usize) {
+        return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
+    }
+    if (sgx_nistp256_r_m1.is_empty()) || (sgx_nistp256_r_m1.len() > i32::max_value() as usize) {
+        return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
+    }
+
+    let mut priv_key = sgx_ec256_private_t::default();
+    let ret = unsafe {
+        sgx_calculate_ecdsa_priv_key(hash_drg.as_ptr(),
+                                     hash_drg.len() as i32,
+                                     sgx_nistp256_r_m1.as_ptr(),
+                                     sgx_nistp256_r_m1.len() as i32,
+                                     &mut priv_key as * mut sgx_ec256_private_t as * mut u8,
+                                     mem::size_of::<sgx_ec256_private_t>() as i32)
+    };
+    match ret {
+        sgx_status_t::SGX_SUCCESS => Ok(priv_key),
+        _ => Err(ret),
+    }
+}
+
+pub fn rsgx_ecc256_pub_from_priv(priv_key: &sgx_ec256_private_t) -> SgxResult<sgx_ec256_public_t> {
+    let mut pub_key = sgx_ec256_public_t::default();
+    let ret = unsafe {
+        sgx_ecc256_calculate_pub_from_priv(priv_key as * const sgx_ec256_private_t,
+                                           &mut pub_key as * mut sgx_ec256_public_t)
+    };
+    match ret {
+        sgx_status_t::SGX_SUCCESS => Ok(pub_key),
+        _ => Err(ret),
+    }
+}
+
 fn rsgx_aes_gcm128_enc_init(key: &sgx_aes_gcm_128bit_key_t,
                             iv: &[u8],
                             aad: &[u8],
-                            aes_gcm_state: &mut sgx_aes_state_handle_t) -> SgxError {
-
+                            aes_gcm_state: &mut sgx_aes_state_handle_t) -> sgx_status_t {
     let iv_len = iv.len();
     if iv_len != SGX_AESGCM_IV_SIZE {
-        return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
+        return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
     let aad_len = aad.len();
     if aad_len > u32::max_value() as usize {
-        return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
+        return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
 
-    let ret = unsafe {
+    unsafe {
         let p_aad = if !aad.is_empty() { aad.as_ptr() } else { ptr::null() };
         sgx_aes_gcm128_enc_init(key as * const sgx_aes_gcm_128bit_key_t as * const u8,
                                 iv.as_ptr(),
@@ -3311,63 +3287,44 @@ fn rsgx_aes_gcm128_enc_init(key: &sgx_aes_gcm_128bit_key_t,
                                 p_aad,
                                 aad_len as u32,
                                 aes_gcm_state as * mut sgx_aes_state_handle_t)
-    };
-    match ret {
-        sgx_status_t::SGX_SUCCESS => Ok(()),
-        _ => Err(ret),
     }
 }
 
 fn rsgx_aes_gcm128_enc_update(src: &[u8],
                               dst: &mut [u8],
-                              aes_gcm_state: sgx_aes_state_handle_t) -> SgxError {
-
+                              aes_gcm_state: sgx_aes_state_handle_t) -> sgx_status_t {
     let src_len = src.len();
     if src_len > u32::max_value() as usize {
-        return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
+        return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
     if src_len == 0 {
-        return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
+        return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
     let dst_len = dst.len();
     if dst_len > u32::max_value() as usize {
-        return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
+        return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
     if dst_len == 0 || dst_len < src_len {
-        return Err(sgx_status_t::SGX_ERROR_INVALID_PARAMETER);
+        return sgx_status_t::SGX_ERROR_INVALID_PARAMETER;
     }
 
-    let ret = unsafe {
+    unsafe {
         sgx_aes_gcm128_enc_update(src.as_ptr(),
                                   src_len as u32,
                                   dst.as_mut_ptr(),
                                   aes_gcm_state)
-    };
-    match ret {
-        sgx_status_t::SGX_SUCCESS => Ok(()),
-        _ => Err(ret),
     }
 }
 
-fn rsgx_aes_gcm128_enc_get_mac(aes_gcm_state: sgx_aes_state_handle_t) -> SgxResult<sgx_aes_gcm_128bit_tag_t> {
-
-    let mut mac = sgx_aes_gcm_128bit_tag_t::default();
-    let ret = unsafe {
-        sgx_aes_gcm128_enc_get_mac(&mut mac as * mut sgx_aes_gcm_128bit_tag_t as * mut u8 , aes_gcm_state)
-    };
-    match ret {
-        sgx_status_t::SGX_SUCCESS => Ok(mac),
-        _ => Err(ret),
+fn rsgx_aes_gcm128_enc_get_mac(mac: &mut sgx_aes_gcm_128bit_tag_t,
+                               aes_gcm_state: sgx_aes_state_handle_t) -> sgx_status_t {
+    unsafe {
+        sgx_aes_gcm128_enc_get_mac(mac as * mut sgx_aes_gcm_128bit_tag_t as * mut u8, aes_gcm_state)
     }
 }
 
-fn rsgx_aes_gcm_close(aes_gcm_state: sgx_aes_state_handle_t) -> SgxError {
-
-    let ret = unsafe { sgx_aes_gcm_close(aes_gcm_state) };
-    match ret {
-        sgx_status_t::SGX_SUCCESS => Ok(()),
-        _ => Err(ret),
-    }
+fn rsgx_aes_gcm_close(aes_gcm_state: sgx_aes_state_handle_t) -> sgx_status_t {
+    unsafe { sgx_aes_gcm_close(aes_gcm_state) }
 }
 
 pub struct SgxAesHandle {
@@ -3385,31 +3342,40 @@ impl SgxAesHandle {
     }
 
     pub fn init(&self, key: &sgx_aes_gcm_128bit_key_t, iv: &[u8], aad: &[u8]) -> SgxError {
-
         if self.initflag.get() {
             return Ok(());
         }
-        rsgx_aes_gcm128_enc_init(key, iv, aad, self.handle.borrow_mut().deref_mut())
+        let ret = rsgx_aes_gcm128_enc_init(key, iv, aad, self.handle.borrow_mut().deref_mut());
+        match ret {
+            sgx_status_t::SGX_SUCCESS => Ok(()),
+            _ => Err(ret),
+        }
     }
 
     pub fn update(&self, src: &[u8], dst: &mut [u8]) -> SgxError {
-
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
-        rsgx_aes_gcm128_enc_update(src, dst, *self.handle.borrow())
+        let ret = rsgx_aes_gcm128_enc_update(src, dst, *self.handle.borrow());
+        match ret {
+            sgx_status_t::SGX_SUCCESS => Ok(()),
+            _ => Err(ret),
+        }
     }
 
     pub fn get_mac(&self) -> SgxResult<sgx_aes_gcm_128bit_tag_t> {
-
         if !self.initflag.get() {
             return Err(sgx_status_t::SGX_ERROR_INVALID_STATE);
         }
-        rsgx_aes_gcm128_enc_get_mac(*self.handle.borrow())
+        let mut mac = sgx_aes_gcm_128bit_tag_t::default();
+        let ret = rsgx_aes_gcm128_enc_get_mac(&mut mac, *self.handle.borrow());
+        match ret {
+            sgx_status_t::SGX_SUCCESS => Ok(mac),
+            _ => Err(ret),
+        }
     }
 
     pub fn close(&self) -> SgxError {
-
         if !self.initflag.get() {
             return Ok(());
         }
@@ -3417,17 +3383,19 @@ impl SgxAesHandle {
         let ret = {
             let handle = *self.handle.borrow();
             if handle.is_null() {
-                Ok(())
+                sgx_status_t::SGX_SUCCESS
             } else {
                 rsgx_aes_gcm_close(handle)
             }
         };
-
-        if ret.is_ok() {
-            self.initflag.set(false);
-            *self.handle.borrow_mut() = ptr::null_mut();
+        match ret {
+            sgx_status_t::SGX_SUCCESS => {
+                self.initflag.set(false);
+                *self.handle.borrow_mut() = ptr::null_mut();
+                Ok(())
+            },
+            _ => Err(ret),
         }
-        ret
     }
 }
 
diff --git a/sgx_ucrypto/src/util.rs b/sgx_ucrypto/src/util.rs
index 65adac7..20b0f8c 100644
--- a/sgx_ucrypto/src/util.rs
+++ b/sgx_ucrypto/src/util.rs
@@ -22,7 +22,7 @@ const SIZE_MAX: size_t = std::usize::MAX;
 #[allow(clippy::absurd_extreme_comparisons)]
 #[no_mangle]
 pub extern "C"
-fn memset_s(p : *mut c_void,
+fn memset_s(p: *mut c_void,
             destsz: size_t,
             ch: c_int,
             count: size_t) -> errno_t {


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


Mime
View raw message