Integrate with Security Keys HAL API 30/319330/37
authorJakub Wlostowski <j.wlostowski@samsung.com>
Fri, 7 Feb 2025 12:00:58 +0000 (13:00 +0100)
committerDariusz Michaluk <d.michaluk@samsung.com>
Tue, 8 Apr 2025 08:35:10 +0000 (10:35 +0200)
Change-Id: I56314a91f69070f09edbc62b940b2d24627f21db

19 files changed:
CMakeLists.txt
misc/ckm_db_tool/CMakeLists.txt
misc/db_perf/CMakeLists.txt
misc/encryption_scheme/CMakeLists.txt
packaging/key-manager.spec
src/CMakeLists.txt
src/manager/crypto/platform/decider.cpp
src/manager/crypto/tz-backend/hal-context.cpp [new file with mode: 0644]
src/manager/crypto/tz-backend/hal-context.h [new file with mode: 0644]
src/manager/crypto/tz-backend/internals.cpp
src/manager/crypto/tz-backend/tz-context.cpp [deleted file]
src/manager/crypto/tz-backend/tz-context.h [deleted file]
src/manager/crypto/tz-backend/tz-memory.cpp [deleted file]
src/manager/crypto/tz-backend/tz-memory.h [deleted file]
src/manager/crypto/tz-backend/tz-serializer.cpp [deleted file]
src/manager/crypto/tz-backend/tz-serializer.h [deleted file]
src/manager/service/ckm-service.cpp
unit-tests/CMakeLists.txt
unit-tests/test_serialization.cpp

index ecfc13d0445986e7a0a0d6a0f80d0b13835b2779..4eac45634538920d878a242beb0f0a5b94ae6cff 100644 (file)
@@ -79,16 +79,14 @@ ADD_DEFINITIONS("-DCOVERAGE_DIR=\"${COVERAGE_DIR}\"")
 
 IF (TZ_BACKEND_ENABLED)
     ADD_DEFINITIONS("-DTZ_BACKEND_ENABLED")
-    SET(EXTRA_KM_DEPS ${EXTRA_KM_DEPS} tef-libteec)
-    SET(KM_LINK_EXTRA_DEPS km_serialization)
+    PKG_CHECK_MODULES(HAL_DEP REQUIRED hal-api-security)
+
     SET(TZ_BACKEND_SOURCES
         ${KEY_MANAGER_PATH}/crypto/tz-backend/internals.cpp
         ${KEY_MANAGER_PATH}/crypto/tz-backend/obj.cpp
         ${KEY_MANAGER_PATH}/crypto/tz-backend/ctx.cpp
         ${KEY_MANAGER_PATH}/crypto/tz-backend/store.cpp
-        ${KEY_MANAGER_PATH}/crypto/tz-backend/tz-context.cpp
-        ${KEY_MANAGER_PATH}/crypto/tz-backend/tz-memory.cpp
-        ${KEY_MANAGER_PATH}/crypto/tz-backend/tz-serializer.cpp
+        ${KEY_MANAGER_PATH}/crypto/tz-backend/hal-context.cpp
     )
 ENDIF()
 
index a061da949d99eca865e510de84f2b894c12471cb..c77c370a3827224800658cad8a30a9bc5d9afd11 100644 (file)
@@ -8,6 +8,7 @@ FIND_PACKAGE(Threads REQUIRED)
 
 INCLUDE_DIRECTORIES(
     ${KEY_MANAGER_DEP_INCLUDE_DIRS}
+    ${HAL_DEP_INCLUDE_DIRS}
     ${CMAKE_CURRENT_SOURCE_DIR}
     ${PROJECT_SOURCE_DIR}/common
     ${KEY_MANAGER_PATH}/main
@@ -68,15 +69,15 @@ SET(CKM_DB_TOOLS_SOURCES
     ${SE_BACKEND_SOURCES}
     )
 
-LINK_DIRECTORIES(${CKM_DB_TOOL_DEP_LIBRARY_DIRS})
+LINK_DIRECTORIES(${CKM_DB_TOOL_DEP_LIBRARY_DIRS} ${HAL_DEP_LIBRARY_DIRS})
 
 ADD_EXECUTABLE(${CKM_DB_TOOL} ${CKM_DB_TOOLS_SOURCES} ${CMAKE_CURRENT_SOURCE_DIR}/ckm_db_tool.cpp)
 
 TARGET_LINK_LIBRARIES(${CKM_DB_TOOL}
     ${CMAKE_THREAD_LIBS_INIT}
     ${KEY_MANAGER_DEP_LIBRARIES}
-    ${KM_LINK_EXTRA_DEPS}
     ${TARGET_KEY_MANAGER_COMMON}
+    ${HAL_DEP_LIBRARIES}
     -ldl
     )
 
@@ -85,8 +86,8 @@ ADD_EXECUTABLE(${CKM_DB_MERGE} ${CKM_DB_TOOLS_SOURCES} ${CMAKE_CURRENT_SOURCE_DI
 TARGET_LINK_LIBRARIES(${CKM_DB_MERGE}
     ${CMAKE_THREAD_LIBS_INIT}
     ${KEY_MANAGER_DEP_LIBRARIES}
-    ${KM_LINK_EXTRA_DEPS}
     ${TARGET_KEY_MANAGER_COMMON}
+    ${HAL_DEP_LIBRARIES}
     -ldl
     )
 
index ca9608bbcf3c36b04db45cd6158c76613fa9694d..a3bf0445af8facf3789a93dd72465140bfef3f18 100644 (file)
@@ -49,7 +49,6 @@ TARGET_LINK_LIBRARIES(
     ${TARGET_CKM_DB_PERF}
     ${TARGET_KEY_MANAGER_COMMON}
     ${KEY_MANAGER_DEP_LIBRARIES}
-    ${KM_LINK_EXTRA_DEPS}
     boost_unit_test_framework
     -ldl
 )
index c44b47bb0d9088831ea2efa3eecc0ec679349fbb..ca322e89b67d9998dc034ab7160f51790370e112 100644 (file)
@@ -26,7 +26,6 @@ SET(ENCRYPTION_SCHEME_COMMON_LINK_OPTIONS
     ${TARGET_KEY_MANAGER_CLIENT}
     ${TARGET_KEY_MANAGER_CONTROL_CLIENT}
     ${KEY_MANAGER_DEP_LIBRARIES}
-    ${KM_LINK_EXTRA_DEPS}
     ${CMAKE_THREAD_LIBS_INIT}
     boost_unit_test_framework
     -ldl
index 6f1960640365ed5c163cd9f876ebb5a2643a908e..276900452bdcde7e33c16bdce386f6f3ea0df523 100644 (file)
@@ -44,9 +44,7 @@ BuildRequires: pkgconfig(argos_watchdog)
 BuildRequires: boost-devel
 BuildRequires: ca-certificates-devel
 %if %{tz_backend_enabled} == ON
-BuildRequires: key-manager-ta-devel
-BuildRequires: key-manager-ta-serialization-devel
-BuildRequires: pkgconfig(tef-libteec)
+BuildRequires: pkgconfig(hal-api-security)
 %endif
 %if %{se_backend_enabled} == ON
 BuildRequires: pkgconfig(key-manager-se-backend)
index fea604a10d1907a31182d4cd6bfeb6a3c2c52638..c9d9b30d0b80fa748bc21c4c2db866384e187137 100644 (file)
@@ -64,6 +64,7 @@ SET_SOURCE_FILES_PROPERTIES(
 
 INCLUDE_DIRECTORIES(SYSTEM
     ${KEY_MANAGER_DEP_INCLUDE_DIRS}
+    ${HAL_DEP_INCLUDE_DIRS}
     )
 
 INCLUDE_DIRECTORIES(
@@ -79,7 +80,7 @@ INCLUDE_DIRECTORIES(
     ${KEY_MANAGER_PATH}/crypto
     )
 
-LINK_DIRECTORIES(${KEY_MANAGER_DEP_LIBRARY_DIRS})
+LINK_DIRECTORIES(${KEY_MANAGER_DEP_LIBRARY_DIRS} ${HAL_DEP_LIBRARY_DIRS})
 
 ADD_EXECUTABLE(${TARGET_KEY_MANAGER} ${KEY_MANAGER_SOURCES})
 
@@ -87,7 +88,7 @@ TARGET_LINK_LIBRARIES(${TARGET_KEY_MANAGER}
     ${CMAKE_THREAD_LIBS_INIT}
     ${KEY_MANAGER_DEP_LIBRARIES}
     ${TARGET_KEY_MANAGER_COMMON}
-    ${KM_LINK_EXTRA_DEPS}
+    ${HAL_DEP_LIBRARIES}
     -ldl
     )
 ################################################################################
index d8a15fdada3657c6c160937329cdb14475532778..9118bf5599d83078f70b08049b6323837f9a31da 100644 (file)
@@ -28,7 +28,7 @@
 #include <generic-backend/exception.h>
 
 #ifdef TZ_BACKEND_ENABLED
-#include <tz-backend/tz-context.h>
+#include <tz-backend/hal-context.h>
 #endif // TZ_BACKEND_ENABLED
 
 namespace CKM {
@@ -75,7 +75,7 @@ GStore* Decider::tryBackend(CryptoBackend backend)
 #ifdef TZ_BACKEND_ENABLED
                try {
                        LogDebug("Trying to open TA session...");
-                       TZ::Internals::TrustZoneContext::Instance();
+                       TZ::Internals::HalContext::Instance();
                        LogDebug("...succeeded. Selecting TZ backend.");
                        return &m_tzStore;
                } catch (const Exc::Crypto::InternalError& e) {
diff --git a/src/manager/crypto/tz-backend/hal-context.cpp b/src/manager/crypto/tz-backend/hal-context.cpp
new file mode 100644 (file)
index 0000000..8f77b46
--- /dev/null
@@ -0,0 +1,60 @@
+/*
+ *  Copyright (c) 2025 Samsung Electronics Co., Ltd. All rights reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+
+#include <tz-backend/hal-context.h>
+#include <generic-backend/exception.h>
+#include <dpl/log/log.h>
+
+namespace CKM {
+namespace Crypto {
+namespace TZ {
+namespace Internals {
+
+HalContext::HalContext()
+{
+       int error = hal_security_keys_context_initialize(&m_hal_context);
+       if (error)
+               ThrowErr(Exc::InternalError, "Failed initializing Security Keys backend");
+}
+
+HalContext::~HalContext()
+{
+       hal_security_keys_context_free(&m_hal_context);
+}
+
+HalContext& HalContext::Instance()
+{
+       static HalContext instance;
+       return instance;
+}
+
+hal_security_keys_context_s& HalContext::GetHalContext()
+{
+       return m_hal_context;
+}
+
+void HalContext::ReloadHalContext()
+{
+       hal_security_keys_context_free(&m_hal_context);
+       int error = hal_security_keys_context_initialize(&m_hal_context);
+       if (error)
+               ThrowErr(Exc::InternalError, "Failed reinitializing Security Keys backend");
+}
+
+} // namespace Internals
+} // namespace TZ
+} // namespace Crypto
+} // namespace CKM
diff --git a/src/manager/crypto/tz-backend/hal-context.h b/src/manager/crypto/tz-backend/hal-context.h
new file mode 100644 (file)
index 0000000..8d2283c
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ *  Copyright (c) 2025 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+
+#pragma once
+
+#include <hal/hal-security-keys.h>
+
+namespace CKM {
+namespace Crypto {
+namespace TZ {
+namespace Internals {
+
+class HalContext final
+{
+public:
+       static HalContext& Instance();
+       hal_security_keys_context_s& GetHalContext();
+       void ReloadHalContext();
+
+private:
+       HalContext();
+       ~HalContext();
+       HalContext(const HalContext &other) = delete;
+       HalContext(HalContext &&other) = delete;
+
+       hal_security_keys_context_s m_hal_context;
+};
+
+} // namespace Internals
+} // namespace TZ
+} // namespace Crypto
+} // namespace CKM
index ec6cf9e4ce3c1ce3d96661ffab185ca8f3268348..4cac52b90709fb304a86f33c1af875d847101863 100644 (file)
  *  See the License for the specific language governing permissions and
  *  limitations under the License
  */
-/*
- * @file       internals.h
- * @author     Krzysztof Dynowski (k.dynowski@samsung.com)
- * @author     Lukasz Kostyra (l.kostyra@samsung.com)
- * @version    1.0
- */
 
 #include <generic-backend/exception.h>
 #include <generic-backend/algo-validation.h>
 #include <openssl/evp.h>
 #include <openssl/dsa.h>
 #include <openssl/ec.h>
-#include <openssl/bio.h>
 #include <openssl/bn.h>
 
 #include <tz-backend/internals.h>
-#include <tz-backend/tz-context.h>
+#include <tz-backend/hal-context.h>
 #include <openssl-error-handler.h>
-#include <km_ta_defines.h>
 #include <key-impl.h>
+#include <hal/hal-security-keys.h>
 
 #include <functional>
 
@@ -67,7 +60,7 @@ CKM::RawBuffer extractBignumData(const BIGNUM* bn)
 }
 
 void generateDSAParams(const int sizeBits, CKM::RawBuffer &prime,
-                                       CKM::RawBuffer &subprime, CKM::RawBuffer &base)
+                                          CKM::RawBuffer &subprime, CKM::RawBuffer &base)
 {
        auto dsa = uptr<DSA_free>(DSA_new());
        if (!dsa) {
@@ -89,74 +82,210 @@ void generateDSAParams(const int sizeBits, CKM::RawBuffer &prime,
        base = extractBignumData(g);
 }
 
-tz_data_type toTzDataType(const CKM::DataType dataType) {
-       switch (dataType) {
-       case CKM::DataType::BINARY_DATA:       return TYPE_GENERIC_SECRET;
-       case CKM::DataType::KEY_AES:           return TYPE_SKEY;
-       case CKM::DataType::KEY_DSA_PRIVATE:   return TYPE_AKEY_PRIVATE_DSA;
-       case CKM::DataType::KEY_RSA_PRIVATE:   return TYPE_AKEY_PRIVATE_RSA;
-       case CKM::DataType::KEY_ECDSA_PRIVATE: return TYPE_AKEY_PRIVATE_EC;
-       case CKM::DataType::KEY_KEM_PRIVATE:   return TYPE_AKEY_PRIVATE_KEM;
-       case CKM::DataType::KEY_DSA_PUBLIC:    return TYPE_AKEY_PUBLIC_DSA;
-       case CKM::DataType::KEY_RSA_PUBLIC:    return TYPE_AKEY_PUBLIC_RSA;
-       case CKM::DataType::KEY_ECDSA_PUBLIC:  return TYPE_AKEY_PUBLIC_EC;
-       case CKM::DataType::KEY_KEM_PUBLIC:    return TYPE_AKEY_PUBLIC_KEM;
-       default:
-               ThrowErr(CKM::Exc::Crypto::DataTypeNotSupported,
-                       "Data type could not be imported by tz-backend");
+struct data_free_deleter {
+       void operator()(hal_security_keys_data_s* p) const {
+               if (p->buffer)
+                       free(p->buffer);
+               delete p;
+       }
+};
+
+class security_keys_data_ptr {
+public:
+       security_keys_data_ptr() : data(new hal_security_keys_data_s{nullptr, 0}) {}
+
+       hal_security_keys_data_s* Get() {
+               return data.get();
+       }
+
+       unsigned char* GetBuffer() {
+               return data->buffer;
+       }
+
+       size_t GetLength() {
+               return data->length;
+       }
+
+private:
+       std::unique_ptr<hal_security_keys_data_s, data_free_deleter> data;
+};
+
+hal_security_keys_data_s convertToHalData(const CKM::RawBuffer &buffer)
+{
+       return {const_cast<unsigned char*>(buffer.data()), buffer.size()};
+}
+
+hal_security_keys_password_iv_s convertToHalPwdIv(const CKM::RawBuffer &pwd, const CKM::RawBuffer &iv)
+{
+       hal_security_keys_password_iv_s halPwdIv = {
+               {convertToHalData(pwd)},
+               {convertToHalData(iv)},
+       };
+
+       return halPwdIv;
+}
+
+hal_security_keys_password_iv_tag_s convertToHalPwdIvTag(const CKM::Crypto::TZ::Pwd &pwd)
+{
+       hal_security_keys_password_iv_tag_s halPwdIvTag = {
+               {convertToHalData(pwd.getPassword())},
+               {convertToHalData(pwd.getIV())},
+               {convertToHalData(pwd.getTag())}
+       };
+
+       return halPwdIvTag;
+}
+
+hal_security_keys_algo_type_e convertToHalAlgoType(CKM::AlgoType type)
+{
+       switch (type) {
+               case CKM::AlgoType::AES_CTR:    return HAL_SECURITY_KEYS_ALGO_TYPE_AES_CTR;
+               case CKM::AlgoType::AES_CBC:    return HAL_SECURITY_KEYS_ALGO_TYPE_AES_CBC;
+               case CKM::AlgoType::AES_GCM:    return HAL_SECURITY_KEYS_ALGO_TYPE_AES_GCM;
+               case CKM::AlgoType::AES_CFB:    return HAL_SECURITY_KEYS_ALGO_TYPE_AES_CFB;
+               case CKM::AlgoType::RSA_OAEP:   return HAL_SECURITY_KEYS_ALGO_TYPE_RSA_OAEP;
+               case CKM::AlgoType::RSA_SV:             return HAL_SECURITY_KEYS_ALGO_TYPE_RSA;
+               case CKM::AlgoType::DSA_SV:             return HAL_SECURITY_KEYS_ALGO_TYPE_DSA;
+               case CKM::AlgoType::ECDSA_SV:   return HAL_SECURITY_KEYS_ALGO_TYPE_ECDSA;
+               default: ThrowErr(CKM::Exc::Crypto::InputParam, "Requested algorithm is not supported");
+       }
+}
+
+hal_security_keys_ec_type_e convertToHalEcType(CKM::ElipticCurve ec)
+{
+       switch (ec) {
+               case CKM::ElipticCurve::prime192v1:     return HAL_SECURITY_KEYS_EC_TYPE_PRIME192V1;
+               case CKM::ElipticCurve::prime256v1:     return HAL_SECURITY_KEYS_EC_TYPE_PRIME256V1;
+               case CKM::ElipticCurve::secp384r1:      return HAL_SECURITY_KEYS_EC_TYPE_SECP384R1;
+               default: ThrowErr(CKM::Exc::Crypto::InputParam, "Requested param is not supported");
+       }
+}
+
+hal_security_keys_kem_type_e convertToHalKemType(CKM::KemType kt)
+{
+       switch (kt) {
+               case CKM::KemType::ML_KEM_768:  return HAL_SECURITY_KEYS_ML_KEM_768;
+               case CKM::KemType::ML_KEM_1024: return HAL_SECURITY_KEYS_ML_KEM_1024;
+               default: ThrowErr(CKM::Exc::Crypto::InputParam, "Requested param is not supported");
        }
 }
 
-tz_ec toTzEc(CKM::ElipticCurve ec)
+hal_security_keys_data_type_e convertToHalDataType(CKM::DataType type)
 {
-       switch(ec) {
-       case CKM::ElipticCurve::prime192v1: return EC_NIST_P192;
-       case CKM::ElipticCurve::prime256v1: return EC_NIST_P256;
-       case CKM::ElipticCurve::secp384r1: return EC_NIST_P384;
-       default: ThrowErr(CKM::Exc::Crypto::DataTypeNotSupported, "EC not supported by tz-backend");
+       switch (type) {
+               case CKM::DataType::BINARY_DATA:
+                       return HAL_SECURITY_KEYS_DATA_TYPE_BINARY_DATA;
+               case CKM::DataType::KEY_AES:
+                       return HAL_SECURITY_KEYS_DATA_TYPE_KEY_AES;
+               case CKM::DataType::KEY_RSA_PUBLIC:
+                       return HAL_SECURITY_KEYS_DATA_TYPE_KEY_RSA_PUBLIC;
+               case CKM::DataType::KEY_RSA_PRIVATE:
+                       return HAL_SECURITY_KEYS_DATA_TYPE_KEY_RSA_PRIVATE;
+               case CKM::DataType::KEY_DSA_PUBLIC:
+                       return HAL_SECURITY_KEYS_DATA_TYPE_KEY_DSA_PUBLIC;
+               case CKM::DataType::KEY_DSA_PRIVATE:
+                       return HAL_SECURITY_KEYS_DATA_TYPE_KEY_DSA_PRIVATE;
+               case CKM::DataType::KEY_ECDSA_PUBLIC:
+                       return HAL_SECURITY_KEYS_DATA_TYPE_KEY_ECDSA_PUBLIC;
+               case CKM::DataType::KEY_ECDSA_PRIVATE:
+                       return HAL_SECURITY_KEYS_DATA_TYPE_KEY_ECDSA_PRIVATE;
+               case CKM::DataType::KEY_KEM_PUBLIC:
+                       return HAL_SECURITY_KEYS_DATA_TYPE_KEY_KEM_PUBLIC;
+               case CKM::DataType::KEY_KEM_PRIVATE:
+                       return HAL_SECURITY_KEYS_DATA_TYPE_KEY_KEM_PRIVATE;
+               default:
+                       ThrowErr(CKM::Exc::Crypto::InputParam, "Data type could not be imported by tz-backend");
        }
 }
 
-tz_kem toTzKem(CKM::KemType kem)
+hal_security_keys_hash_algorithm_e convertToHalHashType(CKM::HashAlgorithm hash)
 {
-       switch(kem) {
-       case CKM::KemType::ML_KEM_768: return ML_KEM_768;
-       case CKM::KemType::ML_KEM_1024: return ML_KEM_1024;
-       default: ThrowErr(CKM::Exc::Crypto::InputParam, "KEM not supported by tz-backend");
+       switch (hash) {
+               case CKM::HashAlgorithm::NONE:          return HAL_SECURITY_KEYS_HASH_ALGORITHM_NONE;
+               case CKM::HashAlgorithm::SHA1:          return HAL_SECURITY_KEYS_HASH_ALGORITHM_SHA1;
+               case CKM::HashAlgorithm::SHA256:        return HAL_SECURITY_KEYS_HASH_ALGORITHM_SHA256;
+               case CKM::HashAlgorithm::SHA384:        return HAL_SECURITY_KEYS_HASH_ALGORITHM_SHA384;
+               case CKM::HashAlgorithm::SHA512:        return HAL_SECURITY_KEYS_HASH_ALGORITHM_SHA512;
+               default: ThrowErr(CKM::Exc::Crypto::InputParam, "Requested param is not supported");
        }
 }
 
-tz_prf toTzPrf(CKM::KdfPrf prf)
+hal_security_keys_kdf_prf_type_e convertToHalKdfPrf(CKM::KdfPrf prf)
 {
-       switch(prf) {
-       case CKM::KdfPrf::HMAC_SHA256: return PRF_HMAC_SHA256;
-       case CKM::KdfPrf::HMAC_SHA384: return PRF_HMAC_SHA384;
-       case CKM::KdfPrf::HMAC_SHA512: return PRF_HMAC_SHA512;
-       default: ThrowErr(CKM::Exc::Crypto::DataTypeNotSupported, "PRF not supported by tz-backend");
+       switch (prf) {
+               case CKM::KdfPrf::HMAC_SHA256:  return HAL_SECURITY_KEYS_PRF_TYPE_HMAC_SHA256;
+               case CKM::KdfPrf::HMAC_SHA384:  return HAL_SECURITY_KEYS_PRF_TYPE_HMAC_SHA384;
+               case CKM::KdfPrf::HMAC_SHA512:  return HAL_SECURITY_KEYS_PRF_TYPE_HMAC_SHA512;
+               default: ThrowErr(CKM::Exc::Crypto::InputParam, "Requested param is not supported");
        }
 }
 
-tz_kbkdf_mode toTzKbkdfMode(CKM::KbkdfMode mode)
+hal_security_keys_kbkdf_mode_e convertToHalKbkdfMode(CKM::KbkdfMode mode)
 {
-       switch(mode) {
-       case CKM::KbkdfMode::COUNTER: return KBKDF_MODE_COUNTER;
-       default:
-               ThrowErr(CKM::Exc::Crypto::DataTypeNotSupported, "KBKDF mode not supported by tz-backend");
+       switch (mode) {
+               case CKM::KbkdfMode::COUNTER:   return HAL_SECURITY_KEYS_KBKDF_MODE_COUNTER;
+               default: ThrowErr(CKM::Exc::Crypto::InputParam, "Requested param is not supported");
        }
 }
 
-tz_kbkdf_ctr_loc toTzCtrLoc(CKM::KbkdfCounterLocation loc)
+hal_security_keys_kbkdf_counter_location_e convertToHalKbkdfCounterLocation(CKM::KbkdfCounterLocation loc)
 {
-       switch(loc) {
-       case CKM::KbkdfCounterLocation::BEFORE_FIXED: return KBKDF_LOC_BEFORE_FIXED;
-       case CKM::KbkdfCounterLocation::AFTER_FIXED: return KBKDF_LOC_AFTER_FIXED;
-       case CKM::KbkdfCounterLocation::MIDDLE_FIXED: return KBKDF_LOC_MIDDLE_FIXED;
-       default:
-               ThrowErr(CKM::Exc::Crypto::DataTypeNotSupported,
-                       "KBKDF counter location not supported by tz-backend");
+       switch (loc) {
+               case CKM::KbkdfCounterLocation::BEFORE_FIXED:
+                       return HAL_SECURITY_KEYS_KBKDF_COUNTER_LOCATION_BEFORE_FIXED;
+               case CKM::KbkdfCounterLocation::AFTER_FIXED:
+                       return HAL_SECURITY_KEYS_KBKDF_COUNTER_LOCATION_AFTER_FIXED;
+               case CKM::KbkdfCounterLocation::MIDDLE_FIXED:
+                       return HAL_SECURITY_KEYS_KBKDF_COUNTER_LOCATION_MIDDLE_FIXED;
+               default: ThrowErr(CKM::Exc::Crypto::InputParam, "Requested param is not supported");
        }
 }
 
+hal_security_keys_kbkdf_params_s convertToHalParams(CKM::KdfPrf prf,
+                                                                                                       size_t length,
+                                                                                                       CKM::KbkdfMode mode,
+                                                                                                       const CKM::RawBuffer &label,
+                                                                                                       const CKM::RawBuffer &context,
+                                                                                                       const CKM::RawBuffer &fixed,
+                                                                                                       CKM::KbkdfCounterLocation counterLocation,
+                                                                                                       size_t rlenBits,
+                                                                                                       size_t llenBits,
+                                                                                                       bool noSeparator)
+{
+       hal_security_keys_kbkdf_params_s params = {
+               {convertToHalKdfPrf(prf)},
+               {length},
+               {convertToHalKbkdfMode(mode)},
+               {convertToHalData(label)},
+               {convertToHalData(context)},
+               {convertToHalData(fixed)},
+               {convertToHalKbkdfCounterLocation(counterLocation)},
+               {rlenBits},
+               {llenBits},
+               {noSeparator}
+       };
+       return params;
+}
+
+void ThrowWhenHalError(int error, const std::string& errorMessage)
+{
+       switch (error) {
+               case HAL_SECURITY_KEYS_ERROR_INVALID_PARAMETER:
+                       ThrowErr(CKM::Exc::Crypto::InputParam, errorMessage);
+               case HAL_SECURITY_KEYS_ERROR_INTERNAL_ERROR:
+                       ThrowErr(CKM::Exc::Crypto::InternalError, errorMessage);
+               case HAL_SECURITY_KEYS_ERROR_NOT_SUPPORTED:
+                       ThrowErr(CKM::Exc::Crypto::OperationNotSupported, errorMessage);
+               case HAL_SECURITY_KEYS_ERROR_AUTHENTICATION_FAILED:
+                       ThrowErr(CKM::Exc::Crypto::AuthenticationFailed, errorMessage);
+               case HAL_SECURITY_KEYS_ERROR_TARGET_DEAD:
+                       CKM::Crypto::TZ::Internals::HalContext::Instance().ReloadHalContext();
+                       ThrowErr(CKM::Exc::Crypto::InternalError, errorMessage);
+               case HAL_SECURITY_KEYS_ERROR_VERIFICATION_FAILED:
+                       ;
+       };
+}
+
 } // namespace
 
 namespace CKM {
@@ -179,44 +308,6 @@ ValidatorMap initValidators()
 
 const ValidatorMap g_validators = initValidators();
 
-tz_algo_type getGenSKeyType(AlgoType type)
-{
-       switch (type)
-       {
-       case AlgoType::AES_GEN: return ALGO_AES_GEN;
-       default: ThrowErr(Exc::Crypto::OperationNotSupported, "Requested algorithm is not supported");
-       }
-}
-
-tz_algo_type getAlgType(AlgoType type)
-{
-       switch (type)
-       {
-       case AlgoType::AES_CBC: return ALGO_AES_CBC;
-       case AlgoType::AES_CTR: return ALGO_AES_CTR;
-       case AlgoType::AES_CFB: return ALGO_AES_CFB;
-       case AlgoType::AES_GCM: return ALGO_AES_GCM;
-       case AlgoType::RSA_OAEP: return ALGO_RSA;
-       case AlgoType::RSA_SV: return ALGO_RSA_SV;
-       case AlgoType::DSA_SV: return ALGO_DSA_SV;
-       case AlgoType::ECDSA_SV: return ALGO_ECDSA_SV;
-       default: ThrowErr(Exc::Crypto::OperationNotSupported, "Requested algorithm is not supported");
-       };
-}
-
-tz_hash_type getHashType(HashAlgorithm hash)
-{
-       switch (hash)
-       {
-       case HashAlgorithm::SHA1: return HASH_SHA1;
-       case HashAlgorithm::SHA256: return HASH_SHA256;
-       case HashAlgorithm::SHA384: return HASH_SHA384;
-       case HashAlgorithm::SHA512: return HASH_SHA512;
-       default:
-               ThrowErr(Exc::Crypto::OperationNotSupported, "Requested algorithm is not supported");
-       }
-}
-
 void decompose(const CryptoAlgorithm &alg,
                           AlgoType &algo,
                           uint32_t &ctrLenOrTagSizeBits,
@@ -264,45 +355,57 @@ void decompose(const CryptoAlgorithm &alg,
 
 RawBuffer generateIV()
 {
-       RawBuffer result;
-       TrustZoneContext::Instance().generateIV(result);
-       return result;
+       auto ctx = HalContext::Instance().GetHalContext();
+
+       security_keys_data_ptr out;
+       int error = hal_security_keys_create_iv(ctx, out.Get());
+       ThrowWhenHalError(error, "Failed generating IV");
+
+       return RawBuffer(out.GetBuffer(), out.GetBuffer() + out.GetLength());
 }
 
 void generateSKey(const CryptoAlgorithm &alg,
-                               const Password &pwd,
-                               const RawBuffer &iv,
-                               RawBuffer &tag,
-                               const RawBuffer &hash)
+                                 const Password &pwd,
+                                 const RawBuffer &iv,
+                                 RawBuffer &tag,
+                                 const RawBuffer &hash)
 {
-       AlgoType keyType = unpack<AlgoType>(alg, ParamName::ALGO_TYPE);
        int keyBits = unpack<int>(alg, ParamName::GEN_KEY_LEN);
 
+       auto ctx = HalContext::Instance().GetHalContext();
+       security_keys_data_ptr halTag;
+
        if (!pwd.empty()) {
                if (iv.empty()) {
                        ThrowErr(Exc::InputParam, "Key generation with password encryption requires an IV");
                }
 
                RawBuffer pwdBuf(pwd.begin(), pwd.end());
-               TrustZoneContext::Instance().generateSKeyPwd(getGenSKeyType(keyType),
-                                                                                                       pwdBuf, iv, keyBits,
-                                                                                                       tag, hash);
+               int error = hal_security_keys_create_key_aes(ctx, keyBits,
+                       convertToHalData(hash), convertToHalPwdIv(pwdBuf, iv),
+                       halTag.Get());
+
+               ThrowWhenHalError(error, "Failed generating symmetric key with password");
+               tag.assign(halTag.GetBuffer(), halTag.GetBuffer() + halTag.GetLength());
        } else {
-               TrustZoneContext::Instance().generateSKey(getGenSKeyType(keyType), keyBits,
-                                                                                               hash);
-       }
+               RawBuffer pwdEmpty;
+               int error = hal_security_keys_create_key_aes(ctx, keyBits,
+                       convertToHalData(hash), convertToHalPwdIv(pwdEmpty, iv),
+                       halTag.Get());
 
+               ThrowWhenHalError(error, "Failed generating symmetric key");
+       }
 }
 
 AlgoType generateAKey(const CryptoAlgorithm &alg,
-                                       const Password &pubPwd,
-                                       const Password &privPwd,
-                                       const RawBuffer &pubPwdIv,
-                                       const RawBuffer &privPwdIv,
-                                       RawBuffer &pubTag,
-                                       RawBuffer &privTag,
-                                       const RawBuffer &hashPriv,
-                                       const RawBuffer &hashPub)
+                                         const Password &pubPwd,
+                                         const Password &privPwd,
+                                         const RawBuffer &pubPwdIv,
+                                         const RawBuffer &privPwdIv,
+                                         RawBuffer &pubTag,
+                                         RawBuffer &privTag,
+                                         const RawBuffer &hashPriv,
+                                         const RawBuffer &hashPub)
 {
        AlgoType keyType = unpack<AlgoType>(alg, ParamName::ALGO_TYPE);
 
@@ -314,70 +417,72 @@ AlgoType generateAKey(const CryptoAlgorithm &alg,
        if (!privPwd.empty())
                privPwdBuf.assign(privPwd.begin(), privPwd.end());
 
+       auto ctx = HalContext::Instance().GetHalContext();
+       security_keys_data_ptr halPubTag;
+       security_keys_data_ptr halPrivTag;
+
        switch (keyType) {
-       case AlgoType::RSA_GEN: {
-               int keyBits = unpack<int>(alg, ParamName::GEN_KEY_LEN);
-               TrustZoneContext::Instance().generateRSAKey(keyBits,
-                                                                                                       pubPwdBuf,
-                                                                                                       pubPwdIv,
-                                                                                                       privPwdBuf,
-                                                                                                       privPwdIv,
-                                                                                                       pubTag,
-                                                                                                       privTag,
-                                                                                                       hashPriv,
-                                                                                                       hashPub);
-               break;
-       }
-       case AlgoType::DSA_GEN: {
-               int keyBits = unpack<int>(alg, ParamName::GEN_KEY_LEN);
-               RawBuffer prime;
-               RawBuffer subprime;
-               RawBuffer base;
-               generateDSAParams(keyBits, prime, subprime, base);
-               TrustZoneContext::Instance().generateDSAKey(keyBits,
-                                                                                                       prime,
-                                                                                                       subprime,
-                                                                                                       base,
-                                                                                                       pubPwdBuf,
-                                                                                                       pubPwdIv,
-                                                                                                       privPwdBuf,
-                                                                                                       privPwdIv,
-                                                                                                       pubTag,
-                                                                                                       privTag,
-                                                                                                       hashPriv,
-                                                                                                       hashPub);
-               break;
-       }
-       case AlgoType::ECDSA_GEN: {
-               CKM::ElipticCurve ec = unpack<CKM::ElipticCurve>(alg, ParamName::GEN_EC);
-               TrustZoneContext::Instance().generateECKey(toTzEc(ec),
-                                                                                                  pubPwdBuf,
-                                                                                                  pubPwdIv,
-                                                                                                  privPwdBuf,
-                                                                                                  privPwdIv,
-                                                                                                  pubTag,
-                                                                                                  privTag,
-                                                                                                  hashPriv,
-                                                                                                  hashPub);
-               break;
-       }
-       case AlgoType::KEM_GEN: {
-               CKM::KemType kt = unpack<CKM::KemType>(alg, ParamName::GEN_KEM_TYPE);
-               TrustZoneContext::Instance().generateKEMKey(toTzKem(kt),
-                                                                                                       pubPwdBuf,
-                                                                                                       pubPwdIv,
-                                                                                                       privPwdBuf,
-                                                                                                       privPwdIv,
-                                                                                                       pubTag,
-                                                                                                       privTag,
-                                                                                                       hashPriv,
-                                                                                                       hashPub);
-               break;
-       }
-       default: {
-               ThrowErr(Exc::Crypto::InputParam,
-                       "Invalid algo type provided for generateAKey function");
-       }
+               case AlgoType::RSA_GEN: {
+                       int keyBits = unpack<int>(alg, ParamName::GEN_KEY_LEN);
+                       int error = hal_security_keys_create_key_pair_rsa(ctx, keyBits,
+                               convertToHalData(hashPriv), convertToHalPwdIv(privPwdBuf, privPwdIv),
+                               convertToHalData(hashPub), convertToHalPwdIv(pubPwdBuf, pubPwdIv),
+                               halPrivTag.Get(), halPubTag.Get());
+
+                       ThrowWhenHalError(error, "Failed generating RSA keys");
+
+                       pubTag.assign(halPubTag.GetBuffer(), halPubTag.GetBuffer() + halPubTag.GetLength());
+                       privTag.assign(halPrivTag.GetBuffer(), halPrivTag.GetBuffer() + halPrivTag.GetLength());
+                       break;
+               }
+               case AlgoType::DSA_GEN: {
+                       int keyBits = unpack<int>(alg, ParamName::GEN_KEY_LEN);
+                       RawBuffer prime;
+                       RawBuffer subprime;
+                       RawBuffer base;
+                       generateDSAParams(keyBits, prime, subprime, base);
+                       int error = hal_security_keys_create_key_pair_dsa(ctx, keyBits,
+                               convertToHalData(prime), convertToHalData(subprime), convertToHalData(base),
+                               convertToHalData(hashPriv), convertToHalPwdIv(privPwdBuf, privPwdIv),
+                               convertToHalData(hashPub), convertToHalPwdIv(pubPwdBuf, pubPwdIv),
+                               halPrivTag.Get(), halPubTag.Get());
+
+                       ThrowWhenHalError(error, "Failed generating DSA keys");
+
+                       pubTag.assign(halPubTag.GetBuffer(), halPubTag.GetBuffer() + halPubTag.GetLength());
+                       privTag.assign(halPrivTag.GetBuffer(), halPrivTag.GetBuffer() + halPrivTag.GetLength());
+                       break;
+               }
+               case AlgoType::ECDSA_GEN: {
+                       CKM::ElipticCurve ec = unpack<CKM::ElipticCurve>(alg, ParamName::GEN_EC);
+                       int error = hal_security_keys_create_key_pair_ecdsa(ctx, convertToHalEcType(ec),
+                               convertToHalData(hashPriv), convertToHalPwdIv(privPwdBuf, privPwdIv),
+                               convertToHalData(hashPub), convertToHalPwdIv(pubPwdBuf, pubPwdIv),
+                               halPrivTag.Get(), halPubTag.Get());
+
+                       ThrowWhenHalError(error, "Failed generating ECDSA keys");
+
+                       pubTag.assign(halPubTag.GetBuffer(), halPubTag.GetBuffer() + halPubTag.GetLength());
+                       privTag.assign(halPrivTag.GetBuffer(), halPrivTag.GetBuffer() + halPrivTag.GetLength());
+                       break;
+               }
+               case AlgoType::KEM_GEN: {
+                       CKM::KemType kt = unpack<CKM::KemType>(alg, ParamName::GEN_KEM_TYPE);
+                       int error = hal_security_keys_create_key_pair_kem(ctx, convertToHalKemType(kt),
+                               convertToHalData(hashPriv), convertToHalPwdIv(privPwdBuf, privPwdIv),
+                               convertToHalData(hashPub), convertToHalPwdIv(pubPwdBuf, pubPwdIv),
+                               halPrivTag.Get(), halPubTag.Get());
+
+                       ThrowWhenHalError(error, "Failed generating KEM keys");
+
+                       pubTag.assign(halPubTag.GetBuffer(), halPubTag.GetBuffer() + halPubTag.GetLength());
+                       privTag.assign(halPrivTag.GetBuffer(), halPrivTag.GetBuffer() + halPrivTag.GetLength());
+                       break;
+               }
+               default: {
+                       ThrowErr(Exc::Crypto::InputParam,
+                               "Invalid algo type provided for generateAKey function");
+               }
        }
 
        return keyType;
@@ -385,29 +490,29 @@ AlgoType generateAKey(const CryptoAlgorithm &alg,
 
 void destroyKey(const RawBuffer &keyId)
 {
-       TrustZoneContext::Instance().executeDestroy(keyId);
+       auto ctx = HalContext::Instance().GetHalContext();
+       int error = hal_security_keys_destroy_key(ctx, convertToHalData(keyId));
+       ThrowWhenHalError(error, "Failed destroying key");
 }
 
 void importData(const Data &data,
-                                        const EncryptionParams &encData,
-                                        const Password &pwd,
-                                        const RawBuffer &pwdIV,
-                                        RawBuffer &tag,
-                                        const RawBuffer &hash)
+                               const EncryptionParams &encData,
+                               const Password &pwd,
+                               const RawBuffer &pwdIV,
+                               RawBuffer &tag,
+                               const RawBuffer &hash)
 {
+       RawBuffer pwdBuf(pwd.begin(), pwd.end());
 
-       const auto dataType = toTzDataType(data.type);
+       auto ctx = HalContext::Instance().GetHalContext();
+       security_keys_data_ptr halTag;
+       int error = hal_security_keys_import_data(ctx, convertToHalData(hash),
+               convertToHalPwdIv(pwdBuf, pwdIV), convertToHalDataType(data.type),
+               convertToHalData(data.data), convertToHalData(encData.iv),
+               convertToHalData(encData.tag), halTag.Get());
 
-       RawBuffer pwdBuf(pwd.begin(), pwd.end());
-       uint32_t keySizeBits = data.data.size() * 8;
-       TrustZoneContext::Instance().importData(dataType,
-                                                                               data.data,
-                                                                               encData,
-                                                                               pwdBuf,
-                                                                               pwdIV,
-                                                                               keySizeBits,
-                                                                               tag,
-                                                                               hash);
+       ThrowWhenHalError(error, "Failed importing data");
+       tag.assign(halTag.GetBuffer(), halTag.GetBuffer() + halTag.GetLength());
 }
 
 void importWrappedKey(const RawBuffer &wrappingKeyId,
@@ -425,23 +530,21 @@ void importWrappedKey(const RawBuffer &wrappingKeyId,
        uint32_t ctrLenOrTagSizeBits = 0;
        RawBuffer iv;
        RawBuffer aad;
-       HashAlgorithm oaepHash;
-       decompose(alg, algo, ctrLenOrTagSizeBits, iv, aad, oaepHash);
-
-       // TODO it is awful!
-       TrustZoneContext::Instance().importWrappedKey(wrappingKeyId,
-                                                                                                 wrappingKeyPwd,
-                                                                                                 getAlgType(algo),
-                                                                                                 getHashType(oaepHash),
-                                                                                                 iv,
-                                                                                                 ctrLenOrTagSizeBits,
-                                                                                                 aad,
-                                                                                                 toTzDataType(encryptedKey.type),
-                                                                                                 encryptedKey.data,
-                                                                                                 encryptedKeyPwdBuf,
-                                                                                                 encryptedKeyIV,
-                                                                                                 encryptedKeyTag,
-                                                                                                 encryptedKeyId);
+       HashAlgorithm hash;
+       decompose(alg, algo, ctrLenOrTagSizeBits, iv, aad, hash);
+
+       auto ctx = HalContext::Instance().GetHalContext();
+       security_keys_data_ptr tag;
+       int error = hal_security_keys_import_wrapped_key(ctx,
+               convertToHalAlgoType(algo), convertToHalHashType(hash),
+               convertToHalData(iv), convertToHalData(aad), ctrLenOrTagSizeBits,
+               convertToHalData(wrappingKeyId), convertToHalPwdIvTag(wrappingKeyPwd),
+               convertToHalData(encryptedKey.data), convertToHalData(encryptedKeyId),
+               convertToHalPwdIv(encryptedKeyPwdBuf, encryptedKeyIV),
+               convertToHalDataType(encryptedKey.type), tag.Get());
+
+       ThrowWhenHalError(error, "Failed importing wrapped key");
+       encryptedKeyTag.assign(tag.GetBuffer(), tag.GetBuffer() + tag.GetLength());
 }
 
 RawBuffer exportWrappedKey(const RawBuffer &wrappingKeyId,
@@ -455,21 +558,20 @@ RawBuffer exportWrappedKey(const RawBuffer &wrappingKeyId,
        uint32_t ctrLenOrTagSizeBits = 0;
        RawBuffer iv;
        RawBuffer aad;
-       HashAlgorithm oaepHash;
-       decompose(alg, algo, ctrLenOrTagSizeBits, iv, aad, oaepHash);
-
-       // TODO it is awful!
-       return TrustZoneContext::Instance().exportWrappedKey(wrappingKeyId,
-                                                                                                                wrappingKeyPwd,
-                                                                                                                getAlgType(algo),
-                                                                                                                getHashType(oaepHash),
-                                                                                                                iv,
-                                                                                                                ctrLenOrTagSizeBits,
-                                                                                                                aad,
-                                                                                                                keyToWrapId,
-                                                                                                                keyToWrapPwd,
-                                                                                                                toTzDataType(keyToWrapType));
-
+       HashAlgorithm hash;
+       decompose(alg, algo, ctrLenOrTagSizeBits, iv, aad, hash);
+
+       auto ctx = HalContext::Instance().GetHalContext();
+       security_keys_data_ptr out;
+       int error = hal_security_keys_export_wrapped_key(ctx,
+               convertToHalAlgoType(algo), convertToHalHashType(hash),
+               convertToHalData(iv), convertToHalData(aad), ctrLenOrTagSizeBits,
+               convertToHalData(wrappingKeyId), convertToHalPwdIvTag(wrappingKeyPwd),
+               convertToHalData(keyToWrapId), convertToHalPwdIvTag(keyToWrapPwd),
+               convertToHalDataType(keyToWrapType), out.Get());
+
+       ThrowWhenHalError(error, "Failed exporting wrapped key");
+       return RawBuffer(out.GetBuffer(), out.GetBuffer() + out.GetLength());
 }
 
 RawBuffer wrapConcatenatedData(const RawBuffer &wrappingKeyId,
@@ -480,16 +582,19 @@ RawBuffer wrapConcatenatedData(const RawBuffer &wrappingKeyId,
                                                           const RawBuffer &userData)
 {
        AlgoType algo = unpack<AlgoType>(alg, ParamName::ALGO_TYPE);
-       HashAlgorithm oaepHash = HashAlgorithm::SHA1;
-       alg.getParam(ParamName::ED_OAEP_HASH, oaepHash);
-
-       return TrustZoneContext::Instance().wrapConcatenatedData(wrappingKeyId,
-                                                                                                                        wrappingKeyPwd,
-                                                                                                                        getAlgType(algo),
-                                                                                                                        getHashType(oaepHash),
-                                                                                                                        keyToWrapId,
-                                                                                                                        keyToWrapPwd,
-                                                                                                                        userData);
+       HashAlgorithm hash = HashAlgorithm::SHA1;
+       alg.getParam(ParamName::ED_OAEP_HASH, hash);
+
+       auto ctx = HalContext::Instance().GetHalContext();
+       security_keys_data_ptr out;
+       int error = hal_security_keys_wrap_concatenated_data(ctx,
+               convertToHalAlgoType(algo), convertToHalHashType(hash),
+               convertToHalData(wrappingKeyId), convertToHalPwdIvTag(wrappingKeyPwd),
+               convertToHalData(keyToWrapId), convertToHalPwdIvTag(keyToWrapPwd),
+               convertToHalData(userData), out.Get());
+
+       ThrowWhenHalError(error, "Failed wrapping concatenated data");
+       return RawBuffer(out.GetBuffer(), out.GetBuffer() + out.GetLength());
 }
 
 RawBuffer unwrapConcatenatedData(const RawBuffer &wrappingKeyId,
@@ -505,20 +610,23 @@ RawBuffer unwrapConcatenatedData(const RawBuffer &wrappingKeyId,
        RawBuffer encryptedKeyPwdBuf(encryptedKeyPassword.begin(), encryptedKeyPassword.end());
 
        AlgoType algo = unpack<AlgoType>(alg, ParamName::ALGO_TYPE);
-       HashAlgorithm oaepHash = HashAlgorithm::SHA1;
-       alg.getParam(ParamName::ED_OAEP_HASH, oaepHash);
-
-       return TrustZoneContext::Instance().unwrapConcatenatedData(wrappingKeyId,
-                                                                                                                          wrappingKeyPwd,
-                                                                                                                          getAlgType(algo),
-                                                                                                                          getHashType(oaepHash),
-                                                                                                                          toTzDataType(encryptedKey.type),
-                                                                                                                          encryptedKey.data,
-                                                                                                                          encryptedKeyPwdBuf,
-                                                                                                                          encryptedKeyIV,
-                                                                                                                          encryptedKeyTag,
-                                                                                                                          encryptedKeyId,
-                                                                                                                          keySize);
+       HashAlgorithm hash = HashAlgorithm::SHA1;
+       alg.getParam(ParamName::ED_OAEP_HASH, hash);
+
+       auto ctx = HalContext::Instance().GetHalContext();
+       security_keys_data_ptr tag;
+       security_keys_data_ptr out;
+       int error = hal_security_keys_unwrap_concatenated_data(ctx,
+               convertToHalAlgoType(algo), convertToHalHashType(hash),
+               convertToHalData(wrappingKeyId), convertToHalPwdIvTag(wrappingKeyPwd),
+               convertToHalData(encryptedKey.data), convertToHalData(encryptedKeyId),
+               convertToHalPwdIv(encryptedKeyPwdBuf, encryptedKeyIV),
+               convertToHalDataType(encryptedKey.type), keySize,
+               out.Get(), tag.Get());
+
+       ThrowWhenHalError(error, "Failed unwrapping concatenated data");
+       encryptedKeyTag.assign(tag.GetBuffer(), tag.GetBuffer() + tag.GetLength());
+       return RawBuffer(out.GetBuffer(), out.GetBuffer() + out.GetLength());
 }
 
 RawBuffer encapsulateKey(const RawBuffer &publicKeyId,
@@ -532,13 +640,17 @@ RawBuffer encapsulateKey(const RawBuffer &publicKeyId,
        CKM::KemType kt = unpack<CKM::KemType>(params, ParamName::GEN_KEM_TYPE);
        RawBuffer sharedSecretPwdBuf(sharedSecretPwd.begin(), sharedSecretPwd.end());
 
-       return TrustZoneContext::Instance().encapsulateKey(publicKeyId,
-                                                                                                          publicKeyPwd,
-                                                                                                          toTzKem(kt),
-                                                                                                          sharedSecretPwdBuf,
-                                                                                                          sharedSecretIV,
-                                                                                                          sharedSecretTag,
-                                                                                                          sharedSecretId);
+       auto ctx = HalContext::Instance().GetHalContext();
+       security_keys_data_ptr tag;
+       security_keys_data_ptr out;
+       int error = hal_security_keys_encapsulate_key(ctx, convertToHalKemType(kt),
+               convertToHalData(publicKeyId), convertToHalPwdIvTag(publicKeyPwd),
+               convertToHalData(sharedSecretId), convertToHalPwdIv(sharedSecretPwdBuf, sharedSecretIV),
+               out.Get(), tag.Get());
+
+       ThrowWhenHalError(error, "Failed encapsulating key");
+       sharedSecretTag.assign(tag.GetBuffer(), tag.GetBuffer() + tag.GetLength());
+       return RawBuffer(out.GetBuffer(), out.GetBuffer() + out.GetLength());
 }
 
 void decapsulateKey(const RawBuffer &privateKeyId,
@@ -553,55 +665,67 @@ void decapsulateKey(const RawBuffer &privateKeyId,
        CKM::KemType kt = unpack<CKM::KemType>(params, ParamName::GEN_KEM_TYPE);
        RawBuffer sharedSecretPwdBuf(sharedSecretPwd.begin(), sharedSecretPwd.end());
 
-       TrustZoneContext::Instance().decapsulateKey(privateKeyId,
-                                                                                               privateKeyPwd,
-                                                                                               toTzKem(kt),
-                                                                                               sharedSecretPwdBuf,
-                                                                                               sharedSecretIV,
-                                                                                               sharedSecretTag,
-                                                                                               sharedSecretId,
-                                                                                               ciphertext);
+       auto ctx = HalContext::Instance().GetHalContext();
+       security_keys_data_ptr tag;
+       int error = hal_security_keys_decapsulate_key(ctx, convertToHalKemType(kt),
+               convertToHalData(privateKeyId), convertToHalPwdIvTag(privateKeyPwd),
+               convertToHalData(sharedSecretId), convertToHalPwdIv(sharedSecretPwdBuf, sharedSecretIV),
+               convertToHalData(ciphertext), tag.Get());
+
+       ThrowWhenHalError(error, "Failed decapsulating key");
+       sharedSecretTag.assign(tag.GetBuffer(), tag.GetBuffer() + tag.GetLength());
 }
 
 RawBuffer getData(const RawBuffer &dataId,
                                  const Pwd &pwd,
                                  const DataType &type)
 {
-       RawBuffer result;
-       TrustZoneContext::Instance().getData(dataId,
-                                pwd,
-                                toTzDataType(type),
-                                result);
-       return result;
+       auto ctx = HalContext::Instance().GetHalContext();
+       security_keys_data_ptr out;
+       int error = hal_security_keys_export_data(ctx,
+               convertToHalData(dataId), convertToHalPwdIvTag(pwd),
+               convertToHalDataType(type), out.Get());
+
+       ThrowWhenHalError(error, "Failed getting data");
+       return RawBuffer(out.GetBuffer(), out.GetBuffer() + out.GetLength());
 }
 
 void destroyData(const RawBuffer &dataId)
 {
-       TrustZoneContext::Instance().destroyData(dataId);
+       auto ctx = HalContext::Instance().GetHalContext();
+       int error = hal_security_keys_destroy_data(ctx, convertToHalData(dataId));
+       ThrowWhenHalError(error, "Failed destroying data");
 }
 
 BufferPair encryptDataAesGcm(const RawBuffer &keyId,
-                                                       const Pwd &pwd,
-                                                       const RawBuffer &iv,
-                                                       int tagSize,
-                                                       const RawBuffer &data,
-                                                       const RawBuffer &aad)
+                                                        const Pwd &pwd,
+                                                        const RawBuffer &iv,
+                                                        int tagSize,
+                                                        const RawBuffer &data,
+                                                        const RawBuffer &aad)
 {
-       RawBuffer result;
-       RawBuffer tag;
+       auto ctx = HalContext::Instance().GetHalContext();
+
+       security_keys_data_ptr out;
+       security_keys_data_ptr halTag;
+       int error = hal_security_keys_encrypt_data_auth(ctx,
+               convertToHalData(keyId), convertToHalPwdIvTag(pwd),
+               convertToHalData(data), convertToHalData(iv), convertToHalData(aad),
+               tagSize, halTag.Get(), out.Get());
 
-       TrustZoneContext::Instance().executeEncryptAE(keyId, pwd, iv, tagSize,
-                                                                                               aad, data, result, tag);
+       ThrowWhenHalError(error, "Failed authenticated encryption");
+       RawBuffer encrypted(out.GetBuffer(), out.GetBuffer() + out.GetLength());
+       RawBuffer tag(halTag.GetBuffer(), halTag.GetBuffer() + halTag.GetLength());
 
-       return std::make_pair(result, tag);
+       return std::make_pair(encrypted, tag);
 }
 
 RawBuffer encryptDataAesGcmPacked(const RawBuffer &keyId,
-                                                               const Pwd &pwd,
-                                                               const RawBuffer &iv,
-                                                               int tagSize,
-                                                               const RawBuffer &data,
-                                                               const RawBuffer &aad)
+                                                                 const Pwd &pwd,
+                                                                 const RawBuffer &iv,
+                                                                 int tagSize,
+                                                                 const RawBuffer &data,
+                                                                 const RawBuffer &aad)
 {
        auto pair = encryptDataAesGcm(keyId, pwd, iv, tagSize, data, aad);
        std::copy(pair.second.begin(), pair.second.end(),
@@ -617,20 +741,24 @@ RawBuffer decryptDataAesGcm(const RawBuffer &keyId,
                                                        const RawBuffer &data,
                                                        const RawBuffer &aad)
 {
-       RawBuffer result;
+       auto ctx = HalContext::Instance().GetHalContext();
 
-       TrustZoneContext::Instance().executeDecryptAE(keyId, pwd, iv, tagSizeBits,
-                                                                                               tag, aad, data, result);
+       security_keys_data_ptr out;
+       int error = hal_security_keys_decrypt_data_auth(ctx,
+               convertToHalData(keyId), convertToHalPwdIvTag(pwd),
+               convertToHalData(data), convertToHalData(iv), convertToHalData(aad),
+               tagSizeBits, convertToHalData(tag), out.Get());
 
-       return result;
+       ThrowWhenHalError(error, "Failed authenticated decryption");
+       return RawBuffer(out.GetBuffer(), out.GetBuffer() + out.GetLength());
 }
 
 RawBuffer decryptDataAesGcmPacked(const RawBuffer &keyId,
-                                                               const Pwd &pwd,
-                                                               const RawBuffer &iv,
-                                                               int tagSizeBits,
-                                                               const RawBuffer &data,
-                                                               const RawBuffer &aad)
+                                                                 const Pwd &pwd,
+                                                                 const RawBuffer &iv,
+                                                                 int tagSizeBits,
+                                                                 const RawBuffer &data,
+                                                                 const RawBuffer &aad)
 {
        int tagSizeBytes = tagSizeBits / 8;
        if (tagSizeBytes > static_cast<int>(data.size()))
@@ -638,22 +766,23 @@ RawBuffer decryptDataAesGcmPacked(const RawBuffer &keyId,
 
        auto tagPos = data.data() + data.size() - tagSizeBytes;
        return decryptDataAesGcm(keyId,
-                                                       pwd,
-                                                       iv,
-                                                       tagSizeBits,
-                                                       RawBuffer(tagPos, data.data() + data.size()),
-                                                       RawBuffer(data.data(), tagPos),
-                                                       aad);
+                                                        pwd,
+                                                        iv,
+                                                        tagSizeBits,
+                                                        RawBuffer(tagPos, data.data() + data.size()),
+                                                        RawBuffer(data.data(), tagPos),
+                                                        aad);
 }
 
-
 RawBuffer symmetricEncrypt(const RawBuffer &keyId,
-                                               const Pwd &pwd,
-                                               const CryptoAlgorithm &alg,
-                                               const RawBuffer &data)
+                                                  const Pwd &pwd,
+                                                  const CryptoAlgorithm &alg,
+                                                  const RawBuffer &data)
 {
        AlgoType algo = unpack<AlgoType>(alg, ParamName::ALGO_TYPE);
        uint64_t ctrLen = Params::DEFAULT_AES_IV_LEN * 8;
+       HashAlgorithm hash = HashAlgorithm::SHA1;
+       RawBuffer iv = unpack<RawBuffer>(alg, ParamName::ED_IV);
 
        switch (algo) {
                case AlgoType::AES_CTR: {
@@ -668,16 +797,16 @@ RawBuffer symmetricEncrypt(const RawBuffer &keyId,
                }
                case AlgoType::AES_CBC:
                case AlgoType::AES_CFB: {
-                       RawBuffer result;
-                       TrustZoneContext::Instance().executeCrypt(CMD_ENCRYPT,
-                                                                                                       getAlgType(algo),
-                                                                                                       HASH_SHA1, // ignored
-                                                                                                       keyId,
-                                                                                                       pwd,
-                                                                                                       unpack<RawBuffer>(alg, ParamName::ED_IV),
-                                                                                                       data,
-                                                                                                       result);
-                       return result;
+                       auto ctx = HalContext::Instance().GetHalContext();
+                       security_keys_data_ptr out;
+                       int error = hal_security_keys_encrypt_data(ctx,
+                               convertToHalAlgoType(algo), convertToHalHashType(hash),
+                               convertToHalData(keyId), convertToHalPwdIvTag(pwd),
+                               convertToHalData(data), convertToHalData(iv),
+                               out.Get());
+
+                       ThrowWhenHalError(error, "Failed symmetric encrypt");
+                       return RawBuffer(out.GetBuffer(), out.GetBuffer() + out.GetLength());
                }
                case AlgoType::AES_GCM: {
                        int tagLenBits = Params::DEFAULT_AES_GCM_TAG_LEN_BITS;
@@ -685,11 +814,11 @@ RawBuffer symmetricEncrypt(const RawBuffer &keyId,
                        RawBuffer aad;
                        alg.getParam(ParamName::ED_AAD, aad);
                        return encryptDataAesGcmPacked(keyId,
-                                                                               pwd,
-                                                                               unpack<RawBuffer>(alg, ParamName::ED_IV),
-                                                                               tagLenBits,
-                                                                               data,
-                                                                               aad);
+                                                                                  pwd,
+                                                                                  unpack<RawBuffer>(alg, ParamName::ED_IV),
+                                                                                  tagLenBits,
+                                                                                  data,
+                                                                                  aad);
                }
                default:
                        break;
@@ -700,12 +829,14 @@ RawBuffer symmetricEncrypt(const RawBuffer &keyId,
 }
 
 RawBuffer symmetricDecrypt(const RawBuffer &keyId,
-                                               const Pwd &pwd,
-                                               const CryptoAlgorithm &alg,
-                                               const RawBuffer &data)
+                                                  const Pwd &pwd,
+                                                  const CryptoAlgorithm &alg,
+                                                  const RawBuffer &data)
 {
        AlgoType algo = unpack<AlgoType>(alg, ParamName::ALGO_TYPE);
        uint64_t ctrLen = Params::DEFAULT_AES_IV_LEN * 8;
+       HashAlgorithm hash = HashAlgorithm::SHA1;
+       RawBuffer iv = unpack<RawBuffer>(alg, ParamName::ED_IV);
 
        switch (algo) {
                case AlgoType::AES_CTR: {
@@ -720,16 +851,16 @@ RawBuffer symmetricDecrypt(const RawBuffer &keyId,
                }
                case AlgoType::AES_CBC:
                case AlgoType::AES_CFB: {
-                       RawBuffer result;
-                       TrustZoneContext::Instance().executeCrypt(CMD_DECRYPT,
-                                                                                                       getAlgType(algo),
-                                                                                                       HASH_SHA1, // ignored
-                                                                                                       keyId,
-                                                                                                       pwd,
-                                                                                                       unpack<RawBuffer>(alg, ParamName::ED_IV),
-                                                                                                       data,
-                                                                                                       result);
-                       return result;
+                       auto ctx = HalContext::Instance().GetHalContext();
+                       security_keys_data_ptr out;
+                       int error = hal_security_keys_decrypt_data(ctx,
+                               convertToHalAlgoType(algo), convertToHalHashType(hash),
+                               convertToHalData(keyId), convertToHalPwdIvTag(pwd),
+                               convertToHalData(data), convertToHalData(iv),
+                               out.Get());
+
+                       ThrowWhenHalError(error, "Failed symmetric decrypt");
+                       return RawBuffer(out.GetBuffer(), out.GetBuffer() + out.GetLength());
                }
                case AlgoType::AES_GCM: {
                        int tagSizeBits = Params::DEFAULT_AES_GCM_TAG_LEN_BITS;
@@ -737,11 +868,11 @@ RawBuffer symmetricDecrypt(const RawBuffer &keyId,
                        RawBuffer aad;
                        alg.getParam(ParamName::ED_AAD, aad);
                        return decryptDataAesGcmPacked(keyId,
-                                                                               pwd,
-                                                                               unpack<RawBuffer>(alg, ParamName::ED_IV),
-                                                                               tagSizeBits,
-                                                                               data,
-                                                                               aad);
+                                                                                  pwd,
+                                                                                  unpack<RawBuffer>(alg, ParamName::ED_IV),
+                                                                                  tagSizeBits,
+                                                                                  data,
+                                                                                  aad);
                }
                default:
                        break;
@@ -762,23 +893,23 @@ RawBuffer asymmetricEncrypt(const RawBuffer &keyId,
        if (hash == HashAlgorithm::NONE)
                ThrowErr(Exc::Crypto::InputParam, "Invalid OAEP hash");
 
-       RawBuffer result;
-
-       switch (algo)
-       {
-       case AlgoType::RSA_OAEP: {
-               TrustZoneContext::Instance().executeCrypt(CMD_ENCRYPT,
-                                                                                               getAlgType(algo),
-                                                                                               getHashType(hash),
-                                                                                               keyId,
-                                                                                               pwd,
-                                                                                               result, // unused dummy
-                                                                                               data,
-                                                                                               result);
-               return result;
-       }
-       default:
-               break;
+       switch (algo) {
+               case AlgoType::RSA_OAEP: {
+                       auto ctx = HalContext::Instance().GetHalContext();
+
+                       security_keys_data_ptr out;
+                       RawBuffer ivEmpty;
+                       int error = hal_security_keys_encrypt_data(ctx,
+                               convertToHalAlgoType(algo), convertToHalHashType(hash),
+                               convertToHalData(keyId), convertToHalPwdIvTag(pwd),
+                               convertToHalData(data), convertToHalData(ivEmpty),
+                               out.Get());
+
+                       ThrowWhenHalError(error, "Failed asymmetric encrypt");
+                       return RawBuffer(out.GetBuffer(), out.GetBuffer() + out.GetLength());
+               }
+               default:
+                       break;
        }
 
        ThrowErr(Exc::Crypto::OperationNotSupported,
@@ -794,23 +925,23 @@ RawBuffer asymmetricDecrypt(const RawBuffer &keyId,
        HashAlgorithm hash = HashAlgorithm::SHA1;
        alg.getParam(ParamName::ED_OAEP_HASH, hash);
 
-       RawBuffer result;
-
-       switch (algo)
-       {
-       case AlgoType::RSA_OAEP: {
-               TrustZoneContext::Instance().executeCrypt(CMD_DECRYPT,
-                                                                                               getAlgType(algo),
-                                                                                               getHashType(hash),
-                                                                                               keyId,
-                                                                                               pwd,
-                                                                                               result, // unused dummy
-                                                                                               cipher,
-                                                                                               result);
-               return result;
-       }
-       default:
-               break;
+       switch (algo) {
+               case AlgoType::RSA_OAEP: {
+                       auto ctx = HalContext::Instance().GetHalContext();
+
+                       security_keys_data_ptr out;
+                       RawBuffer ivEmpty;
+                       int error = hal_security_keys_decrypt_data(ctx,
+                               convertToHalAlgoType(algo), convertToHalHashType(hash),
+                               convertToHalData(keyId), convertToHalPwdIvTag(pwd),
+                               convertToHalData(cipher), convertToHalData(ivEmpty),
+                               out.Get());
+
+                       ThrowWhenHalError(error, "Failed asymmetric decrypt");
+                       return RawBuffer(out.GetBuffer(), out.GetBuffer() + out.GetLength());
+               }
+               default:
+                       break;
        }
 
        ThrowErr(Exc::Crypto::OperationNotSupported,
@@ -824,59 +955,78 @@ uint32_t initCipher(const RawBuffer &keyId,
 {
        AlgoType algo = unpack<AlgoType>(alg, ParamName::ALGO_TYPE);
 
-       switch (algo)
-       {
-       case AlgoType::AES_GCM: {
-               int tagSizeBits = Params::DEFAULT_AES_GCM_TAG_LEN_BITS;
-               alg.getParam(ParamName::ED_TAG_LEN, tagSizeBits);
-               RawBuffer aad;
-               alg.getParam(ParamName::ED_AAD, aad);
-               return TrustZoneContext::Instance().initGcmCipher(encrypt ? CIPHER_ENCRYPT : CIPHER_DECRYPT,
-                                                                                                                 keyId,
-                                                                                                                 pwd,
-                                                                                                                 unpack<RawBuffer>(alg, ParamName::ED_IV),
-                                                                                                                 tagSizeBits,
-                                                                                                                 aad);
-       }
-       case AlgoType::AES_CBC:
-       case AlgoType::AES_CTR:
-       case AlgoType::AES_CFB:
-               // TODO optionally implement above modes as well
-       default:
-               break;
+       switch (algo) {
+               case AlgoType::AES_GCM: {
+                       int tagSizeBits = Params::DEFAULT_AES_GCM_TAG_LEN_BITS;
+                       alg.getParam(ParamName::ED_TAG_LEN, tagSizeBits);
+                       RawBuffer aad;
+                       alg.getParam(ParamName::ED_AAD, aad);
+                       RawBuffer iv = unpack<RawBuffer>(alg, ParamName::ED_IV);
+                       hal_security_keys_cipher_context_t cipherCtx;
+
+                       auto ctx = HalContext::Instance().GetHalContext();
+                       int error = hal_security_keys_cipher_initialize(ctx, encrypt,
+                               convertToHalData(keyId), convertToHalPwdIvTag(pwd),
+                               convertToHalData(iv), convertToHalData(aad),
+                               tagSizeBits, &cipherCtx);
+
+                       ThrowWhenHalError(error, "Failed initializing cipher");
+                       return cipherCtx;
+               }
+               case AlgoType::AES_CBC:
+               case AlgoType::AES_CTR:
+               case AlgoType::AES_CFB:
+                       // TODO optionally implement above modes as well
+               default:
+                       break;
        };
 
        ThrowErr(Exc::Crypto::OperationNotSupported,
                         "Incorrect algorithm provided for symmetric crypto operation");
 }
 
-void addAAD(uint32_t opId,
-                       const RawBuffer &aad)
+void addAAD(uint32_t opId, const RawBuffer &aad)
 {
-       TrustZoneContext::Instance().addGcmAAD(opId, aad);
+       auto ctx = HalContext::Instance().GetHalContext();
+       int error = hal_security_keys_cipher_add_aad(ctx,
+               static_cast<unsigned int>(opId), convertToHalData(aad));
+
+       ThrowWhenHalError(error, "Failed adding AAD");
 }
 
-RawBuffer updateCipher(uint32_t opId,
-                                          const RawBuffer &data)
+RawBuffer updateCipher(uint32_t opId, const RawBuffer &data)
 {
-       return TrustZoneContext::Instance().updateGcmCipher(opId, data);
+       auto ctx = HalContext::Instance().GetHalContext();
+       security_keys_data_ptr out;
+       int error = hal_security_keys_cipher_update(ctx,
+               static_cast<hal_security_keys_cipher_context_t>(opId), convertToHalData(data), out.Get());
+
+       ThrowWhenHalError(error, "Failed cipher update");
+       return RawBuffer(out.GetBuffer(), out.GetBuffer() + out.GetLength());
 }
 
-RawBuffer finalizeCipher(uint32_t opId,
-                                                const RawBuffer &data)
+RawBuffer finalizeCipher(uint32_t opId, const RawBuffer &data)
 {
-       return TrustZoneContext::Instance().finalizeGcmCipher(opId, data);
+       auto ctx = HalContext::Instance().GetHalContext();
+       security_keys_data_ptr out;
+       int error = hal_security_keys_cipher_finalize(ctx,
+               static_cast<hal_security_keys_cipher_context_t>(opId), convertToHalData(data), out.Get());
+
+       ThrowWhenHalError(error, "Failed cipher finalize");
+       return RawBuffer(out.GetBuffer(), out.GetBuffer() + out.GetLength());
 }
 
 void cleanupCipher(uint32_t opId)
 {
-       return TrustZoneContext::Instance().cleanupCipher(opId);
+       auto ctx = HalContext::Instance().GetHalContext();
+       int error = hal_security_keys_cipher_free(ctx, static_cast<hal_security_keys_cipher_context_t>(opId));
+       ThrowWhenHalError(error, "Failed cipher cleanup");
 }
 
 RawBuffer sign(const RawBuffer &pkeyId,
-                       const Pwd &pwd,
-                       const CryptoAlgorithm &alg,
-                       const RawBuffer &message)
+                          const Pwd &pwd,
+                          const CryptoAlgorithm &alg,
+                          const RawBuffer &message)
 {
        validateParams<IsSignVerify>(alg, g_validators);
 
@@ -890,21 +1040,22 @@ RawBuffer sign(const RawBuffer &pkeyId,
        if (algo == AlgoType::RSA_SV && padding != RSAPaddingAlgorithm::PKCS1)
                ThrowErr(Exc::Crypto::InputParam, "Only PKCS1 padding is supported");
 
-       RawBuffer signature;
-       TrustZoneContext::Instance().executeSign(getAlgType(algo),
-                                                                                       getHashType(hash),
-                                                                                       pkeyId,
-                                                                                       pwd,
-                                                                                       message,
-                                                                                       signature);
-       return signature;
+       auto ctx = HalContext::Instance().GetHalContext();
+       security_keys_data_ptr sign;
+       int error = hal_security_keys_create_signature(ctx,
+               convertToHalAlgoType(algo), convertToHalHashType(hash),
+               convertToHalData(pkeyId), convertToHalPwdIvTag(pwd),
+               convertToHalData(message), sign.Get());
+
+       ThrowWhenHalError(error, "Failed creating signature");
+       return RawBuffer(sign.GetBuffer(), sign.GetBuffer() + sign.GetLength());
 }
 
 int verify(const RawBuffer &pkeyId,
-               const Pwd &pwd,
-               const CryptoAlgorithm &alg,
-               const RawBuffer &message,
-               const RawBuffer &signature)
+                  const Pwd &pwd,
+                  const CryptoAlgorithm &alg,
+                  const RawBuffer &message,
+                  const RawBuffer &signature)
 {
        validateParams<IsSignVerify>(alg, g_validators);
 
@@ -918,12 +1069,14 @@ int verify(const RawBuffer &pkeyId,
        if (algo == AlgoType::RSA_SV && padding != RSAPaddingAlgorithm::PKCS1)
                ThrowErr(Exc::Crypto::InputParam, "Only PKCS1 padding is supported");
 
-       return TrustZoneContext::Instance().executeVerify(getAlgType(algo),
-                                                                                                       getHashType(hash),
-                                                                                                       pkeyId,
-                                                                                                       pwd,
-                                                                                                       message,
-                                                                                                       signature);
+       auto ctx = HalContext::Instance().GetHalContext();
+       int error = hal_security_keys_verify_signature(ctx, convertToHalAlgoType(algo),
+               convertToHalHashType(hash), convertToHalData(pkeyId), convertToHalPwdIvTag(pwd),
+               convertToHalData(message), convertToHalData(signature));
+
+       ThrowWhenHalError(error, "Failed verify signature");
+       return error == HAL_SECURITY_KEYS_ERROR_VERIFICATION_FAILED ?
+               CKM_API_ERROR_VERIFICATION_FAILED : CKM_API_SUCCESS;
 }
 
 void deriveECDH(const RawBuffer &prvKeyId,
@@ -967,34 +1120,32 @@ void deriveECDH(const RawBuffer &prvKeyId,
        RawBuffer secretPwdBuf(secretPwd.begin(), secretPwd.end());
 
        int pubCurve = EC_GROUP_get_curve_name(ecGroup);
-       tz_ec tzCurve;
-       switch (pubCurve)
-       {
-       case NID_X9_62_prime192v1:
-               tzCurve = EC_NIST_P192;
-               break;
-
-       case NID_X9_62_prime256v1:
-               tzCurve = EC_NIST_P256;
-               break;
-
-       case NID_secp384r1:
-               tzCurve = EC_NIST_P384;
-               break;
-
-       default:
-               ThrowErr(Exc::Crypto::InputParam, "Unsupported public key EC");
+       hal_security_keys_ec_type_e ec;
+       switch (pubCurve) {
+               case NID_X9_62_prime192v1:
+                       ec = hal_security_keys_ec_type_e::HAL_SECURITY_KEYS_EC_TYPE_PRIME192V1;
+                       break;
+               case NID_X9_62_prime256v1:
+                       ec = hal_security_keys_ec_type_e::HAL_SECURITY_KEYS_EC_TYPE_PRIME256V1;
+                       break;
+               case NID_secp384r1:
+                       ec = hal_security_keys_ec_type_e::HAL_SECURITY_KEYS_EC_TYPE_SECP384R1;
+                       break;
+               default:
+                       ThrowErr(Exc::Crypto::InputParam, "Unsupported public key EC");
        }
 
-       TrustZoneContext::Instance().executeEcdh(prvKeyId,
-                                                                                        prvKeyPwd,
-                                                                                        tzCurve,
-                                                                                        xBuf,
-                                                                                        yBuf,
-                                                                                        secretPwdBuf,
-                                                                                        secretPwdIV,
-                                                                                        secretTag,
-                                                                                        secretHash);
+       auto ctx = HalContext::Instance().GetHalContext();
+
+       security_keys_data_ptr tag;
+       int error = hal_security_keys_derive_ecdh(ctx, ec,
+               convertToHalData(xBuf), convertToHalData(yBuf),
+               convertToHalData(prvKeyId), convertToHalPwdIvTag(prvKeyPwd),
+               convertToHalData(secretHash), convertToHalPwdIv(secretPwdBuf, secretPwdIV),
+               tag.Get());
+
+       ThrowWhenHalError(error, "Failed deriving ECDH");
+       secretTag.assign(tag.GetBuffer(), tag.GetBuffer() + tag.GetLength());
 }
 
 void deriveKBKDF(const RawBuffer &secretId,
@@ -1018,7 +1169,6 @@ void deriveKBKDF(const RawBuffer &secretId,
        bool hasLLen = alg.getParam(ParamName::KBKDF_LLEN, llenBits);
        bool noSeparator = alg.getParam(ParamName::KBKDF_NO_SEPARATOR, tmp);
 
-       RawBuffer key;
        if (hasFixed) {
                if (hasLabel || hasContext || noSeparator || hasLLen ||
                        counterLocation == KbkdfCounterLocation::MIDDLE_FIXED)
@@ -1030,22 +1180,18 @@ void deriveKBKDF(const RawBuffer &secretId,
 
        RawBuffer keyPwdBuf(keyPwd.begin(), keyPwd.end());
 
-       TrustZoneContext::Instance().executeKbkdf(secretId,
-                                                                                         secretPwd,
-                                                                                         length,
-                                                                                         label,
-                                                                                         context,
-                                                                                         fixed,
-                                                                                         toTzPrf(prf),
-                                                                                         toTzKbkdfMode(mode),
-                                                                                         toTzCtrLoc(counterLocation),
-                                                                                         rlenBits,
-                                                                                         llenBits,
-                                                                                         noSeparator,
-                                                                                         keyPwdBuf,
-                                                                                         keyPwdIV,
-                                                                                         keyTag,
-                                                                                         keyHash);
+       auto ctx = HalContext::Instance().GetHalContext();
+       auto params = convertToHalParams(prf, length, mode, label, context, fixed,
+               counterLocation, rlenBits, llenBits, noSeparator);
+
+       security_keys_data_ptr tag;
+       int error = hal_security_keys_derive_kbkdf(ctx, params,
+               convertToHalData(secretId), convertToHalPwdIvTag(secretPwd),
+               convertToHalData(keyHash), convertToHalPwdIv(keyPwdBuf, keyPwdIV),
+               tag.Get());
+
+       ThrowWhenHalError(error, "Failed deriving KBKDF");
+       keyTag.assign(tag.GetBuffer(), tag.GetBuffer() + tag.GetLength());
 }
 
 void deriveHybridKBKDF(const RawBuffer &firstSecretId,
@@ -1082,29 +1228,30 @@ void deriveHybridKBKDF(const RawBuffer &firstSecretId,
 
        RawBuffer keyPwdBuf(keyPwd.begin(), keyPwd.end());
 
-       TrustZoneContext::Instance().executeHybridKbkdf(firstSecretId,
-                                                                                                       firstSecretPwd,
-                                                                                                       secondSecretId,
-                                                                                                       secondSecretPwd,
-                                                                                                       length,
-                                                                                                       label,
-                                                                                                       context,
-                                                                                                       fixed,
-                                                                                                       toTzPrf(prf),
-                                                                                                       toTzKbkdfMode(mode),
-                                                                                                       toTzCtrLoc(counterLocation),
-                                                                                                       rlenBits,
-                                                                                                       llenBits,
-                                                                                                       noSeparator,
-                                                                                                       keyPwdBuf,
-                                                                                                       keyPwdIV,
-                                                                                                       keyTag,
-                                                                                                       keyHash);
+       auto ctx = HalContext::Instance().GetHalContext();
+       auto params = convertToHalParams(prf, length, mode, label, context, fixed,
+               counterLocation, rlenBits, llenBits, noSeparator);
+
+       security_keys_data_ptr tag;
+       int error = hal_security_keys_derive_hybrid_kbkdf(ctx, params,
+               convertToHalData(firstSecretId), convertToHalPwdIvTag(firstSecretPwd),
+               convertToHalData(secondSecretId), convertToHalPwdIvTag(secondSecretPwd),
+               convertToHalData(keyHash), convertToHalPwdIv(keyPwdBuf, keyPwdIV),
+               tag.Get());
+
+       ThrowWhenHalError(error, "Failed deriving hybrid KBKDF");
+       keyTag.assign(tag.GetBuffer(), tag.GetBuffer() + tag.GetLength());
 }
 
 size_t maxChunkSize()
 {
-       return TrustZoneContext::Instance().getMaxChunkSize();
+       auto ctx = HalContext::Instance().GetHalContext();
+
+       size_t size;
+       int error = hal_security_keys_get_max_chunk_size(ctx, &size);
+       ThrowWhenHalError(error, "Failed getting max chunk size");
+
+       return size;
 }
 
 } // namespace Internals
diff --git a/src/manager/crypto/tz-backend/tz-context.cpp b/src/manager/crypto/tz-backend/tz-context.cpp
deleted file mode 100644 (file)
index bb455e1..0000000
+++ /dev/null
@@ -1,1369 +0,0 @@
-/*
- *  Copyright (c) 2017-2021 Samsung Electronics Co., Ltd. All rights reserved
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License
- */
-/*
- * @file       tz-context.cpp
- * @author     Lukasz Kostyra (l.kostyra@samsung.com)
- * @version    1.0
- */
-
-#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
-
-#include <tz-backend/tz-context.h>
-#include <tz-backend/tz-memory.h>
-#include <generic-backend/exception.h>
-#include <generic-backend/crypto-params.h>
-#include <generic-backend/encryption-params.h>
-#include <dpl/log/log.h>
-
-#include <km_serialization.h>
-#include <km_ta_defines.h>
-
-#include <cstdint>
-#include <cstring>
-#include <cassert>
-#include <unordered_map>
-
-namespace CKM {
-namespace Crypto {
-namespace TZ {
-namespace Internals {
-
-namespace {
-
-// A little bit of extra memory to add to output buffers.
-//
-// We need this extra memory to output for padding purposes - after encryption
-// we can resize the result memory back to its proper size according to
-// whatever TA will return us.
-const uint32_t CIPHER_EXTRA_PADDING_SIZE = 16;
-
-// Maximum size of GCM tag in bytes.
-const size_t MAX_GCM_TAG_SIZE = 16;
-
-// Identifier of our TA
-const TEEC_UUID KEY_MANAGER_TA_UUID = KM_TA_UUID;
-
-//raw to hex string conversion to print persistent storage data ID
-static std::string rawToHexString(const RawBuffer &raw)
-{
-       return hexDump<std::string>(raw);
-}
-
-/*
- * Maximum size for given key type in bytes according to key-manager-ta implementation.
- * Note that they are greater than TEE Internal Core API v1.1.2.50 (Table 5-9) values.
- */
-const std::unordered_map<tz_algo_type, size_t> MAX_KEY_SIZE = {
-       { ALGO_RSA, 4096 / 8 },
-       { ALGO_RSA_SV, 4096 / 8 },
-       { ALGO_DSA_SV, 4096 / 8 },
-       { ALGO_ECDSA_SV, 1024 / 8 } // 384*2 + additional space for DERR encoding
-};
-
-struct EncPwd {
-       const RawBuffer &password;
-       const RawBuffer &iv;
-};
-
-template <typename T>
-void push(TZSerializer& ser, const T& value)
-{
-       ser.Push(new TZSerializableFlag(static_cast<uint32_t>(value)));
-}
-
-template<>
-void push<RawBuffer>(TZSerializer& ser, const RawBuffer& value)
-{
-       ser.Push(new TZSerializableBinary(value));
-}
-
-template<>
-void push<Pwd>(TZSerializer& ser, const Pwd& value)
-{
-       int32_t pwd_flag = value.getPassword().empty() ? 0 : 1;
-       ser.Push(new TZSerializableFlag(pwd_flag));
-       if (pwd_flag)
-               ser.Push(new TZSerializablePwdData(value.getPassword(),
-                                                                                  value.getIV(),
-                                                                                  value.getTag().size() * 8,
-                                                                                  value.getTag()));
-}
-
-template<>
-void push<EncPwd>(TZSerializer& ser, const EncPwd& value)
-{
-       int32_t pwd_flag = value.password.empty() ? 0 : 1;
-       ser.Push(new TZSerializableFlag(pwd_flag));
-       if (pwd_flag)
-               ser.Push(new TZSerializablePwdData(value.password,
-                                                                                  value.iv,
-                                                                                  Params::DEFAULT_AES_GCM_TAG_LEN_BITS));
-}
-
-template <typename T, typename ...Args>
-void push(TZSerializer& ser, const T& first, const Args&... args)
-{
-       push<T>(ser, first);
-       push<Args...>(ser, args...);
-}
-
-template <typename ...Args>
-TZSerializer makeSerializer(const Args&... args)
-{
-       TZSerializer ser;
-       push<Args...>(ser, args...);
-       return ser;
-}
-
-} // anonymous namespace
-
-TrustZoneContext::TrustZoneContext()
-       : m_ContextInitialized(false)
-       , m_SessionInitialized(false)
-{
-       Initialize();
-}
-
-TrustZoneContext::~TrustZoneContext()
-{
-       Destroy();
-}
-
-TrustZoneContext& TrustZoneContext::Instance()
-{
-       static TrustZoneContext instance;
-       return instance;
-}
-
-TEEC_Operation makeOp(uint32_t value, TrustZoneMemory& mem1)
-{
-       TEEC_Operation op;
-
-       op.paramTypes = TEEC_PARAM_TYPES(value, TEEC_MEMREF_WHOLE, TEEC_NONE, TEEC_NONE);
-
-       op.params[1].memref.parent = mem1.Get();
-       op.params[1].memref.offset = 0;
-       op.params[1].memref.size = mem1.Get()->size;
-       return op;
-}
-
-TEEC_Operation makeOp(uint32_t value, TrustZoneMemory& mem1, TrustZoneMemory& mem2)
-{
-       TEEC_Operation op = makeOp(value, mem1);
-
-       op.paramTypes = TEEC_PARAM_TYPES(value, TEEC_MEMREF_WHOLE, TEEC_MEMREF_WHOLE, TEEC_NONE);
-
-       op.params[2].memref.parent = mem2.Get();
-       op.params[2].memref.offset = 0;
-       op.params[2].memref.size = mem2.Get()->size;
-
-       return op;
-}
-
-void TrustZoneContext::generateIV(RawBuffer& iv)
-{
-       // command ID = CMD_GENERATE_IV
-       // IV generation is a simple call - no need to serialize data
-       // just provide the output buffer with size equal to iv.
-       uint32_t ivSize = Params::DEFAULT_AES_IV_LEN;
-       TrustZoneMemory ivMemory(m_Context, ivSize, TEEC_MEM_OUTPUT);
-
-       TEEC_Operation op = makeOp(TEEC_VALUE_INOUT, ivMemory);
-
-       Execute(CMD_GENERATE_IV, &op);
-
-       iv.resize(ivSize);
-       memcpy(iv.data(), ivMemory.Get()->buffer, ivMemory.Get()->size);
-}
-
-void TrustZoneContext::generateSKey(tz_algo_type algo,
-                                                                       uint32_t keySizeBits,
-                                                                       const RawBuffer &hash)
-{
-       // command ID = CMD_GENERATE_KEY
-       auto sIn = makeSerializer(hash);
-       TrustZoneMemory inMemory(m_Context, sIn.GetSize(), TEEC_MEM_INPUT);
-       sIn.Serialize(inMemory);
-
-       TEEC_Operation op = makeOp(TEEC_VALUE_INOUT, inMemory);
-       op.params[0].value.a = algo;
-       op.params[0].value.b = keySizeBits;
-
-       Execute(CMD_GENERATE_KEY, &op);
-}
-
-void TrustZoneContext::generateSKeyPwd(tz_algo_type algo,
-                                                                       const RawBuffer &pwd,
-                                                                       const RawBuffer &iv,
-                                                                       const uint32_t keySizeBits,
-                                                                       RawBuffer &pwdTag,
-                                                                       const RawBuffer &hash)
-{
-       // command ID = CMD_GENERATE_KEY_PWD
-       TZSerializer sIn;
-       sIn.Push(new TZSerializablePwdData(pwd, iv, Params::DEFAULT_AES_GCM_TAG_LEN_BITS));
-       sIn.Push(new TZSerializableBinary(hash));
-       TrustZoneMemory inMemory(m_Context, sIn.GetSize(), TEEC_MEM_INPUT);
-       sIn.Serialize(inMemory);
-
-       TZSerializer sOut;
-       sOut.Push(new TZSerializableBinary(Params::DEFAULT_AES_GCM_TAG_LEN_BYTES));
-       TrustZoneMemory outMemory(m_Context, sOut.GetSize(), TEEC_MEM_OUTPUT);
-
-       TEEC_Operation op = makeOp(TEEC_VALUE_INOUT, inMemory, outMemory);
-       op.params[0].value.a = algo;
-       op.params[0].value.b = keySizeBits;
-
-       Execute(CMD_GENERATE_KEY_PWD, &op);
-
-       sOut.Deserialize(outMemory);
-       sOut.Pull(pwdTag);
-
-       if (pwdTag.size() != Params::DEFAULT_AES_GCM_TAG_LEN_BYTES) {
-               ThrowErr(Exc::Crypto::InternalError, "Deserialized incorrect key tag");
-       }
-}
-
-void TrustZoneContext::GenerateAKey(tz_command commandId,
-                                    TZSerializer &sIn,
-                                    uint32_t genParam, // key size in bits or EC type
-                                    const RawBuffer &pubPwd,
-                                    const RawBuffer &pubPwdIv,
-                                    const RawBuffer &privPwd,
-                                    const RawBuffer &privPwdIv,
-                                    RawBuffer &pubKeyTag,
-                                    RawBuffer &privKeyTag,
-                                    const RawBuffer &hashPriv,
-                                                                       const RawBuffer &hashPub)
-{
-       uint32_t pubPwdExists = pubPwd.empty() ? 0 : 1;
-       TZSerializer sOut;
-       if (pubPwdExists)
-               sOut.Push(new TZSerializableBinary(Params::DEFAULT_AES_GCM_TAG_LEN_BYTES));
-
-       uint32_t privPwdExists = privPwd.empty() ? 0 : 1;
-       if (privPwdExists)
-               sOut.Push(new TZSerializableBinary(Params::DEFAULT_AES_GCM_TAG_LEN_BYTES));
-
-       push(sIn, EncPwd{pubPwd, pubPwdIv}, EncPwd{privPwd, privPwdIv}, hashPriv, hashPub);
-       TrustZoneMemory inMemory(m_Context, sIn.GetSize(), TEEC_MEM_INPUT);
-       sIn.Serialize(inMemory);
-
-       TrustZoneMemory outMemory(m_Context, sOut.GetSize(), TEEC_MEM_OUTPUT);
-
-       TEEC_Operation op;
-       if (sOut.GetSize() == 0) {
-               op = makeOp(TEEC_VALUE_INOUT, inMemory);
-       } else {
-               op = makeOp(TEEC_VALUE_INOUT, inMemory, outMemory);
-       }
-       op.params[0].value.b = genParam;
-
-       Execute(commandId, &op);
-
-       sOut.Deserialize(outMemory);
-       if (pubPwdExists) {
-               sOut.Pull(pubKeyTag);
-       }
-
-       if (privPwdExists) {
-               sOut.Pull(privKeyTag);
-       }
-}
-
-void TrustZoneContext::generateRSAKey(uint32_t keySizeBits,
-                                                                       const RawBuffer &pubPwd,
-                                                                       const RawBuffer &pubPwdIv,
-                                                                       const RawBuffer &privPwd,
-                                                                       const RawBuffer &privPwdIv,
-                                                                       RawBuffer &pubKeyTag,
-                                                                       RawBuffer &privKeyTag,
-                                                                       const RawBuffer &hashPriv,
-                                                                       const RawBuffer &hashPub)
-{
-       // command ID = CMD_GENERATE_RSA_KEYPAIR
-       TZSerializer sIn;
-
-       GenerateAKey(CMD_GENERATE_RSA_KEYPAIR,
-                    sIn,
-                    keySizeBits,
-                    pubPwd,
-                    pubPwdIv,
-                    privPwd,
-                    privPwdIv,
-                    pubKeyTag,
-                    privKeyTag,
-                    hashPriv,
-                    hashPub);
-}
-
-void TrustZoneContext::generateDSAKey(uint32_t keySizeBits,
-                                                                       const RawBuffer &prime,
-                                                                       const RawBuffer &subprime,
-                                                                       const RawBuffer &base,
-                                                                       const RawBuffer &pubPwd,
-                                                                       const RawBuffer &pubPwdIv,
-                                                                       const RawBuffer &privPwd,
-                                                                       const RawBuffer &privPwdIv,
-                                                                       RawBuffer &pubKeyTag,
-                                                                       RawBuffer &privKeyTag,
-                                                                       const RawBuffer &hashPriv,
-                                                                       const RawBuffer &hashPub)
-{
-       // command ID = CMD_GENERATE_DSA_KEYPAIR
-       auto sIn = makeSerializer(prime, subprime, base);
-
-       GenerateAKey(CMD_GENERATE_DSA_KEYPAIR,
-                    sIn,
-                    keySizeBits,
-                    pubPwd,
-                    pubPwdIv,
-                    privPwd,
-                    privPwdIv,
-                    pubKeyTag,
-                    privKeyTag,
-                    hashPriv,
-                    hashPub);
-}
-
-void TrustZoneContext::generateECKey(tz_ec ec,
-                                                                        const RawBuffer &pubPwd,
-                                                                        const RawBuffer &pubPwdIv,
-                                                                        const RawBuffer &privPwd,
-                                                                        const RawBuffer &privPwdIv,
-                                                                        RawBuffer &pubKeyTag,
-                                                                        RawBuffer &privKeyTag,
-                                                                        const RawBuffer &hashPriv,
-                                                                        const RawBuffer &hashPub)
-{
-       // command ID = CMD_GENERATE_EC_KEYPAIR
-       TZSerializer sIn;
-
-       GenerateAKey(CMD_GENERATE_EC_KEYPAIR,
-                    sIn,
-                    static_cast<uint32_t>(ec),
-                    pubPwd,
-                    pubPwdIv,
-                    privPwd,
-                    privPwdIv,
-                    pubKeyTag,
-                    privKeyTag,
-                    hashPriv,
-                    hashPub);
-}
-
-void TrustZoneContext::generateKEMKey(tz_kem kemType,
-                                                                         const RawBuffer &pubPwd,
-                                                                         const RawBuffer &pubPwdIv,
-                                                                         const RawBuffer &privPwd,
-                                                                         const RawBuffer &privPwdIv,
-                                                                         RawBuffer &pubKeyTag,
-                                                                         RawBuffer &privKeyTag,
-                                                                         const RawBuffer &hashPriv,
-                                                                         const RawBuffer &hashPub)
-{
-       // command ID = CMD_GENERATE_KEM_KEYPAIR
-       TZSerializer sIn;
-
-       GenerateAKey(CMD_GENERATE_KEM_KEYPAIR,
-                    sIn,
-                    static_cast<uint32_t>(kemType),
-                    pubPwd,
-                    pubPwdIv,
-                    privPwd,
-                    privPwdIv,
-                    pubKeyTag,
-                    privKeyTag,
-                    hashPriv,
-                    hashPub);
-}
-
-void TrustZoneContext::executeCrypt(tz_command cmd,
-                                                                       tz_algo_type algo,
-                                                                       tz_hash_type hash,
-                                                                       const RawBuffer &keyId,
-                                                                       const Pwd &pwd,
-                                                                       const RawBuffer &iv,
-                                                                       const RawBuffer &data,
-                                                                       RawBuffer &out)
-{
-       // command IDs = CMD_ENCRYPT, CMD_DECRYPT (from km_ta_defines.h)
-       if (keyId.size() != KM_KEY_ID_SIZE) {
-               ThrowErr(Exc::Crypto::InternalError, "TZ Backend received incorrect key buffer (size = "
-                       + std::to_string(keyId.size()) + ")");
-       }
-
-       TZSerializer sIn;
-       if (algo == ALGO_RSA)
-               sIn = makeSerializer(data, pwd, hash, keyId);
-       else
-               sIn = makeSerializer(data, pwd, iv, keyId);
-
-       TrustZoneMemory inMemory(m_Context, sIn.GetSize(), TEEC_MEM_INPUT);
-       sIn.Serialize(inMemory);
-
-       // decrypt operation does not require padding
-       uint32_t outMemorySize = data.size();
-       if (cmd == CMD_ENCRYPT) {
-               if (algo == ALGO_RSA) {
-                       // We don't know the key length
-                       outMemorySize = MAX_KEY_SIZE.at(ALGO_RSA);
-               } else {
-                       outMemorySize = static_cast<uint32_t>(data.size() + CIPHER_EXTRA_PADDING_SIZE);
-               }
-       }
-
-       TZSerializer sOut;
-       sOut.Push(new TZSerializableBinary(outMemorySize, false));
-       TrustZoneMemory outMemory(m_Context, sOut.GetSize(), TEEC_MEM_OUTPUT);
-
-       TEEC_Operation op = makeOp(TEEC_VALUE_INOUT, inMemory, outMemory);
-       op.params[0].value.a = algo;
-
-       Execute(cmd, &op);
-
-       sOut.Deserialize(outMemory);
-       sOut.Pull(out);
-}
-
-void TrustZoneContext::executeEncryptAE(const RawBuffer &keyId,
-                                                                               const Pwd &pwd,
-                                                                               const RawBuffer &iv,
-                                                                               int tagSizeBits,
-                                                                               const RawBuffer &aad,
-                                                                               const RawBuffer &data,
-                                                                               RawBuffer &out,
-                                                                               RawBuffer &tag)
-{
-       // command ID = CMD_ENCRYPT (from km_ta_defines.h)
-       if (keyId.size() != KM_KEY_ID_SIZE) {
-               ThrowErr(Exc::Crypto::InternalError, "TZ Backend received incorrect key buffer");
-       }
-
-       auto sIn = makeSerializer(data, pwd, iv, keyId, aad, tagSizeBits);
-       TrustZoneMemory inMemory(m_Context, sIn.GetSize(), TEEC_MEM_INPUT);
-       sIn.Serialize(inMemory);
-
-       uint32_t outMemorySize = static_cast<uint32_t>(data.size() + CIPHER_EXTRA_PADDING_SIZE);
-       uint32_t tagSizeBytes = (tagSizeBits + 7) / 8;
-
-       TZSerializer sOut;
-       sOut.Push(new TZSerializableBinary(outMemorySize, false));
-       sOut.Push(new TZSerializableBinary(tagSizeBytes));
-       TrustZoneMemory outMemory(m_Context, sOut.GetSize(), TEEC_MEM_OUTPUT);
-
-       TEEC_Operation op = makeOp(TEEC_VALUE_INOUT, inMemory, outMemory);
-       op.params[0].value.a = ALGO_AES_GCM;
-
-       Execute(CMD_ENCRYPT, &op);
-
-       sOut.Deserialize(outMemory);
-       sOut.Pull(out);
-       sOut.Pull(tag);
-}
-
-void TrustZoneContext::executeDecryptAE(const RawBuffer &keyId,
-                                                                               const Pwd &pwd,
-                                                                               const RawBuffer &iv,
-                                                                               int  tagSizeBits,
-                                                                               const RawBuffer &tag,
-                                                                               const RawBuffer &aad,
-                                                                               const RawBuffer &data,
-                                                                               RawBuffer &out)
-{
-       // command ID = CMD_DECRYPT (from km_ta_defines.h)
-       if (keyId.size() != KM_KEY_ID_SIZE) {
-               ThrowErr(Exc::Crypto::InternalError, "TZ Backend received incorrect key buffer");
-       }
-
-       auto sIn = makeSerializer(data, pwd, iv, keyId, aad, tagSizeBits, tag);
-       TrustZoneMemory inMemory(m_Context, sIn.GetSize(), TEEC_MEM_INPUT);
-       sIn.Serialize(inMemory);
-
-       TZSerializer sOut;
-       sOut.Push(new TZSerializableBinary(data.size()));
-       TrustZoneMemory outMemory(m_Context, sOut.GetSize(), TEEC_MEM_OUTPUT);
-
-       TEEC_Operation op = makeOp(TEEC_VALUE_INOUT, inMemory, outMemory);
-       op.params[0].value.a = ALGO_AES_GCM;
-
-       Execute(CMD_DECRYPT, &op);
-
-       sOut.Deserialize(outMemory);
-       sOut.Pull(out);
-}
-
-uint32_t TrustZoneContext::initGcmCipher(uint32_t encrypt,
-                                                                                const RawBuffer &keyId,
-                                                                                const Pwd &pwd,
-                                                                                const RawBuffer &iv,
-                                                                                int tagSizeBits,
-                                                                                const RawBuffer &aad)
-{
-       // command ID = CMD_CIPHER_INIT (from km_ta_defines.h)
-       if (keyId.size() != KM_KEY_ID_SIZE) {
-               ThrowErr(Exc::Crypto::InternalError, "TZ Backend received incorrect key buffer");
-       }
-
-       auto sIn = makeSerializer(pwd, iv, keyId, aad, tagSizeBits);
-       TrustZoneMemory inMemory(m_Context, sIn.GetSize(), TEEC_MEM_INPUT);
-       sIn.Serialize(inMemory);
-
-       TEEC_Operation op = makeOp(TEEC_VALUE_INOUT, inMemory);
-       op.params[0].value.a = ALGO_AES_GCM;
-       op.params[0].value.b = encrypt;
-
-       Execute(CMD_CIPHER_INIT, &op);
-
-       return op.params[0].value.b;
-}
-
-void TrustZoneContext::addGcmAAD(uint32_t opId,
-                                                                const RawBuffer &aad)
-{
-       // command ID = CMD_CIPHER_INIT_AAD (from km_ta_defines.h)
-       auto sIn = makeSerializer(aad);
-       TrustZoneMemory inMemory(m_Context, sIn.GetSize(), TEEC_MEM_INPUT);
-       sIn.Serialize(inMemory);
-
-       TEEC_Operation op = makeOp(TEEC_VALUE_INOUT, inMemory);
-       op.params[0].value.a = opId;
-
-       Execute(CMD_CIPHER_INIT_AAD, &op);
-}
-
-RawBuffer TrustZoneContext::updateGcmCipher(uint32_t opId,
-                                                                                       const RawBuffer &data)
-{
-       auto sIn = makeSerializer(data);
-       TrustZoneMemory inMemory(m_Context, sIn.GetSize(), TEEC_MEM_INPUT);
-       sIn.Serialize(inMemory);
-
-       TZSerializer sOut;
-       sOut.Push(new TZSerializableBinary(data.size()));
-       TrustZoneMemory outMemory(m_Context, sOut.GetSize(), TEEC_MEM_OUTPUT);
-
-       TEEC_Operation op = makeOp(TEEC_VALUE_INOUT, inMemory, outMemory);
-       op.params[0].value.a = opId;
-
-       Execute(CMD_CIPHER_UPDATE, &op);
-
-       sOut.Deserialize(outMemory);
-
-       RawBuffer out;
-       sOut.Pull(out);
-       return out;
-}
-
-RawBuffer TrustZoneContext::finalizeGcmCipher(uint32_t opId,
-                                                                                         const RawBuffer &data)
-{
-       auto sIn = makeSerializer(data);
-       TrustZoneMemory inMemory(m_Context, sIn.GetSize(), TEEC_MEM_INPUT);
-       sIn.Serialize(inMemory);
-
-       TZSerializer sOut;
-       sOut.Push(new TZSerializableBinary(MAX_GCM_TAG_SIZE, false));
-       TrustZoneMemory outMemory(m_Context, sOut.GetSize(), TEEC_MEM_OUTPUT);
-
-       TEEC_Operation op = makeOp(TEEC_VALUE_INOUT, inMemory, outMemory);
-       op.params[0].value.a = opId;
-
-       Execute(CMD_CIPHER_FINALIZE, &op);
-
-       sOut.Deserialize(outMemory);
-
-       RawBuffer out;
-       sOut.Pull(out);
-       return out;
-}
-
-void TrustZoneContext::cleanupCipher(uint32_t opId)
-{
-       TEEC_Operation op;
-       op.paramTypes = TEEC_PARAM_TYPES(TEEC_VALUE_INOUT, TEEC_NONE, TEEC_NONE, TEEC_NONE);
-       op.params[0].value.a = opId;
-
-       Execute(CMD_CIPHER_CLEANUP, &op);
-}
-
-void TrustZoneContext::executeSign(tz_algo_type algo,
-                                                               tz_hash_type hash,
-                                                               const RawBuffer &keyId,
-                                                               const Pwd &pwd,
-                                                               const RawBuffer &message,
-                                                               RawBuffer &signature)
-{
-       // command ID = CMD_SIGN (from km_ta_defines.h)
-       if (keyId.size() != KM_KEY_ID_SIZE) {
-               ThrowErr(Exc::Crypto::InternalError, "TZ Backend received incorrect key buffer (size = "
-                       + std::to_string(keyId.size()) + ")");
-       }
-
-       auto sIn = makeSerializer(message, pwd, keyId);
-       TrustZoneMemory inMemory(m_Context, sIn.GetSize(), TEEC_MEM_INPUT);
-       sIn.Serialize(inMemory);
-
-       TZSerializer sOut;
-       sOut.Push(new TZSerializableBinary(MAX_KEY_SIZE.at(algo), false));
-       TrustZoneMemory outMemory(m_Context, sOut.GetSize(), TEEC_MEM_OUTPUT);
-
-       TEEC_Operation op = makeOp(TEEC_VALUE_INOUT, inMemory, outMemory);
-       op.params[0].value.a = algo;
-       op.params[0].value.b = hash;
-
-       Execute(CMD_SIGN, &op);
-
-       sOut.Deserialize(outMemory);
-       sOut.Pull(signature);
-}
-
-int TrustZoneContext::executeVerify(tz_algo_type algo,
-                                                                       tz_hash_type hash,
-                                                                       const RawBuffer &keyId,
-                                                                       const Pwd &pwd,
-                                                                       const RawBuffer &message,
-                                                                       const RawBuffer &signature)
-{
-       // command ID = CMD_VERIFY (from km_ta_defines.h)
-       if (keyId.size() != KM_KEY_ID_SIZE) {
-               ThrowErr(Exc::Crypto::InternalError, "TZ Backend received incorrect key buffer (size = "
-                       + std::to_string(keyId.size()) + ")");
-       }
-
-       auto sIn = makeSerializer(message, signature, pwd, keyId);
-       TrustZoneMemory inMemory(m_Context, sIn.GetSize(), TEEC_MEM_INPUT);
-       sIn.Serialize(inMemory);
-
-       TEEC_Operation op = makeOp(TEEC_VALUE_INOUT, inMemory);
-       op.params[0].value.a = algo;
-       op.params[0].value.b = hash;
-
-       Execute(CMD_VERIFY, &op);
-
-       int opRet = op.params[0].value.a;
-       switch (opRet) {
-       case KM_TA_SUCCESS:
-               return CKM_API_SUCCESS;
-       case KM_TA_ERROR_SIGNATURE:
-               LogWarning("Signature verification failed");
-               return CKM_API_ERROR_VERIFICATION_FAILED;
-       default:
-               assert(false); // This condition should be checked inside Execute() function
-               ThrowErr(Exc::Crypto::InternalError, "Unknown TA error during operation: ", opRet);
-       }
-}
-
-void TrustZoneContext::executeDestroy(const RawBuffer &keyId)
-{
-       // command ID = CMD_DESTROY_KEY (from km_ta_defines.h)
-       if (keyId.size() != KM_KEY_ID_SIZE) {
-               ThrowErr(Exc::Crypto::InternalError, "TZ Backend received incorrect key buffer");
-       }
-
-       auto sIn = makeSerializer(keyId);
-       TrustZoneMemory inMemory(m_Context, sIn.GetSize(), TEEC_MEM_INPUT);
-       sIn.Serialize(inMemory);
-
-       TEEC_Operation op = makeOp(TEEC_VALUE_OUTPUT, inMemory);
-
-       Execute(CMD_DESTROY_KEY, &op);
-}
-
-void TrustZoneContext::importData(
-                               const uint32_t dataType,
-                               const RawBuffer &data,
-                               const Crypto::EncryptionParams &encData,
-                               const RawBuffer &pwd,
-                               const RawBuffer &iv,
-                               const uint32_t keySizeBits,
-                               RawBuffer &pwdTag,
-                               const RawBuffer &hash)
-{
-       // command ID = CMD_IMPORT_DATA
-       LogDebug("TrustZoneContext::importData data size = [" << data.size() << "]");
-
-       auto sIn = makeSerializer(
-               dataType, data, keySizeBits, encData.iv, encData.tag, EncPwd{pwd, iv}, hash);
-
-       TrustZoneMemory inMemory(m_Context, sIn.GetSize(), TEEC_MEM_INPUT);
-       sIn.Serialize(inMemory);
-
-       TZSerializer sOut;
-       if (!pwd.empty()) {
-               sOut.Push(new TZSerializableBinary(Params::DEFAULT_AES_GCM_TAG_LEN_BYTES));
-       }
-
-       TrustZoneMemory outMemory(m_Context, sOut.GetSize(), TEEC_MEM_OUTPUT);
-
-       TEEC_Operation op = makeOp(TEEC_VALUE_INOUT, inMemory);
-       if (!pwd.empty())
-               op = makeOp(TEEC_VALUE_INOUT, inMemory, outMemory);
-
-       Execute(CMD_IMPORT_DATA, &op);
-
-       if (!pwd.empty()) {
-               sOut.Deserialize(outMemory);
-               sOut.Pull(pwdTag);
-       }
-
-       LogDebug("Imported object ID is (hex): " << rawToHexString(hash));
-}
-
-void TrustZoneContext::importWrappedKey(const RawBuffer &wrappingKeyId,
-                                                                               const Pwd &wrappingKeyPwd,
-                                                                               tz_algo_type algo,
-                                                                               tz_hash_type oaepHash,
-                                                                               const RawBuffer &iv,
-                                                                               const uint32_t ctrLenOrTagSizeBits,
-                                                                               const RawBuffer &aad,
-                                                                               const tz_data_type encryptedKeyType,
-                                                                               const RawBuffer &encryptedKey,
-                                                                               const RawBuffer &encryptedKeyPwdBuf,
-                                                                               const RawBuffer &encryptedKeyIV,
-                                                                               RawBuffer &encryptedKeyTag,
-                                                                               const RawBuffer &encryptedKeyId)
-{
-       // command ID = CMD_IMPORT_WRAPPED_KEY
-       LogDebug("TrustZoneContext::importWrappedKey encryptedKey size = [" << encryptedKey.size() << "]");
-
-       TZSerializer sIn;
-       if (algo == ALGO_RSA) {
-               sIn = makeSerializer(wrappingKeyId,
-                                                        wrappingKeyPwd,
-                                                        algo,
-                                                        oaepHash,
-                                                        encryptedKeyType,
-                                                        encryptedKey,
-                                                        EncPwd{encryptedKeyPwdBuf, encryptedKeyIV},
-                                                        encryptedKeyId);
-       } else {
-               sIn = makeSerializer(wrappingKeyId,
-                                                        wrappingKeyPwd,
-                                                        algo,
-                                                        iv,
-                                                        ctrLenOrTagSizeBits,
-                                                        aad,
-                                                        encryptedKeyType,
-                                                        encryptedKey,
-                                                        EncPwd{encryptedKeyPwdBuf, encryptedKeyIV},
-                                                        encryptedKeyId);
-       }
-
-       TrustZoneMemory inMemory(m_Context, sIn.GetSize(), TEEC_MEM_INPUT);
-       sIn.Serialize(inMemory);
-
-       TZSerializer sOut;
-       if (!encryptedKeyPwdBuf.empty()) {
-               sOut.Push(new TZSerializableBinary(Params::DEFAULT_AES_GCM_TAG_LEN_BYTES));
-       }
-
-       TrustZoneMemory outMemory(m_Context, sOut.GetSize(), TEEC_MEM_OUTPUT);
-
-       TEEC_Operation op = makeOp(TEEC_VALUE_INOUT, inMemory);
-       if (!encryptedKeyPwdBuf.empty())
-               op = makeOp(TEEC_VALUE_INOUT, inMemory, outMemory);
-
-       Execute(CMD_IMPORT_WRAPPED_KEY, &op);
-
-       if (!encryptedKeyPwdBuf.empty()) {
-               sOut.Deserialize(outMemory);
-               sOut.Pull(encryptedKeyTag);
-       }
-
-       LogDebug("Imported object ID is (hex): " << rawToHexString(encryptedKeyId));
-}
-
-RawBuffer TrustZoneContext::exportWrappedKey(const RawBuffer &wrappingKeyId,
-                                                                                        const Pwd &wrappingKeyPwd,
-                                                                                        tz_algo_type algo,
-                                                                                        tz_hash_type oaepHash,
-                                                                                        const RawBuffer &iv,
-                                                                                        const uint32_t ctrLenOrTagSizeBits,
-                                                                                        const RawBuffer &aad,
-                                                                                        const RawBuffer &keyToWrapId,
-                                                                                        const Pwd &keyToWrapPwd,
-                                                                                        tz_data_type keyToWrapType)
-{
-       // command ID = CMD_EXPORT_WRAPPED_KEY
-       LogDebug("TrustZoneContext::exportWrappedKey");
-
-       TZSerializer sIn;
-       if (algo == ALGO_RSA) {
-               sIn = makeSerializer(wrappingKeyId,
-                                                        wrappingKeyPwd,
-                                                        algo,
-                                                        oaepHash,
-                                                        keyToWrapId,
-                                                        keyToWrapPwd,
-                                                        keyToWrapType);
-       } else {
-               sIn = makeSerializer(wrappingKeyId,
-                                                        wrappingKeyPwd,
-                                                        algo,
-                                                        iv,
-                                                        ctrLenOrTagSizeBits,
-                                                        aad,
-                                                        keyToWrapId,
-                                                        keyToWrapPwd,
-                                                        keyToWrapType);
-       }
-
-       TrustZoneMemory inMemory(m_Context, sIn.GetSize(), TEEC_MEM_INPUT);
-       sIn.Serialize(inMemory);
-
-       uint32_t dataSize = 0;
-       GetDataSize(keyToWrapId, keyToWrapPwd, keyToWrapType, dataSize);
-
-       LogDebug("GetData data_size = [" << dataSize << "]");
-
-       uint32_t enc_overhead = KM_ENCRYPTION_OVERHEAD;
-       if (algo == ALGO_RSA)
-               enc_overhead = KM_RSA_BLOCK_SIZE;
-
-       // encrypted data may be longer
-       TZSerializer sOut;
-       sOut.Push(new TZSerializableBinary(dataSize + enc_overhead, false));
-       TrustZoneMemory outMemory(m_Context, sOut.GetSize(), TEEC_MEM_OUTPUT);
-       sOut.Serialize(outMemory);
-
-       TEEC_Operation op = makeOp(TEEC_VALUE_INOUT, inMemory, outMemory);
-
-       Execute(CMD_EXPORT_WRAPPED_KEY, &op);
-
-       sOut.Deserialize(outMemory);
-
-       RawBuffer wrappedKey;
-       sOut.Pull(wrappedKey);
-
-       return wrappedKey;
-}
-
-RawBuffer TrustZoneContext::wrapConcatenatedData(const RawBuffer &wrappingKeyId,
-                                                                                                const Pwd &wrappingKeyPwd,
-                                                                                                tz_algo_type algo,
-                                                                                                tz_hash_type oaepHash,
-                                                                                                const RawBuffer &keyToWrapId,
-                                                                                                const Pwd &keyToWrapPwd,
-                                                                                                const RawBuffer &userData)
-{
-       // command ID = CMD_WRAP_CONCATENATED_DATA
-       LogDebug("TrustZoneContext::wrapConcatenatedData");
-
-       if (algo != ALGO_RSA) {
-               ThrowErr(Exc::Crypto::InputParam, "Only RSA is supported in wrapConcatenatedData");
-       }
-
-       TZSerializer sIn = makeSerializer(wrappingKeyId,
-                                                        wrappingKeyPwd,
-                                                        algo,
-                                                        oaepHash,
-                                                        keyToWrapId,
-                                                        keyToWrapPwd,
-                                                        userData);
-
-       TrustZoneMemory inMemory(m_Context, sIn.GetSize(), TEEC_MEM_INPUT);
-       sIn.Serialize(inMemory);
-
-       uint32_t outMemorySize = KM_RSA_BLOCK_SIZE;
-       TZSerializer sOut;
-       sOut.Push(new TZSerializableBinary(outMemorySize, false));
-       TrustZoneMemory outMemory(m_Context, sOut.GetSize(), TEEC_MEM_OUTPUT);
-       sOut.Serialize(outMemory);
-
-       TEEC_Operation op = makeOp(TEEC_VALUE_INOUT, inMemory, outMemory);
-       Execute(CMD_WRAP_CONCATENATED_DATA, &op);
-       sOut.Deserialize(outMemory);
-
-       RawBuffer wrappedKey;
-       sOut.Pull(wrappedKey);
-
-       return wrappedKey;
-}
-
-RawBuffer TrustZoneContext::unwrapConcatenatedData(const RawBuffer &wrappingKeyId,
-                                                                                                  const Pwd &wrappingKeyPwd,
-                                                                                                  tz_algo_type algo,
-                                                                                                  tz_hash_type oaepHash,
-                                                                                                  const tz_data_type encryptedKeyType,
-                                                                                                  const RawBuffer &encryptedKey,
-                                                                                                  const RawBuffer &encryptedKeyPwdBuf,
-                                                                                                  const RawBuffer &encryptedKeyIV,
-                                                                                                  RawBuffer &encryptedKeyTag,
-                                                                                                  const RawBuffer &encryptedKeyId,
-                                                                                                  size_t keySize)
-{
-       // command ID = CMD_UNWRAP_CONCATENATED_DATA
-       LogDebug("TrustZoneContext::unwrapConcatenatedData");
-
-       if (algo != ALGO_RSA) {
-               ThrowErr(Exc::Crypto::InputParam, "Only RSA is supported in wrapConcatenatedData");
-       }
-
-       TZSerializer sIn = makeSerializer(wrappingKeyId,
-                                                        wrappingKeyPwd,
-                                                        algo,
-                                                        oaepHash,
-                                                        encryptedKeyType,
-                                                        encryptedKey,
-                                                        EncPwd{encryptedKeyPwdBuf, encryptedKeyIV},
-                                                        encryptedKeyId,
-                                                        keySize);
-
-       TrustZoneMemory inMemory(m_Context, sIn.GetSize(), TEEC_MEM_INPUT);
-       sIn.Serialize(inMemory);
-
-       TZSerializer sOut;
-       uint32_t outMemorySize = KM_RSA_BLOCK_SIZE;
-       if (!encryptedKeyPwdBuf.empty()) {
-               outMemorySize += Params::DEFAULT_AES_GCM_TAG_LEN_BYTES;
-       }
-       sOut.Push(new TZSerializableBinary(outMemorySize, false));
-       TrustZoneMemory outMemory(m_Context, sOut.GetSize(), TEEC_MEM_OUTPUT);
-       sOut.Serialize(outMemory);
-
-       TEEC_Operation op = makeOp(TEEC_VALUE_INOUT, inMemory, outMemory);
-       Execute(CMD_UNWRAP_CONCATENATED_DATA, &op);
-
-       sOut.Deserialize(outMemory);
-
-       RawBuffer userData;
-       sOut.Pull(userData);
-       if (!encryptedKeyPwdBuf.empty()) {
-               sOut.Pull(encryptedKeyTag);
-       }
-
-       return userData;
-}
-
-RawBuffer TrustZoneContext::encapsulateKey(const RawBuffer &publicKeyId,
-                                                                                  const Pwd &publicKeyPwd,
-                                                                                  tz_kem kemType,
-                                                                                  const RawBuffer &sharedSecretPwdBuf,
-                                                                                  const RawBuffer &sharedSecretIV,
-                                                                                  RawBuffer &sharedSecretTag,
-                                                                                  const RawBuffer &sharedSecretId)
-{
-       // command ID = CMD_ENCAPSULATE_KEY
-       LogDebug("TrustZoneContext::encapsulateKey");
-
-       TZSerializer sIn = makeSerializer(publicKeyId,
-                                                                         publicKeyPwd,
-                                                                         EncPwd{sharedSecretPwdBuf, sharedSecretIV},
-                                                                         sharedSecretId);
-
-       TrustZoneMemory inMemory(m_Context, sIn.GetSize(), TEEC_MEM_INPUT);
-       sIn.Serialize(inMemory);
-
-       TZSerializer sOut;
-       uint32_t outMemorySize = 0;
-       switch (kemType)
-       {
-       case ML_KEM_768:
-               outMemorySize = 1088;
-               break;
-       case ML_KEM_1024:
-               outMemorySize = 1568;
-               break;
-       default:
-               break;
-       }
-       sOut.Push(new TZSerializableBinary(outMemorySize, false));
-       if (!sharedSecretPwdBuf.empty()) {
-               uint32_t tagSizeBytes = Params::DEFAULT_AES_GCM_TAG_LEN_BYTES;
-               sOut.Push(new TZSerializableBinary(tagSizeBytes));
-       }
-       TrustZoneMemory outMemory(m_Context, sOut.GetSize(), TEEC_MEM_OUTPUT);
-
-       TEEC_Operation op = makeOp(TEEC_VALUE_INOUT, inMemory, outMemory);
-       op.params[0].value.a = static_cast<uint32_t>(kemType);
-
-       Execute(CMD_ENCAPSULATE_KEY, &op);
-
-       sOut.Deserialize(outMemory);
-       RawBuffer ciphertext;
-       sOut.Pull(ciphertext);
-
-       if (!sharedSecretPwdBuf.empty()) {
-               sOut.Pull(sharedSecretTag);
-       }
-
-       return ciphertext;
-}
-
-void TrustZoneContext::decapsulateKey(const RawBuffer &privateKeyId,
-                                                                         const Pwd &privateKeyPwd,
-                                                                         tz_kem kemType,
-                                                                         const RawBuffer &sharedSecretPwdBuf,
-                                                                         const RawBuffer &sharedSecretIV,
-                                                                         RawBuffer &sharedSecretTag,
-                                                                         const RawBuffer &sharedSecretId,
-                                                                         const RawBuffer &ciphertext)
-{
-       // command ID = CMD_DECAPSULATE_KEY
-       LogDebug("TrustZoneContext::decapsulateKey");
-
-       TZSerializer sIn = makeSerializer(privateKeyId,
-                                                                         privateKeyPwd,
-                                                                         EncPwd{sharedSecretPwdBuf, sharedSecretIV},
-                                                                         sharedSecretId,
-                                                                         ciphertext);
-
-       TrustZoneMemory inMemory(m_Context, sIn.GetSize(), TEEC_MEM_INPUT);
-       sIn.Serialize(inMemory);
-
-       TZSerializer sOut;
-       if (!sharedSecretPwdBuf.empty()) {
-               uint32_t tagSizeBytes = Params::DEFAULT_AES_GCM_TAG_LEN_BYTES;
-               sOut.Push(new TZSerializableBinary(tagSizeBytes));
-       }
-       TrustZoneMemory outMemory(m_Context, sOut.GetSize(), TEEC_MEM_OUTPUT);
-
-       TEEC_Operation op = makeOp(TEEC_VALUE_INOUT, inMemory);
-       if (!sharedSecretPwdBuf.empty())
-               op = makeOp(TEEC_VALUE_INOUT, inMemory, outMemory);
-
-       op.params[0].value.a = static_cast<uint32_t>(kemType);
-
-       Execute(CMD_DECAPSULATE_KEY, &op);
-
-       if (!sharedSecretPwdBuf.empty()) {
-               sOut.Deserialize(outMemory);
-               sOut.Pull(sharedSecretTag);
-       }
-}
-
-void TrustZoneContext::GetDataSize(const RawBuffer &dataId,
-                                                                  const Pwd &pwd,
-                                                                  const tz_data_type type,
-                                                                  uint32_t &dataSize)
-{
-       // command ID = CMD_GET_DATA_SIZE
-       LogDebug("Object ID (passed to CMD_GET_DATA_SIZE) is (hex): " << rawToHexString(dataId));
-
-       auto sIn = makeSerializer(dataId, pwd, type);
-       TrustZoneMemory inMemory(m_Context, sIn.GetSize(), TEEC_MEM_INPUT);
-       sIn.Serialize(inMemory);
-
-       TEEC_Operation op = makeOp(TEEC_VALUE_OUTPUT, inMemory);
-
-       Execute(CMD_GET_DATA_SIZE, &op);
-       dataSize = op.params[0].value.b;
-}
-
-void TrustZoneContext::getData(const RawBuffer &dataId,
-                        const Pwd &pwd,
-                        const tz_data_type type,
-                        RawBuffer &data)
-{
-       // command ID = CMD_GET_DATA
-       LogDebug("Object ID (passed to CMD_GET_DATA) is (hex): " << rawToHexString(dataId));
-
-       auto sIn = makeSerializer(dataId, pwd, type);
-       TrustZoneMemory inMemory(m_Context, sIn.GetSize(), TEEC_MEM_INPUT);
-       sIn.Serialize(inMemory);
-
-       uint32_t data_size = 0;
-       GetDataSize(dataId, pwd, type, data_size);
-
-       LogDebug("GetData data_size = [" << data_size << "]");
-
-       TZSerializer sOut;
-       sOut.Push(new TZSerializableBinary(data_size));
-       TrustZoneMemory outMemory(m_Context, sOut.GetSize(), TEEC_MEM_OUTPUT);
-       sOut.Serialize(outMemory);
-
-       TEEC_Operation op = makeOp(TEEC_VALUE_INOUT, inMemory, outMemory);
-
-       Execute(CMD_GET_DATA, &op);
-
-       sOut.Deserialize(outMemory);
-       sOut.Pull(data);
-}
-
-void TrustZoneContext::destroyData(const RawBuffer &dataId)
-{
-       //      command ID = CMD_DESTROY_DATA
-       LogDebug("Object ID (passed to CMD_GET_DATA) is (hex): " << rawToHexString(dataId));
-       auto sIn = makeSerializer(dataId);
-       TrustZoneMemory inMemory(m_Context, sIn.GetSize(), TEEC_MEM_INPUT);
-       sIn.Serialize(inMemory);
-
-       TEEC_Operation op = makeOp(TEEC_VALUE_OUTPUT, inMemory);
-
-       Execute(CMD_DESTROY_DATA, &op);
-}
-
-TZSerializablePwdData* makeSerializablePwd(const Pwd &pwd)
-{
-       auto &tag = pwd.getTag();
-       return new TZSerializablePwdData(pwd.getPassword(), pwd.getIV(), tag.size() * 8, tag);
-}
-
-void TrustZoneContext::executeEcdh(const RawBuffer &prvKeyId,
-                                                                  const Pwd &prvKeyPwd,
-                                                                  const tz_ec curve,
-                                                                  const RawBuffer &pubX,
-                                                                  const RawBuffer &pubY,
-                                                                  const RawBuffer &secretPwdBuf,
-                                                                  const RawBuffer &secretPwdIV,
-                                                                  RawBuffer &secretTag,
-                                                                  const RawBuffer &secretHash)
-{
-       // command ID = CMD_DERIVE
-       LogDebug("TrustZoneContext::executeEcdh");
-
-       auto sIn = makeSerializer(
-               prvKeyId, prvKeyPwd, curve, pubX, pubY, EncPwd{secretPwdBuf, secretPwdIV}, secretHash);
-       TrustZoneMemory inMemory(m_Context, sIn.GetSize(), TEEC_MEM_INPUT);
-       sIn.Serialize(inMemory);
-
-       TZSerializer sOut;
-       if (!secretPwdBuf.empty()) {
-               sOut.Push(new TZSerializableBinary(Params::DEFAULT_AES_GCM_TAG_LEN_BYTES));
-       }
-
-       TrustZoneMemory outMemory(m_Context, sOut.GetSize(), TEEC_MEM_OUTPUT);
-
-       TEEC_Operation op = makeOp(TEEC_VALUE_INOUT, inMemory);
-       if (!secretPwdBuf.empty())
-               op = makeOp(TEEC_VALUE_INOUT, inMemory, outMemory);
-       op.params[0].value.a = ALGO_ECDH_DRV;
-
-       Execute(CMD_DERIVE, &op);
-
-       if (!secretPwdBuf.empty()) {
-               sOut.Deserialize(outMemory);
-               sOut.Pull(secretTag);
-       }
-
-       LogDebug("Derived object ID is (hex): " << rawToHexString(secretHash));
-}
-
-void TrustZoneContext::executeKbkdf(const RawBuffer& secretId,
-                                                                       const Pwd& secretPwd,
-                                                                       size_t length,
-                                                                       const RawBuffer& label,
-                                                                       const RawBuffer& context,
-                                                                       const RawBuffer& fixed,
-                                                                       tz_prf prf,
-                                                                       tz_kbkdf_mode mode,
-                                                                       tz_kbkdf_ctr_loc location,
-                                                                       size_t rlen,
-                                                                       size_t llen,
-                                                                       bool noSeparator,
-                                                                       const RawBuffer &keyPwdBuf,
-                                                                       const RawBuffer &keyPwdIV,
-                                                                       RawBuffer &keyTag,
-                                                                       const RawBuffer &keyHash)
-{
-       // command ID = CMD_DERIVE
-       LogDebug("TrustZoneContext::executeKbkdf");
-
-       auto sIn = makeSerializer(secretId,
-                                                         secretPwd,
-                                                         length,
-                                                         label,
-                                                         context,
-                                                         fixed,
-                                                         prf,
-                                                         mode,
-                                                         location,
-                                                         rlen,
-                                                         llen,
-                                                         noSeparator,
-                                                         EncPwd{keyPwdBuf, keyPwdIV}, keyHash);
-
-       TrustZoneMemory inMemory(m_Context, sIn.GetSize(), TEEC_MEM_INPUT);
-       sIn.Serialize(inMemory);
-
-       TZSerializer sOut;
-       if (!keyPwdBuf.empty()) {
-               sOut.Push(new TZSerializableBinary(Params::DEFAULT_AES_GCM_TAG_LEN_BYTES));
-       }
-
-       TrustZoneMemory outMemory(m_Context, sOut.GetSize(), TEEC_MEM_OUTPUT);
-
-       TEEC_Operation op = makeOp(TEEC_VALUE_INOUT, inMemory);
-       if (!keyPwdBuf.empty())
-               op = makeOp(TEEC_VALUE_INOUT, inMemory, outMemory);
-       op.params[0].value.a = ALGO_KBKDF_DRV;
-
-       Execute(CMD_DERIVE, &op);
-
-       if (!keyPwdBuf.empty()) {
-               sOut.Deserialize(outMemory);
-               sOut.Pull(keyTag);
-       }
-
-       LogDebug("Derived object ID is (hex): " << rawToHexString(keyHash));
-}
-
-void TrustZoneContext::executeHybridKbkdf(const RawBuffer& firstSecretId,
-                                                                                 const Pwd& firstSecretPwd,
-                                                                                 const RawBuffer& secondSecretId,
-                                                                                 const Pwd& secondSecretPwd,
-                                                                                 size_t length,
-                                                                                 const RawBuffer& label,
-                                                                                 const RawBuffer& context,
-                                                                                 const RawBuffer& fixed,
-                                                                                 tz_prf prf,
-                                                                                 tz_kbkdf_mode mode,
-                                                                                 tz_kbkdf_ctr_loc location,
-                                                                                 size_t rlen,
-                                                                                 size_t llen,
-                                                                                 bool noSeparator,
-                                                                                 const RawBuffer &keyPwdBuf,
-                                                                                 const RawBuffer &keyPwdIV,
-                                                                                 RawBuffer &keyTag,
-                                                                                 const RawBuffer &keyHash)
-{
-       // command ID = CMD_DERIVE_HYBRID
-       LogDebug("TrustZoneContext::executeHybridKbkdf");
-
-       auto sIn = makeSerializer(firstSecretId,
-                                                         firstSecretPwd,
-                                                         secondSecretId,
-                                                         secondSecretPwd,
-                                                         length,
-                                                         label,
-                                                         context,
-                                                         fixed,
-                                                         prf,
-                                                         mode,
-                                                         location,
-                                                         rlen,
-                                                         llen,
-                                                         noSeparator,
-                                                         EncPwd{keyPwdBuf, keyPwdIV}, keyHash);
-
-       TrustZoneMemory inMemory(m_Context, sIn.GetSize(), TEEC_MEM_INPUT);
-       sIn.Serialize(inMemory);
-
-       TZSerializer sOut;
-       if (!keyPwdBuf.empty()) {
-               sOut.Push(new TZSerializableBinary(Params::DEFAULT_AES_GCM_TAG_LEN_BYTES));
-       }
-
-       TrustZoneMemory outMemory(m_Context, sOut.GetSize(), TEEC_MEM_OUTPUT);
-
-       TEEC_Operation op = makeOp(TEEC_VALUE_INOUT, inMemory);
-       if (!keyPwdBuf.empty())
-               op = makeOp(TEEC_VALUE_INOUT, inMemory, outMemory);
-       op.params[0].value.a = ALGO_KBKDF_DRV;
-
-       Execute(CMD_DERIVE_HYBRID, &op);
-
-       if (!keyPwdBuf.empty()) {
-               sOut.Deserialize(outMemory);
-               sOut.Pull(keyTag);
-       }
-
-       LogDebug("Derived object ID is (hex): " << rawToHexString(keyHash));
-}
-
-uint32_t TrustZoneContext::getMaxChunkSize()
-{
-       // command ID = CMD_GET_MAX_CHUNK_SIZE
-       LogDebug("TrustZoneContext::getMaxChunkSize");
-
-       TEEC_Operation op;
-       op.paramTypes = TEEC_PARAM_TYPES(TEEC_VALUE_OUTPUT, TEEC_NONE, TEEC_NONE, TEEC_NONE);
-
-       Execute(CMD_GET_MAX_CHUNK_SIZE, &op);
-
-       return op.params[0].value.b;
-}
-
-void TrustZoneContext::Initialize()
-{
-       TEEC_Operation op;
-       TEEC_Result result;
-       uint32_t retOrigin;
-
-       op.paramTypes = TEEC_PARAM_TYPES(TEEC_NONE, TEEC_NONE, TEEC_NONE, TEEC_NONE);
-
-       result = TEEC_InitializeContext(nullptr, &m_Context);
-       if (result != TEEC_SUCCESS) {
-               ThrowErr(Exc::Crypto::InternalError, "Failed to initialize TEE context: ", result);
-       }
-       m_ContextInitialized = true;
-
-       result = TEEC_OpenSession(&m_Context, &m_Session, &KEY_MANAGER_TA_UUID, 0, nullptr, &op, &retOrigin);
-       if (result != TEEC_SUCCESS) {
-               ThrowErr(Exc::Crypto::InternalError, "Failed to open session to Key Manager TA: ", result);
-       }
-       m_SessionInitialized = true;
-}
-
-void TrustZoneContext::Destroy()
-{
-       if (m_SessionInitialized) {
-               TEEC_CloseSession(&m_Session);
-               m_SessionInitialized = false;
-       }
-
-       if (m_ContextInitialized) {
-               TEEC_FinalizeContext(&m_Context);
-               m_ContextInitialized = false;
-       }
-}
-
-void TrustZoneContext::Reload()
-{
-       Destroy();
-       Initialize();
-}
-
-void TrustZoneContext::Execute(tz_command commandID, TEEC_Operation* op)
-{
-       uint32_t retOrigin = 0;
-       LogDebug("Executing TZ operation " << commandID);
-
-       TEEC_Result result = TEEC_InvokeCommand(&m_Session, static_cast<unsigned int>(commandID), op, &retOrigin);
-       if (result != TEEC_SUCCESS) {
-               switch (result) {
-               case TEEC_ERROR_TARGET_DEAD:
-                       Reload();
-                       ThrowErr(Exc::Crypto::InternalError, "TA panicked while executing command ",
-                                       static_cast<unsigned int>(commandID));
-               case TEEC_ERROR_BAD_PARAMETERS:
-                       ThrowErr(Exc::Crypto::InputParam, "Incorrect parameters provided to TA");
-               default:
-                       ThrowErr(Exc::Crypto::InternalError, "TA failed to invoke command ",
-                                       static_cast<unsigned int>(commandID), " with error: ", std::hex,
-                                       static_cast<unsigned int>(result), " with origin: ", std::hex,
-                                       retOrigin);
-               }
-       }
-
-       int ta_ret = op->params[0].value.a;
-       switch (ta_ret) {
-       case KM_TA_SUCCESS:
-       case KM_TA_ERROR_SIGNATURE:
-               break;
-       case KM_TA_ERROR_AUTH_FAILED:
-               // Authentication cipher failed - notify with proper exception
-               ThrowErr(Exc::AuthenticationFailed, "Crypto operation authentication failed");
-       default:
-               ThrowErr(Exc::Crypto::InternalError, "Unknown TA error during operation: ", ta_ret);
-       }
-}
-
-} // namespace Internals
-} // namespace TZ
-} // namespace Crypto
-} // namespace CKM
diff --git a/src/manager/crypto/tz-backend/tz-context.h b/src/manager/crypto/tz-backend/tz-context.h
deleted file mode 100644 (file)
index ce82b6c..0000000
+++ /dev/null
@@ -1,316 +0,0 @@
-/*
- *  Copyright (c) 2017 - 2019 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License
- */
-/*
- * @file       tz-context.h
- * @author     Lukasz Kostyra (l.kostyra@samsung.com)
- * @version    1.0
- */
-#pragma once
-
-#include <tee_client_api.h>
-#include <ckm/ckm-raw-buffer.h>
-#include <data-type.h>
-#include <km_ta_defines.h>
-#include <memory>
-#include <tz-backend/obj.h>
-#include <generic-backend/encryption-params.h>
-#include <tz-backend/tz-serializer.h>
-
-namespace CKM {
-namespace Crypto {
-namespace TZ {
-namespace Internals {
-
-class TrustZoneContext final
-{
-public:
-       static TrustZoneContext& Instance();
-
-       void generateIV(RawBuffer &iv);
-       void generateSKey(tz_algo_type algo,
-                                       uint32_t keySizeBits,
-                                       const RawBuffer &hash);
-       void generateSKeyPwd(tz_algo_type algo,
-                                               const RawBuffer &pwd,
-                                               const RawBuffer &iv,
-                                               const uint32_t pwdKeySizeBits,
-                                               RawBuffer &pwdTag,
-                                               const RawBuffer &hash);
-       void generateRSAKey(uint32_t keySizeBits,
-                                       const RawBuffer &pubPwd,
-                                       const RawBuffer &pubPwdIv,
-                                       const RawBuffer &privPwd,
-                                       const RawBuffer &privPwdIv,
-                                       RawBuffer &pubKeyTag,
-                                       RawBuffer &privKeyTag,
-                                       const RawBuffer &hashPriv,
-                                       const RawBuffer &hashPub);
-       void generateDSAKey(uint32_t keySizeBits,
-                                               const RawBuffer &prime,
-                                               const RawBuffer &subprime,
-                                               const RawBuffer &base,
-                                               const RawBuffer &pubPwd,
-                                               const RawBuffer &pubPwdIv,
-                                               const RawBuffer &privPwd,
-                                               const RawBuffer &privPwdIv,
-                                               RawBuffer &pubKeyTag,
-                                               RawBuffer &privKeyTag,
-                                               const RawBuffer &hashPriv,
-                                               const RawBuffer &hashPub);
-       void generateECKey(tz_ec ec,
-                                          const RawBuffer &pubPwd,
-                                          const RawBuffer &pubPwdIv,
-                                          const RawBuffer &privPwd,
-                                          const RawBuffer &privPwdIv,
-                                          RawBuffer &pubKeyTag,
-                                          RawBuffer &privKeyTag,
-                                          const RawBuffer &hashPriv,
-                                          const RawBuffer &hashPub);
-       void generateKEMKey(tz_kem kemType,
-                                               const RawBuffer &pubPwd,
-                                               const RawBuffer &pubPwdIv,
-                                               const RawBuffer &privPwd,
-                                               const RawBuffer &privPwdIv,
-                                               RawBuffer &pubKeyTag,
-                                               RawBuffer &privKeyTag,
-                                               const RawBuffer &hashPriv,
-                                               const RawBuffer &hashPub);
-
-       void importData(uint32_t dataType,
-                                       const RawBuffer &data,
-                                       const Crypto::EncryptionParams &encData,
-                                       const RawBuffer &pwd,
-                                       const RawBuffer &pwdIV,
-                                       const uint32_t keySizeBits,
-                                       RawBuffer &pwdTag,
-                                       const RawBuffer &hash);
-
-       void importWrappedKey(const RawBuffer &wrappingKeyId,
-                                                 const Pwd &wrappingKeyPwd,
-                                                 tz_algo_type algo,
-                                                 tz_hash_type oaepHash,
-                                                 const RawBuffer &iv,
-                                                 const uint32_t ctrLenOrTagSizeBits,
-                                                 const RawBuffer &aad,
-                                                 const tz_data_type encryptedKeyType,
-                                                 const RawBuffer &encryptedKey,
-                                                 const RawBuffer &encryptedKeyPwdBuf,
-                                                 const RawBuffer &encryptedKeyIV,
-                                                 RawBuffer &encryptedKeyTag,
-                                                 const RawBuffer &encryptedKeyHash);
-
-       RawBuffer exportWrappedKey(const RawBuffer &wrappingKeyId,
-                                                          const Pwd &wrappingKeyPwd,
-                                                          tz_algo_type algo,
-                                                          tz_hash_type oaepHash,
-                                                          const RawBuffer &iv,
-                                                          const uint32_t ctrLenOrTagSizeBits,
-                                                          const RawBuffer &aad,
-                                                          const RawBuffer &keyToWrapId,
-                                                          const Pwd &keyToWrapPwd,
-                                                          tz_data_type keyToWrapType);
-
-       RawBuffer wrapConcatenatedData(const RawBuffer &wrappingKeyId,
-                                                                  const Pwd &wrappingKeyPwd,
-                                                                  tz_algo_type algo,
-                                                                  tz_hash_type oaepHash,
-                                                                  const RawBuffer &keyToWrapId,
-                                                                  const Pwd &keyToWrapPwd,
-                                                                  const RawBuffer &userData);
-
-       RawBuffer unwrapConcatenatedData(const RawBuffer &wrappingKeyId,
-                                                                        const Pwd &wrappingKeyPwd,
-                                                                        tz_algo_type algo,
-                                                                        tz_hash_type oaepHash,
-                                                                        const tz_data_type encryptedKeyType,
-                                                                        const RawBuffer &encryptedKey,
-                                                                        const RawBuffer &encryptedKeyPwdBuf,
-                                                                        const RawBuffer &encryptedKeyIV,
-                                                                        RawBuffer &encryptedKeyTag,
-                                                                        const RawBuffer &encryptedKeyId,
-                                                                        size_t keySize);
-
-       RawBuffer encapsulateKey(const RawBuffer &publicKeyId,
-                                                        const Pwd &publicKeyPwd,
-                                                        tz_kem kemType,
-                                                        const RawBuffer &sharedSecretPwdBuf,
-                                                        const RawBuffer &sharedSecretIV,
-                                                        RawBuffer &sharedSecretTag,
-                                                        const RawBuffer &sharedSecretId);
-
-       void decapsulateKey(const RawBuffer &privateKeyId,
-                                               const Pwd &privateKeyPwd,
-                                               tz_kem kemType,
-                                               const RawBuffer &sharedSecretPwdBuf,
-                                               const RawBuffer &sharedSecretIV,
-                                               RawBuffer &sharedSecretTag,
-                                               const RawBuffer &sharedSecretId,
-                                               const RawBuffer &ciphertext);
-
-       void executeCrypt(tz_command cmd,
-                                       tz_algo_type algo,
-                                       tz_hash_type hash,
-                                       const RawBuffer &keyId,
-                                       const Pwd &pwd,
-                                       const RawBuffer &iv,
-                                       const RawBuffer &data,
-                                       RawBuffer &out);
-
-       void executeEncryptAE(const RawBuffer &keyId,
-                                               const Pwd &pwd,
-                                               const RawBuffer &iv,
-                                               int tagSizeBits,
-                                               const RawBuffer &aad,
-                                               const RawBuffer &data,
-                                               RawBuffer &out,
-                                               RawBuffer &tag);
-       void executeDecryptAE(const RawBuffer &keyId,
-                                               const Pwd &pwd,
-                                               const RawBuffer &iv,
-                                               int tagSizeBits,
-                                               const RawBuffer &tag,
-                                               const RawBuffer &aad,
-                                               const RawBuffer &data,
-                                               RawBuffer &out);
-
-       uint32_t initGcmCipher(uint32_t encrypt,
-                                                  const RawBuffer &keyId,
-                                                  const Pwd &pwd,
-                                                  const RawBuffer &iv,
-                                                  int tagSizeBits,
-                                                  const RawBuffer &aad);
-
-       void addGcmAAD(uint32_t opId,
-                                  const RawBuffer &aad);
-
-       RawBuffer updateGcmCipher(uint32_t opId,
-                                                         const RawBuffer &data);
-
-       RawBuffer finalizeGcmCipher(uint32_t opId,
-                                                               const RawBuffer &data);
-
-       void cleanupCipher(uint32_t opId);
-
-       void executeSign(tz_algo_type algo,
-                                       tz_hash_type hash,
-                                       const RawBuffer &keyId,
-                                       const Pwd &pwd,
-                                       const RawBuffer &message,
-                                       RawBuffer &signature);
-       int executeVerify(tz_algo_type algo,
-                                       tz_hash_type hash,
-                                       const RawBuffer &keyId,
-                                       const Pwd &pwd,
-                                       const RawBuffer &message,
-                                       const RawBuffer &signature);
-
-       void executeDestroy(const RawBuffer &keyId);
-
-       void getData(const RawBuffer &dataId,
-                                const Pwd &pwd,
-                                const tz_data_type type,
-                                RawBuffer &data);
-
-       void destroyData(const RawBuffer &dataId);
-
-       void executeEcdh(const RawBuffer &prvKeyId,
-                                        const Pwd &prvKeyPwd,
-                                        const tz_ec curve,
-                                        const RawBuffer &pubX,
-                                        const RawBuffer &pubY,
-                                        const RawBuffer &secretPwdBuf,
-                                        const RawBuffer &secretPwdIV,
-                                        RawBuffer &secretTag,
-                                        const RawBuffer &secretHash);
-
-       void executeKbkdf(const RawBuffer& secretId,
-                                         const Pwd& secretPwd,
-                                         size_t length,
-                                         const RawBuffer& label,
-                                         const RawBuffer& context,
-                                         const RawBuffer& fixed,
-                                         tz_prf prf,
-                                         tz_kbkdf_mode mode,
-                                         tz_kbkdf_ctr_loc location,
-                                         size_t rlen,
-                                         size_t llen,
-                                         bool noSeparator,
-                                         const RawBuffer &keyPwdBuf,
-                                         const RawBuffer &keyPwdIV,
-                                         RawBuffer &keyTag,
-                                         const RawBuffer &keyHash);
-
-       void executeHybridKbkdf(const RawBuffer& firstSecretId,
-                                                       const Pwd& firstSecretPwd,
-                                                       const RawBuffer& secondSecretId,
-                                                       const Pwd& secondSecretPwd,
-                                                       size_t length,
-                                                       const RawBuffer& label,
-                                                       const RawBuffer& context,
-                                                       const RawBuffer& fixed,
-                                                       tz_prf prf,
-                                                       tz_kbkdf_mode mode,
-                                                       tz_kbkdf_ctr_loc location,
-                                                       size_t rlen,
-                                                       size_t llen,
-                                                       bool noSeparator,
-                                                       const RawBuffer &keyPwdBuf,
-                                                       const RawBuffer &keyPwdIV,
-                                                       RawBuffer &keyTag,
-                                                       const RawBuffer &keyHash);
-
-       uint32_t getMaxChunkSize();
-
-private:
-       TrustZoneContext();
-       ~TrustZoneContext();
-       TrustZoneContext(const TrustZoneContext &other) = delete;
-       TrustZoneContext(TrustZoneContext &&other) = delete;
-
-       void Initialize();
-       void Destroy();
-       void Reload();
-
-       void GetDataSize(const RawBuffer &dataId,
-                                        const Pwd &pwd,
-                                        const tz_data_type type,
-                                        uint32_t &dataSize);
-
-       void Execute(tz_command commandID, TEEC_Operation* op);
-
-       void GenerateAKey(tz_command commandID,
-                         TZSerializer &sIn,
-                         uint32_t genParam,
-                         const RawBuffer &pubPwd,
-                         const RawBuffer &pubPwdIv,
-                         const RawBuffer &privPwd,
-                         const RawBuffer &privPwdIv,
-                         RawBuffer &pubKeyTag,
-                         RawBuffer &privKeyTag,
-                         const RawBuffer &hashPriv,
-                                         const RawBuffer &hashPub);
-
-       TEEC_Context m_Context;
-       TEEC_Session m_Session;
-
-       bool m_ContextInitialized;
-       bool m_SessionInitialized;
-};
-
-} // namespace Internals
-} // namespace TZ
-} // namespace Crypto
-} // namespace CKM
diff --git a/src/manager/crypto/tz-backend/tz-memory.cpp b/src/manager/crypto/tz-backend/tz-memory.cpp
deleted file mode 100644 (file)
index 2904e37..0000000
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- *  Copyright (c) 2017-2021 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License
- */
-/*
- * @file       tz-memory.cpp
- * @author     Lukasz Kostyra (l.kostyra@samsung.com)
- * @version    1.0
- * @brief      TrustZone Shared Memory wrapper definitions
- */
-
-#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
-
-#include <tz-backend/tz-memory.h>
-#include <generic-backend/exception.h>
-#include <dpl/log/log.h>
-
-#include <cstring>
-
-namespace CKM {
-namespace Crypto {
-namespace TZ {
-namespace Internals {
-
-TrustZoneMemory::TrustZoneMemory(TEEC_Context &context, const size_t size, const uint32_t flags)
-{
-       Allocate(context, size, flags);
-}
-
-TrustZoneMemory::~TrustZoneMemory()
-{
-       Release();
-}
-
-void TrustZoneMemory::Allocate(TEEC_Context &context, const size_t size, const uint32_t flags)
-{
-       m_SharedMemory.size = size;
-       m_SharedMemory.flags = flags;
-
-       LogDebug("Allocating " << size << " bytes of shared TZ memory, flags: " << flags);
-       if(size != 0) {
-               TEEC_Result result = TEEC_AllocateSharedMemory(&context, &m_SharedMemory);
-               if (result != TEEC_SUCCESS) {
-               ThrowErr(Exc::Crypto::InternalError, "TZ failed to register memory: ",
-                               static_cast<uint32_t>(result));
-               }
-               memset(m_SharedMemory.buffer, 0, m_SharedMemory.size);
-       }
-       else {
-               m_SharedMemory.buffer = NULL;
-               m_SharedMemory.size = 0;
-       }
-
-}
-
-TEEC_SharedMemory* TrustZoneMemory::Get() const
-{
-       return &m_SharedMemory;
-}
-
-void TrustZoneMemory::Release()
-{
-       if(m_SharedMemory.size != 0)
-               TEEC_ReleaseSharedMemory(&m_SharedMemory);
-}
-
-} // namespace Internals
-} // namespace TZ
-} // namespace Crypto
-} // namespace CKM
diff --git a/src/manager/crypto/tz-backend/tz-memory.h b/src/manager/crypto/tz-backend/tz-memory.h
deleted file mode 100644 (file)
index 74e505c..0000000
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- *  Copyright (c) 2017 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License
- */
-/*
- * @file       tz-memory.h
- * @author     Lukasz Kostyra (l.kostyra@samsung.com)
- * @version    1.0
- * @brief      TrustZone Shared Memory wrapper declaration
- */
-
-#pragma once
-
-#include <tee_client_api.h>
-
-namespace CKM {
-namespace Crypto {
-namespace TZ {
-namespace Internals {
-
-class TrustZoneMemory final
-{
-public:
-    TrustZoneMemory(TEEC_Context &context, const size_t size, const uint32_t flags);
-    TrustZoneMemory(const TrustZoneMemory&) = delete;
-    TrustZoneMemory(TrustZoneMemory &&) = delete;
-    TrustZoneMemory& operator=(const TrustZoneMemory&) = delete;
-    TrustZoneMemory& operator=(TrustZoneMemory &&) = delete;
-    ~TrustZoneMemory();
-
-    TEEC_SharedMemory* Get() const;
-
-private:
-    void Allocate(TEEC_Context &context, const size_t size, const uint32_t flags);
-    void Release();
-
-    mutable TEEC_SharedMemory m_SharedMemory;
-};
-
-} // namespace Internals
-} // namespace TZ
-} // namespace Crypto
-} // namespace CKM
diff --git a/src/manager/crypto/tz-backend/tz-serializer.cpp b/src/manager/crypto/tz-backend/tz-serializer.cpp
deleted file mode 100644 (file)
index 764c532..0000000
+++ /dev/null
@@ -1,191 +0,0 @@
-/*
- *  Copyright (c) 2019 Samsung Electronics Co., Ltd. All rights reserved
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License
- */
-/*
- * @file       tz-serializer.cpp
- * @author     Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
- * @version    1.0
- * @brief
- */
-#include "tz-serializer.h"
-
-#include <string.h>
-
-#include <cassert>
-
-#include <generic-backend/crypto-params.h>
-
-namespace CKM {
-namespace Crypto {
-namespace TZ {
-namespace Internals {
-
-// TZSerializable
-void TZSerializable::Pull(RawBuffer &) const
-{
-       ThrowErr(Exc::Crypto::InternalError,
-                "This serializable does not support conversion to RawBuffer");
-}
-
-void TZSerializable::Pull(uint32_t &) const
-{
-       ThrowErr(Exc::Crypto::InternalError,
-                "This serializable does not support conversion to uint32_t");
-}
-
-
-// TZSerializableBinary
-TZSerializableBinary::TZSerializableBinary(uint32_t data_size, bool is_size_fixed)
-{
-       m_data.data = nullptr;
-       m_data.data_size = data_size;
-       m_isSizeFixed = is_size_fixed;
-       m_expectedSize = data_size;
-}
-
-TZSerializableBinary::TZSerializableBinary(const RawBuffer &data)
-{
-       m_data.data = data.empty() ? nullptr : const_cast<unsigned char *>(data.data());
-       m_data.data_size = data.size();
-       m_isSizeFixed = true;
-       m_expectedSize = data.size();
-}
-
-uint32_t TZSerializableBinary::GetSize() const
-{
-       return KM_SizeOfBinaryData(const_cast<KM_BinaryData*>(&m_data));
-}
-
-int TZSerializableBinary::Serialize(void **buffer, uint32_t *size_guard) const
-{
-       return KM_SerializeBinaryData(buffer, size_guard, const_cast<KM_BinaryData*>(&m_data));
-}
-
-int TZSerializableBinary::Deserialize(void **buffer, uint32_t *size_guard)
-{
-       int ret = KM_DeserializeBinaryData(buffer, size_guard, &m_data);
-       if (m_isSizeFixed) {
-               if (m_data.data_size != m_expectedSize) {
-                       ThrowErr(Exc::Crypto::InternalError, "Size of deserialized data differ from size given in constructor.");
-               }
-       } else {
-               if (m_data.data_size > m_expectedSize) {
-                       ThrowErr(Exc::Crypto::InternalError, "Size of deserialized data is bigger than size given in constructor.");
-               }
-       }
-       return ret;
-}
-
-void TZSerializableBinary::Pull(RawBuffer &buffer) const
-{
-       buffer.resize(m_data.data_size);
-       memcpy(buffer.data(), m_data.data, m_data.data_size);
-}
-
-
-// TZSerializablePwdData
-TZSerializablePwdData::TZSerializablePwdData(const RawBuffer &pwd,
-                                             const RawBuffer &iv,
-                                             uint32_t tagSizeBits,
-                                             const RawBuffer &tag)
-{
-       memset(&m_data, 0, sizeof(KM_PwdData));
-       m_data.pwd = pwd.empty() ? nullptr : const_cast<unsigned char *>(pwd.data());
-       m_data.pwd_size = pwd.size();
-       m_data.iv = iv.empty() ? nullptr : const_cast<unsigned char *>(iv.data());
-       m_data.iv_size = iv.size();
-       m_data.tag = tag.empty() ? nullptr : const_cast<unsigned char *>(tag.data());
-       m_data.tag_size = tag.size();
-       m_data.derive_len_bits = Params::DERIVED_KEY_LENGTH_BITS;
-       m_data.it_count = Params::DERIVED_KEY_ITERATIONS;
-       m_data.tag_len_bits = tagSizeBits;
-}
-
-uint32_t TZSerializablePwdData::GetSize() const
-{
-       return KM_SizeOfPwdData(const_cast<KM_PwdData*>(&m_data));
-}
-
-int TZSerializablePwdData::Serialize(void **buffer, uint32_t *size_guard) const
-{
-       return KM_SerializePwdData(buffer, size_guard, const_cast<KM_PwdData*>(&m_data));
-}
-
-int TZSerializablePwdData::Deserialize(void **, uint32_t *)
-{
-       // Key manager should not receive any password data from the TA
-       assert(false);
-       return -1;
-}
-
-// TZSerializableFlag
-uint32_t TZSerializableFlag::GetSize() const
-{
-       return KM_SizeOfFlag();
-}
-
-int TZSerializableFlag::Serialize(void **buffer, uint32_t *size_guard) const
-{
-       return KM_SerializeFlag(buffer, size_guard, m_flag);
-}
-
-int TZSerializableFlag::Deserialize(void **buffer, uint32_t *size_guard)
-{
-       return KM_DeserializeFlag(buffer, size_guard, &m_flag);
-}
-
-void TZSerializableFlag::Pull(uint32_t &flag) const
-{
-       flag = m_flag;
-}
-
-
-// TZSerializer
-void TZSerializer::Push(TZSerializable *serializable)
-{
-       m_serializables.emplace_back(serializable);
-       m_memorySize += serializable->GetSize();
-}
-
-void TZSerializer::Serialize(TrustZoneMemory &memory) const
-{
-       void *inBuffer = memory.Get()->buffer;
-       uint32_t inBufferGuard = m_memorySize;
-
-       for (const auto& s : m_serializables) {
-               int ret = s->Serialize(&inBuffer, &inBufferGuard);
-               if (ret) {
-                       ThrowErr(Exc::Crypto::InternalError, "Failed to serialize data, ret: ", ret);
-               }
-       }
-}
-
-void TZSerializer::Deserialize(const TrustZoneMemory &memory)
-{
-       void *outBuffer = memory.Get()->buffer;
-       uint32_t outBufferGuard = m_memorySize;
-
-       for (const auto& s : m_serializables) {
-               int ret = s->Deserialize(&outBuffer, &outBufferGuard);
-               if (ret) {
-                       ThrowErr(Exc::Crypto::InternalError, "Failed to deserialize data, ret: ", ret);
-               }
-       }
-}
-
-} // namespace Internals
-} // namespace TZ
-} // namespace Crypto
-} // namespace CKM
diff --git a/src/manager/crypto/tz-backend/tz-serializer.h b/src/manager/crypto/tz-backend/tz-serializer.h
deleted file mode 100644 (file)
index 8a1fbb4..0000000
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- *  Copyright (c) 2019-2021 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License
- */
-/*
- * @file       tz-serializer.h
- * @author     Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
- * @version    1.0
- * @brief
- */
-
-#pragma once
-
-#include <cstdint>
-#include <list>
-#include <memory>
-
-#include <km_serialization.h>
-
-#include <tz-backend/tz-memory.h>
-#include <generic-backend/exception.h>
-#include <dpl/raw-buffer.h>
-
-namespace CKM {
-namespace Crypto {
-namespace TZ {
-namespace Internals {
-
-class TZSerializable {
-public:
-       TZSerializable() {}
-       virtual ~TZSerializable() {}
-       TZSerializable(const TZSerializable&) = delete;
-       TZSerializable& operator=(const TZSerializable&) = delete;
-
-       virtual uint32_t GetSize() const = 0;
-       virtual int Serialize(void **buffer, uint32_t *size_guard) const = 0;
-       virtual int Deserialize(void **buffer, uint32_t *size_guard) = 0;
-       virtual void Pull(RawBuffer &buffer) const;
-       virtual void Pull(uint32_t &flag) const;
-};
-
-
-class TZSerializableBinary : public TZSerializable {
-public:
-       explicit TZSerializableBinary(uint32_t data_size, bool is_size_fixed = true);
-       explicit TZSerializableBinary(const RawBuffer &data);
-       uint32_t GetSize() const override;
-       int Serialize(void **buffer, uint32_t *size_guard) const override;
-       int Deserialize(void **buffer, uint32_t *size_guard) override;
-       void Pull(RawBuffer &buffer) const override;
-private:
-       KM_BinaryData m_data;
-       bool m_isSizeFixed;
-       uint32_t m_expectedSize;
-};
-
-
-class TZSerializablePwdData : public TZSerializable {
-public:
-       TZSerializablePwdData(const RawBuffer &pwd,
-                             const RawBuffer &iv,
-                             uint32_t tagSizeBits,
-                             const RawBuffer &tag = RawBuffer());
-       uint32_t GetSize() const override;
-       int Serialize(void **buffer, uint32_t *size_guard) const override;
-       int Deserialize(void **buffer, uint32_t *size_guard) override;
-private:
-       KM_PwdData m_data;
-};
-
-
-class TZSerializableFlag : public TZSerializable {
-public:
-       TZSerializableFlag() : m_flag(0) {}
-       explicit TZSerializableFlag(uint32_t flag) : m_flag(flag) {}
-       uint32_t GetSize() const override;
-       int Serialize(void **buffer, uint32_t *size_guard) const override;
-       int Deserialize(void **buffer, uint32_t *size_guard) override;
-       void Pull(uint32_t &flag) const override;
-private:
-       uint32_t m_flag;
-};
-
-
-class TZSerializer {
-public:
-       TZSerializer() : m_memorySize(0) {}
-       ~TZSerializer() {}
-       TZSerializer(const TZSerializer&) = delete;
-       TZSerializer(TZSerializer&&) = default;
-       TZSerializer& operator=(const TZSerializer&) = delete;
-       TZSerializer& operator=(TZSerializer&&) = default;
-
-       void Push(TZSerializable *serializable);
-
-       template <typename T>
-       void Pull(T &buffer);
-       uint32_t GetSize() const { return m_memorySize; }
-       void Serialize(TrustZoneMemory &memory) const;
-       void Deserialize(const TrustZoneMemory &memory);
-
-private:
-       std::list<std::unique_ptr<TZSerializable>> m_serializables;
-       uint32_t m_memorySize;
-};
-
-template <typename T>
-void TZSerializer::Pull(T &data)
-{
-       if (m_serializables.empty()) {
-               ThrowErr(Exc::Crypto::InternalError, "No more serializables to extract");
-       }
-
-       m_serializables.front()->Pull(data);
-       m_serializables.pop_front();
-}
-
-} // namespace Internals
-} // namespace TZ
-} // namespace Crypto
-} // namespace CKM
index 1ca76cfe7a1737982d882fb3a8f9168db6759afd..ccc8b9877f3bde17277d0a653506b06e9c20bf3f 100644 (file)
@@ -28,6 +28,9 @@
 #include <ckm-service.h>
 #include <ckm-logic.h>
 #include <initial-value-loader.h>
+#ifdef TZ_BACKEND_ENABLED
+#include <hal/hal-security-keys.h>
+#endif
 
 namespace {
 const CKM::InterfaceID SOCKET_ID_CONTROL = 0;
@@ -40,11 +43,18 @@ namespace CKM {
 CKMService::CKMService() :
        m_logic(new CKMLogic)
 {
+#ifdef TZ_BACKEND_ENABLED
+       if (hal_security_keys_get_backend())
+               LogError("Can't get Security Keys backend");
+#endif
        InitialValues::LoadFiles(*m_logic);
 }
 
 CKMService::~CKMService()
 {
+#ifdef TZ_BACKEND_ENABLED
+       hal_security_keys_put_backend();
+#endif
        delete m_logic;
 }
 
index 0fd568038fff4740c939ea0497d56e2d7ce16899..79c3fbc028a3d59ac2b54f6f84a2c59d06df5da6 100644 (file)
@@ -40,7 +40,7 @@ ADD_DEFINITIONS("-Wno-stringop-truncation")
 
 SET(MANAGER_PATH ${PROJECT_SOURCE_DIR}/src/manager)
 
-INCLUDE_DIRECTORIES(SYSTEM ${KEY_MANAGER_DEP_INCLUDE_DIRS})
+INCLUDE_DIRECTORIES(SYSTEM ${KEY_MANAGER_DEP_INCLUDE_DIRS} ${HAL_DEP_INCLUDE_DIRS})
 
 INCLUDE_DIRECTORIES(
     ${MANAGER_PATH}/dpl/db/include
@@ -60,7 +60,7 @@ INCLUDE_DIRECTORIES(
     ${CMAKE_CURRENT_SOURCE_DIR}
 )
 
-LINK_DIRECTORIES(${KEY_MANAGER_DEP_LIBRARY_DIRS})
+LINK_DIRECTORIES(${KEY_MANAGER_DEP_LIBRARY_DIRS} ${HAL_DEP_LIBRARY_DIRS})
 
 SET(UNIT_TESTS_SOURCES
     ${PROJECT_SOURCE_DIR}/common/base64_generic.cpp
@@ -164,8 +164,8 @@ ADD_EXECUTABLE(
 TARGET_LINK_LIBRARIES(
     ${TARGET_UNIT_TESTS}
     ${KEY_MANAGER_DEP_LIBRARIES}
-    ${KM_LINK_EXTRA_DEPS}
     ${CMAKE_THREAD_LIBS_INIT}
+    ${HAL_DEP_LIBRARIES}
     boost_unit_test_framework
     liboqs.a
     -ldl
index 3efc159ffa68eed7a726b3ed15e4e9f4e87ece93..5428e5da937da4d5e5a769f414ebf12cff5a8397 100644 (file)
@@ -33,6 +33,7 @@
 #include <sw-backend/store.h>
 #include <sw-backend/internals.h>
 #ifdef TZ_BACKEND_ENABLED
+#include <hal/hal-security-keys.h>
 #include <tz-backend/store.h>
 #include <tz-backend/internals.h>
 #endif
@@ -349,6 +350,19 @@ NEGATIVE_TEST_CASE(Serialization_32_vs_64_bit_SW)
 }
 
 #ifdef TZ_BACKEND_ENABLED
+struct TzBackendFixture {
+       TzBackendFixture() {
+               if (hal_security_keys_get_backend())
+                       LogError("Can't get Security Keys backend");
+       }
+
+       ~TzBackendFixture() {
+               hal_security_keys_put_backend();
+       }
+};
+
+BOOST_GLOBAL_FIXTURE(TzBackendFixture);
+
 POSITIVE_TEST_CASE(Serialization_32_vs_64_bit_TZ)
 {
        using Crypto::TZ::Store;