mini平台新增接口

Signed-off-by: guoxin <756090608@qq.com>
This commit is contained in:
绫地宁宁 2024-09-05 11:02:00 +08:00
parent 610a8b86d6
commit 51551bbaa9
30 changed files with 1666 additions and 78 deletions

View File

@ -24,6 +24,12 @@ group("crypto_framework_component") {
"frameworks/native:ohcrypto",
"plugin:crypto_openssl_plugin_lib",
]
} else if (os_level == "mini") {
deps = [
"frameworks:crypto_framework_lib",
"frameworks/js/jsi:cryptoframework_jsi",
"plugin:crypto_mbedtls_plugin_lib",
]
}
}

View File

@ -29,7 +29,8 @@
],
"features": [ "crypto_framework_enabled" ],
"adapted_system_type": [
"standard"
"standard",
"mini"
],
"rom": "2048KB",
"ram": "",

View File

@ -14,31 +14,46 @@
import("//base/security/crypto_framework/common/common.gni")
import("//build/ohos.gni")
ohos_static_library("crypto_plugin_common") {
branch_protector_ret = "pac_ret"
subsystem_name = "security"
part_name = "crypto_framework"
include_dirs = crypto_framwork_common_inc_path
if (os_level == "standard") {
ohos_static_library("crypto_plugin_common") {
branch_protector_ret = "pac_ret"
subsystem_name = "security"
part_name = "crypto_framework"
include_dirs = crypto_framwork_common_inc_path
sources = crypto_framwork_common_files
sources = crypto_framwork_common_files
if (os_level == "standard") {
sanitize = {
cfi = true
cfi_cross_dso = true
debug = false
if (os_level == "standard") {
sanitize = {
cfi = true
cfi_cross_dso = true
debug = false
}
}
defines = [ "HILOG_ENABLE" ]
cflags = [
"-DHILOG_ENABLE",
"-fPIC",
"-Wall",
]
external_deps = [
"c_utils:utils",
"hilog:libhilog",
]
}
} else if (os_level == "mini") {
ohos_static_library("crypto_common_lite") {
subsystem_name = "security"
part_name = "crypto_framework"
include_dirs = crypto_framwork_common_inc_path
include_dirs +=
[ "//base/hiviewdfx/hilog_lite/interfaces/native/kits/hilog_lite" ]
defines = [ "HILOG_ENABLE" ]
cflags = [
"-DHILOG_ENABLE",
"-fPIC",
"-Wall",
]
sources = crypto_framwork_common_files_lite
external_deps = [
"c_utils:utils",
"hilog:libhilog",
]
defines = [ "MINI_HILOG_ENABLE" ]
configs = [ "${product_path}:product_public_configs" ]
}
}

View File

@ -30,3 +30,11 @@ framework_common_util_files = [
]
crypto_framwork_common_files = framework_common_util_files
crypto_framwork_common_files_lite = [
"//base/security/crypto_framework/common/src/blob.c",
"//base/security/crypto_framework/common/src/utils.c",
"//base/security/crypto_framework/common/src/log.c",
"//base/security/crypto_framework/common/src/memory.c",
"//base/security/crypto_framework/common/src/object_base.c",
]

View File

@ -19,7 +19,16 @@
#include <stdint.h>
#include <stdlib.h>
#ifdef HILOG_ENABLE
#ifdef MINI_HILOG_ENABLE
#include "hiview_log.h"
#define LOGD(fmt, ...) HILOG_DEBUG(HILOG_MODULE_SCY, fmt, ##__VA_ARGS__)
#define LOGI(fmt, ...) HILOG_INFO(HILOG_MODULE_SCY, fmt, ##__VA_ARGS__)
#define LOGW(fmt, ...) HILOG_WARN(HILOG_MODULE_SCY, fmt, ##__VA_ARGS__)
#define LOGE(fmt, ...) HILOG_ERROR(HILOG_MODULE_SCY, fmt, ##__VA_ARGS__)
#elif HILOG_ENABLE
enum HcfLogLevel {
HCF_LOG_LEVEL_I,

View File

@ -24,37 +24,67 @@ config("framework_config") {
]
}
ohos_shared_library("crypto_framework_lib") {
branch_protector_ret = "pac_ret"
subsystem_name = "security"
innerapi_tags = [ "platformsdk" ]
part_name = "crypto_framework"
public_configs = [ ":framework_config" ]
include_dirs = framework_inc_path + crypto_framwork_common_inc_path
if (os_level == "standard") {
ohos_shared_library("crypto_framework_lib") {
branch_protector_ret = "pac_ret"
subsystem_name = "security"
innerapi_tags = [ "platformsdk" ]
part_name = "crypto_framework"
public_configs = [ ":framework_config" ]
include_dirs = framework_inc_path + crypto_framwork_common_inc_path
sources = framework_files
sources = framework_files
if (os_level == "standard") {
sanitize = {
cfi = true
cfi_cross_dso = true
debug = false
if (os_level == "standard") {
sanitize = {
cfi = true
cfi_cross_dso = true
debug = false
}
}
cflags = [
"-DHILOG_ENABLE",
"-fPIC",
"-Wall",
]
deps = [
"../common:crypto_plugin_common",
"../plugin:crypto_openssl_plugin_lib",
]
external_deps = [
"c_utils:utils",
"hilog:libhilog",
]
}
} else if (os_level == "mini") {
ohos_static_library("crypto_framework_lib") {
subsystem_name = "security"
part_name = "crypto_framework"
public_configs = [ ":framework_config" ]
include_dirs = framework_inc_lite_path + crypto_framwork_common_inc_path
include_dirs +=
[ "//base/hiviewdfx/hilog_lite/interfaces/native/kits/hilog_lite" ]
cflags = [
"-DHILOG_ENABLE",
"-fPIC",
"-Wall",
]
sources = framework_lite_files
deps = [
"../common:crypto_plugin_common",
"../plugin:crypto_openssl_plugin_lib",
]
defines = [
"CRYPTO_MBEDTLS",
"MINI_HILOG_ENABLE",
]
external_deps = [
"c_utils:utils",
"hilog:libhilog",
]
deps = [
"../common:crypto_common_lite",
"../plugin:crypto_mbedtls_plugin_lib",
]
configs = [ "${product_path}:product_public_configs" ]
cflags = [
"--diag_suppress",
"Pe188,Pe186",
]
}
}

View File

@ -19,7 +19,11 @@
#include "sym_key.h"
#include "md_spi.h"
#ifdef CRYPTO_MBEDTLS
#include "mbedtls_md.h"
#else
#include "md_openssl.h"
#endif
#include "log.h"
#include "config.h"
@ -43,6 +47,12 @@ typedef struct {
} HcfMdAbility;
static const HcfMdAbility MD_ABILITY_SET[] = {
#ifdef CRYPTO_MBEDTLS
{ "SHA1", MbedtlsMdSpiCreate },
{ "SHA256", MbedtlsMdSpiCreate },
{ "SHA512", MbedtlsMdSpiCreate },
{ "MD5", MbedtlsMdSpiCreate },
#else
{ "SHA1", OpensslMdSpiCreate },
{ "SHA224", OpensslMdSpiCreate },
{ "SHA256", OpensslMdSpiCreate },
@ -50,6 +60,7 @@ static const HcfMdAbility MD_ABILITY_SET[] = {
{ "SHA512", OpensslMdSpiCreate },
{ "MD5", OpensslMdSpiCreate },
{ "SM3", OpensslMdSpiCreate },
#endif
};
static const char *GetMdClass(void)

View File

@ -18,7 +18,11 @@
#include <limits.h>
#include <securec.h>
#include "rand_spi.h"
#ifdef CRYPTO_MBEDTLS
#include "mbedtls_rand.h"
#else
#include "rand_openssl.h"
#endif
#include "log.h"
#include "config.h"
#include "memory.h"
@ -40,15 +44,19 @@ typedef struct {
HcfRandSpiCreateFunc createSpiFunc;
} HcfRandAbility;
static const HcfRandAbility RAND_ABILITY_SET[] = {
{ "OpensslRand", HcfRandSpiCreate }
};
static const char *GetRandClass(void)
{
return "Rand";
}
static const HcfRandAbility RAND_ABILITY_SET[] = {
#ifdef CRYPTO_MBEDTLS
{ "MbedtlsRand", MbedtlsRandSpiCreate }
#else
{ "OpensslRand", HcfRandSpiCreate }
#endif
};
static HcfRandSpiCreateFunc FindAbility(const char *algoName)
{
for (uint32_t i = 0; i < (sizeof(RAND_ABILITY_SET) / sizeof(RAND_ABILITY_SET[0])); i++) {
@ -127,7 +135,11 @@ HcfResult HcfRandCreate(HcfRand **random)
LOGE("Invalid input params while creating rand!");
return HCF_INVALID_PARAMS;
}
#ifdef CRYPTO_MBEDTLS
HcfRandSpiCreateFunc createSpiFunc = FindAbility("MbedtlsRand");
#else
HcfRandSpiCreateFunc createSpiFunc = FindAbility("OpensslRand");
#endif
if (createSpiFunc == NULL) {
LOGE("Algo not supported!");
return HCF_NOT_SUPPORT;

View File

@ -65,3 +65,17 @@ framework_files =
framework_cipher_files + framework_key_files + framework_mac_files +
framework_rand_files + framework_md_files + framework_kdf_files +
framework_sm2_crypto_util_files
framework_inc_lite_path = [
"${base_path}/interfaces/innerkits/algorithm_parameter",
"${base_path}/interfaces/innerkits/common",
"${base_path}/interfaces/innerkits/crypto_operation",
"${base_path}/interfaces/innerkits/key",
"${base_path}/common/inc",
"${plugin_path}/mbedtls_plugin/common",
"${plugin_path}/mbedtls_plugin/md/inc",
"${plugin_path}/mbedtls_plugin/rand/inc",
"${framework_path}/spi",
]
framework_lite_files = framework_rand_files + framework_md_files

View File

@ -0,0 +1,45 @@
# Copyright (C) 2024 Huawei Device Co., Ltd.
# 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.
import("//base/security/crypto_framework/common/common.gni")
import("//base/security/crypto_framework/frameworks/frameworks.gni")
import("//build/lite/config/component/lite_component.gni")
import("//build/ohos.gni")
ohos_static_library("cryptoframework_jsi") {
subsystem_name = "security"
part_name = "crypto_framework"
include_dirs = [ "inc" ]
include_dirs += framework_inc_path
include_dirs += [
"../../../../../hiviewdfx/hilog_lite/interfaces/native/kits/hilog_lite",
]
sources = [
"src/jsi_api.cpp",
"src/jsi_api_common.cpp",
"src/jsi_api_errcode.cpp",
"src/jsi_list.cpp",
"src/jsi_md.cpp",
"src/jsi_rand.cpp",
"src/jsi_utils.cpp",
]
defines = [ "MINI_HILOG_ENABLE" ]
deps = [
"../../../common:crypto_common_lite",
"../../../frameworks:crypto_framework_lib",
]
configs = [ "${product_path}:product_public_configs" ]
}

View File

@ -0,0 +1,54 @@
/*
* Copyright (C) 2024 Huawei Device Co., Ltd.
* 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.
*/
#ifndef JSI_API_H
#define JSI_API_H
#include "jsi/jsi.h"
#include "jsi/jsi_types.h"
namespace OHOS {
namespace ACELite {
class CryptoFrameworkLiteModule final : public MemoryHeap {
public:
CryptoFrameworkLiteModule() {}
~CryptoFrameworkLiteModule() {};
static JSIValue CreateMd(const JSIValue thisVal, const JSIValue *args, uint8_t argsNum);
static JSIValue CreateRandom(const JSIValue thisVal, const JSIValue *args, uint8_t argsNum);
static void OnDestroy(void);
private:
// Md
static JSIValue Update(const JSIValue thisVal, const JSIValue *args, uint8_t argsNum);
static JSIValue UpdateSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsNum);
static JSIValue Digest(const JSIValue thisVal, const JSIValue *args, uint8_t argsNum);
static JSIValue DigestSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsNum);
static JSIValue GetMdLength(const JSIValue thisVal, const JSIValue *args, uint8_t argsNum);
// Random
static JSIValue GenerateRandom(const JSIValue thisVal, const JSIValue *args, uint8_t argsNum);
static JSIValue GenerateRandomSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsNum);
static JSIValue SetSeed(const JSIValue thisVal, const JSIValue *args, uint8_t argsNum);
static void MdDestroy(void);
static void RandomDestroy(void);
};
void InitCryptoFrameworkModule(JSIValue exports);
} // namespace ACELite
} // namespace OHOS
#endif // JSI_API_H

View File

@ -0,0 +1,43 @@
/*
* Copyright (C) 2024 Huawei Device Co., Ltd.
* 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.
*/
#ifndef JSI_API_COMMON_H
#define JSI_API_COMMON_H
#include "jsi.h"
#include "jsi/jsi_types.h"
#include "md.h"
#include "rand.h"
#include "object_base.h"
namespace OHOS {
namespace ACELite {
typedef enum {
JSI_ALG_MD = 1,
JSI_ALG_RAND = 2,
JSI_ALG_MAX
} LiteAlgType;
#define ARRAY_MAX_SIZE 2
#define ARRAY_INDEX_ZERO 0
#define ARRAY_INDEX_ONE 1
void JsiAsyncCallback(const JSIValue thisVal, JSIValue args, const JSIValue *params, uint8_t paramsNum);
} // namespace ACELite
} // namespace OHOS
#endif // JSI_API_COMMON_H

View File

@ -0,0 +1,30 @@
/*
* Copyright (C) 2024 Huawei Device Co., Ltd.
* 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.
*/
#ifndef JSI_API_ERRCODE_H
#define JSI_API_ERRCODE_H
#include "jsi/jsi.h"
#include "jsi/jsi_types.h"
namespace OHOS {
namespace ACELite {
void CallbackErrorCodeOrDataResult(const JSIValue thisVal, const JSIValue args, int32_t errCode, const JSIValue data);
JSIValue ThrowErrorCodeResult(int32_t errorCode);
} // namespace ACELite
} // namespace OHOS
#endif // JSI_API_ERRCODE_H

View File

@ -0,0 +1,43 @@
/*
* Copyright (C) 2024 Huawei Device Co., Ltd.
* 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.
*/
#ifndef JSI_LIST_H
#define JSI_LIST_H
#include "los_list.h"
#include "jsi_api_common.h"
namespace OHOS {
namespace ACELite {
typedef struct {
LiteAlgType type;
LOS_DL_LIST *objListHeader;
} ListInfo;
typedef struct {
LOS_DL_LIST listNode;
uint32_t objAddr;
} ObjList;
void ListObjInit(LiteAlgType type);
HcfResult ListAddObjNode(LiteAlgType type, uint32_t addAddr);
void ListDeleteObjNode(LiteAlgType type, uint32_t deleteAddr);
void ListDestroy(LiteAlgType type);
} // namespace ACELite
} // namespace OHOS
#endif // JSI_LIST_H

View File

@ -0,0 +1,32 @@
/*
* Copyright (C) 2024 Huawei Device Co., Ltd.
* 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.
*/
#ifndef JSI_UTILS_H
#define JSI_UTILS_H
#include <cstdint>
#include "blob.h"
#include "jsi_api_common.h"
namespace OHOS {
namespace ACELite {
HcfResult ParseUint8ArrayToBlob(JSIValue value, HcfBlob *blob);
JSIValue ConstructJSIReturnResult(const HcfBlob *blob);
} // namespace ACELite
} // namespace OHOS
#endif // JSI_UTILS_H

View File

@ -0,0 +1,39 @@
/*
* Copyright (C) 2024 Huawei Device Co., Ltd.
* 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 "jsi_api.h"
#include "jsi_list.h"
#include "jsi.h"
namespace OHOS {
namespace ACELite {
void InitCryptoFrameworkModule(JSIValue exports)
{
JSI::SetModuleAPI(exports, "createMd", CryptoFrameworkLiteModule::CreateMd);
JSI::SetModuleAPI(exports, "createRandom", CryptoFrameworkLiteModule::CreateRandom);
JSI::SetOnDestroy(exports, CryptoFrameworkLiteModule::OnDestroy);
ListObjInit(JSI_ALG_MD);
ListObjInit(JSI_ALG_RAND);
}
void CryptoFrameworkLiteModule::OnDestroy(void)
{
RandomDestroy();
MdDestroy();
}
} // ACELite
} // OHOS

View File

@ -0,0 +1,31 @@
/*
* Copyright (C) 2024 Huawei Device Co., Ltd.
* 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 "jsi_api_common.h"
#include "jsi_api_errcode.h"
namespace OHOS {
namespace ACELite {
void JsiAsyncCallback(const JSIValue thisVal, const JSIValue args, const JSIValue *params, uint8_t paramsNum)
{
JSIValue para[ARRAY_MAX_SIZE] = { params[ARRAY_INDEX_ZERO], params[ARRAY_INDEX_ONE] };
JSI::CallFunction(args, thisVal, para, paramsNum);
JSI::ReleaseValue(para[ARRAY_INDEX_ZERO]);
JSI::ReleaseValue(para[ARRAY_INDEX_ONE]);
}
} // namespace ACELite
} // namespace OHOS

View File

@ -0,0 +1,88 @@
/*
* Copyright (C) 2024 Huawei Device Co., Ltd.
* 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 "jsi_api_errcode.h"
#include "jsi_api_common.h"
namespace OHOS {
namespace ACELite {
constexpr uint32_t JSI_ERR_CODE_DEFAULT_ERR = 0;
constexpr uint32_t JSI_ERR_CODE_OUT_OF_MEMORY = 17620001;
constexpr uint32_t JSI_ERR_CODE_RUNTIME_ERROR = 17620002;
constexpr uint32_t JSI_ERR_CODE_CRYPTO_OPERATION = 17630001;
typedef struct {
uint32_t errorCode;
const char *errorMsg;
} JsiErrMsg;
static JsiErrMsg g_errMsg[] = {
{ JSI_ERR_CODE_PARAM_CHECK_FAILED, "Parameter error. Possible causes: 1. Mandatory parameters are left unspecified;\
2. Incorrect parameter types; 3. Parameter verification failed." },
{ JSI_ERR_CODE_NOT_SUPPORTED, "Capability not supported. Failed to call the API due to limited device\
capabilities." },
{ JSI_ERR_CODE_OUT_OF_MEMORY, "memory error." },
{ JSI_ERR_CODE_RUNTIME_ERROR, "runtime error." },
{ JSI_ERR_CODE_CRYPTO_OPERATION, "crypto operation error." },
};
static uint32_t GetJsiErrValueByErrCode(HcfResult errCode)
{
switch (errCode) {
case HCF_INVALID_PARAMS:
return JSI_ERR_CODE_PARAM_CHECK_FAILED;
case HCF_NOT_SUPPORT:
return JSI_ERR_CODE_NOT_SUPPORTED;
case HCF_ERR_MALLOC:
return JSI_ERR_CODE_OUT_OF_MEMORY;
case HCF_ERR_NAPI:
return JSI_ERR_CODE_RUNTIME_ERROR;
case HCF_ERR_CRYPTO_OPERATION:
return JSI_ERR_CODE_CRYPTO_OPERATION;
default:
return JSI_ERR_CODE_DEFAULT_ERR;
}
}
JSIValue ThrowErrorCodeResult(int32_t errCode)
{
for (uint32_t index = 0; index < sizeof(g_errMsg) / sizeof(g_errMsg[0]); index++) {
if (g_errMsg[index].errorCode == GetJsiErrValueByErrCode((HcfResult)errCode)) {
return JSI::CreateErrorWithCode(g_errMsg[index].errorCode, g_errMsg[index].errorMsg);
}
}
return JSI::CreateUndefined();
}
void CallbackErrorCodeOrDataResult(const JSIValue thisVal, const JSIValue args, int32_t errCode, const JSIValue data)
{
for (uint32_t index = 0; index < sizeof(g_errMsg) /sizeof(g_errMsg[0]); index++) {
if (g_errMsg[index].errorCode == GetJsiErrValueByErrCode((HcfResult)errCode)) {
JSIValue errObj = JSI::CreateObject();
JSI::SetNumberProperty(errObj, "code", g_errMsg[index].errorCode);
JSI::SetStringProperty(errObj, "message", g_errMsg[index].errorMsg);
JSIValue params[ARRAY_MAX_SIZE] = { errObj, data };
JsiAsyncCallback(thisVal, args, params, ARRAY_MAX_SIZE);
return;
}
}
JSIValue params[ARRAY_MAX_SIZE] = { JSI::CreateUndefined(), data };
JsiAsyncCallback(thisVal, args, params, ARRAY_MAX_SIZE);
}
} // ACELite
} // OHOS

View File

@ -0,0 +1,97 @@
/*
* Copyright (C) 2024 Huawei Device Co., Ltd.
* 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 "jsi_list.h"
#include "memory.h"
static LOS_DL_LIST g_mdObjListHeader = { 0 };
static LOS_DL_LIST g_randObjListHeader = { 0 };
namespace OHOS {
namespace ACELite {
ListInfo g_listMap[] = {
{ JSI_ALG_MD, &g_mdObjListHeader },
{ JSI_ALG_RAND, &g_randObjListHeader }
};
LOS_DL_LIST *GetListHeader(LiteAlgType type)
{
for (uint32_t index = 0; index < sizeof(g_listMap) / sizeof(g_listMap[0]); index++) {
if (type == g_listMap[index].type) {
return g_listMap[index].objListHeader;
}
}
return nullptr;
}
void ListObjInit(LiteAlgType type)
{
LOS_ListInit(GetListHeader(type));
}
HcfResult ListAddObjNode(LiteAlgType type, uint32_t addAddr)
{
ObjList *obj = (ObjList *)HcfMalloc(sizeof(ObjList), 0);
if (obj == nullptr) {
return HCF_ERR_MALLOC;
}
obj->objAddr = addAddr;
if (GetListHeader(type)->pstNext == nullptr) {
LOS_ListInit(GetListHeader(type));
}
LOS_ListAdd(GetListHeader(type), &(obj->listNode));
return HCF_SUCCESS;
}
void ListDeleteObjNode(LiteAlgType type, uint32_t deleteAddr)
{
ObjList *obj = nullptr;
ObjList *objNext = nullptr;
LOS_DL_LIST_FOR_EACH_ENTRY_SAFE(obj, objNext, GetListHeader(type), ObjList, listNode) {
if (obj == nullptr) {
return;
}
if ((obj->objAddr != 0) && (obj->objAddr == deleteAddr)) {
LOS_ListDelete(&(obj->listNode));
HcfObjDestroy((void *)deleteAddr);
obj->objAddr = 0;
HcfFree(obj);
obj = nullptr;
}
}
}
void ListDestroy(LiteAlgType type)
{
ObjList *obj = nullptr;
ObjList *objNext = nullptr;
uint32_t i = 0;
LOS_DL_LIST_FOR_EACH_ENTRY_SAFE(obj, objNext, GetListHeader(type), ObjList, listNode) {
if (obj == nullptr) {
return;
}
LOS_ListDelete(&(obj->listNode));
HcfObjDestroy((void *)(obj->objAddr));
HcfFree(obj);
obj = nullptr;
}
}
} // ACELite
} // OHOS

View File

@ -0,0 +1,200 @@
/*
* Copyright (C) 2024 Huawei Device Co., Ltd.
* 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 "jsi_api.h"
#include "jsi_api_common.h"
#include "jsi_api_errcode.h"
#include "jsi_utils.h"
#include "jsi_list.h"
#include "securec.h"
#include "log.h"
namespace OHOS {
namespace ACELite {
JSIValue CryptoFrameworkLiteModule::CreateMd(const JSIValue thisVal, const JSIValue *args, uint8_t argsNum)
{
if ((args == nullptr) || (argsNum != ARRAY_INDEX_ONE)) {
LOGE("CreateMd args is err!");
return ThrowErrorCodeResult(HCF_INVALID_PARAMS);
}
char *alg = JSI::ValueToString(args[0]);
if (alg == nullptr) {
LOGE("Update alg is null!");
return ThrowErrorCodeResult(HCF_INVALID_PARAMS);
}
HcfMd *mdObj = nullptr;
HcfResult res = HcfMdCreate(reinterpret_cast<const char *>(alg), &mdObj);
if (res != HCF_SUCCESS) {
LOGE("CreateMd is mdObj err res %d!", res);
return ThrowErrorCodeResult(res);
}
res = ListAddObjNode(JSI_ALG_MD, (uint32_t)mdObj);
if (res != HCF_SUCCESS) {
LOGE("md add node is %d err!", res);
HcfObjDestroy((void *)mdObj);
return ThrowErrorCodeResult(res);
}
JSIValue serviceObj = JSI::CreateObject();
JSIValue update = JSI::CreateFunction(Update);
JSIValue updateSync = JSI::CreateFunction(UpdateSync);
JSIValue digest = JSI::CreateFunction(Digest);
JSIValue digestSync = JSI::CreateFunction(DigestSync);
JSIValue getMdLength = JSI::CreateFunction(GetMdLength);
JSI::SetNamedProperty(serviceObj, "update", update);
JSI::SetNamedProperty(serviceObj, "updateSync", updateSync);
JSI::SetNamedProperty(serviceObj, "digest", digest);
JSI::SetNamedProperty(serviceObj, "digestSync", digestSync);
JSI::SetNamedProperty(serviceObj, "getMdLength", getMdLength);
JSI::SetNumberProperty(serviceObj, "mdObj", (double)(uint32_t)mdObj);
JSI::ReleaseValueList(update, updateSync, digest, digestSync, getMdLength, ARGS_END);
return serviceObj;
}
JSIValue CryptoFrameworkLiteModule::Update(const JSIValue thisVal, const JSIValue *args, uint8_t argsNum)
{
if ((args == nullptr) || (argsNum != ARRAY_MAX_SIZE)) {
LOGE("Update args is null!");
CallbackErrorCodeOrDataResult(thisVal, args[ARRAY_INDEX_ONE], HCF_INVALID_PARAMS, JSI::CreateNull());
return JSI::CreateUndefined();
}
HcfMd *mdObj = (HcfMd *)(uint32_t)JSI::GetNumberProperty(thisVal, "mdObj");
if (mdObj == nullptr) {
LOGE("Update mdObj is null!!");
CallbackErrorCodeOrDataResult(thisVal, args[ARRAY_INDEX_ONE], HCF_INVALID_PARAMS, JSI::CreateNull());
return JSI::CreateUndefined();
}
JSIValue inVlaue = JSI::GetNamedProperty(args[ARRAY_INDEX_ZERO], "data");
HcfBlob inBlob = { .data = nullptr, .len = 0 };
HcfResult errCode = ParseUint8ArrayToBlob(inVlaue, &inBlob);
if (errCode != HCF_SUCCESS) {
LOGE("Update inBlob is null!");
CallbackErrorCodeOrDataResult(thisVal, args[ARRAY_INDEX_ONE], HCF_INVALID_PARAMS, JSI::CreateNull());
return JSI::CreateUndefined();
}
errCode = mdObj->update(mdObj, &inBlob);
HcfBlobDataClearAndFree(&inBlob);
if (errCode != HCF_SUCCESS) {
LOGE("Update errCode not is success!");
CallbackErrorCodeOrDataResult(thisVal, args[ARRAY_INDEX_ONE], errCode, JSI::CreateNull());
return JSI::CreateUndefined();
}
CallbackErrorCodeOrDataResult(thisVal, args[ARRAY_INDEX_ONE], HCF_SUCCESS, JSI::CreateNull());
return JSI::CreateUndefined();
}
JSIValue CryptoFrameworkLiteModule::UpdateSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsNum)
{
if ((args == nullptr) || (argsNum != ARRAY_INDEX_ONE)) {
LOGE("UpdateSync args is null!");
return ThrowErrorCodeResult(HCF_INVALID_PARAMS);
}
HcfMd *mdObj = (HcfMd *)(uint32_t)JSI::GetNumberProperty(thisVal, "mdObj");
if (mdObj == nullptr) {
LOGE("UpdateSync mdObj is null!!");
return ThrowErrorCodeResult(HCF_INVALID_PARAMS);
}
JSIValue inVlaue = JSI::GetNamedProperty(args[ARRAY_INDEX_ZERO], "data");
HcfBlob inBlob = { .data = nullptr, .len = 0 };
HcfResult errCode = ParseUint8ArrayToBlob(inVlaue, &inBlob);
if (errCode != HCF_SUCCESS) {
LOGE("UpdateSync inBlob is null!");
CallbackErrorCodeOrDataResult(thisVal, args[ARRAY_INDEX_ONE], HCF_INVALID_PARAMS, JSI::CreateNull());
return JSI::CreateUndefined();
}
errCode = mdObj->update(mdObj, &inBlob);
HcfBlobDataClearAndFree(&inBlob);
if (errCode != HCF_SUCCESS) {
LOGE("UpdateSync update ret is error!");
}
return ThrowErrorCodeResult(errCode);
}
JSIValue CryptoFrameworkLiteModule::Digest(const JSIValue thisVal, const JSIValue *args, uint8_t argsNum)
{
if ((args == nullptr) || (argsNum != ARRAY_INDEX_ONE)) {
LOGE("Digest args is err or mdObj nullptr!");
CallbackErrorCodeOrDataResult(thisVal, args[ARRAY_INDEX_ONE], HCF_INVALID_PARAMS, JSI::CreateUndefined());
return JSI::CreateUndefined();
}
HcfMd *mdObj = (HcfMd *)(uint32_t)JSI::GetNumberProperty(thisVal, "mdObj");
if (mdObj == nullptr) {
LOGE("Digest mdObj is null!!");
CallbackErrorCodeOrDataResult(thisVal, args[ARRAY_INDEX_ONE], HCF_INVALID_PARAMS, JSI::CreateUndefined());
return JSI::CreateUndefined();
}
HcfBlob outBlob = { .data = nullptr, .len = 0 };
HcfResult errCode = mdObj->doFinal(mdObj, &outBlob);
if (errCode != HCF_SUCCESS) {
LOGE("Digest errCode not is success!");
HcfBlobDataClearAndFree(&outBlob);
CallbackErrorCodeOrDataResult(thisVal, args[ARRAY_INDEX_ONE], errCode, JSI::CreateUndefined());
return JSI::CreateUndefined();
}
JSIValue outVlaue = ConstructJSIReturnResult(&outBlob);
CallbackErrorCodeOrDataResult(thisVal, args[0], errCode, outVlaue);
HcfBlobDataClearAndFree(&outBlob);
return JSI::CreateUndefined();
}
JSIValue CryptoFrameworkLiteModule::DigestSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsNum)
{
HcfMd *mdObj = (HcfMd *)(uint32_t)JSI::GetNumberProperty(thisVal, "mdObj");
if (mdObj == nullptr) {
LOGE("DigestSync mdObj is null!!");
return ThrowErrorCodeResult(HCF_INVALID_PARAMS);
}
HcfBlob outBlob = { .data = nullptr, .len = 0 };
HcfResult errCode = mdObj->doFinal(mdObj, &outBlob);
if (errCode != HCF_SUCCESS) {
LOGE("DigestSync errCode not is success!");
HcfBlobDataClearAndFree(&outBlob);
return ThrowErrorCodeResult(errCode);
}
JSIValue mdSyncData = ConstructJSIReturnResult(&outBlob);
HcfBlobDataClearAndFree(&outBlob);
return mdSyncData;
}
JSIValue CryptoFrameworkLiteModule::GetMdLength(const JSIValue thisVal, const JSIValue *args, uint8_t argsNum)
{
HcfMd *mdObj = (HcfMd *)(uint32_t)JSI::GetNumberProperty(thisVal, "mdObj");
if (mdObj == nullptr) {
LOGE("GetMdLength mdObj is null!");
return ThrowErrorCodeResult(HCF_INVALID_PARAMS);
}
return JSI::CreateNumber(mdObj->getMdLength(mdObj));
}
void CryptoFrameworkLiteModule::MdDestroy(void)
{
ListDestroy(JSI_ALG_MD);
}
} // namespace ACELite
} // namespace OHOS

View File

@ -0,0 +1,160 @@
/*
* Copyright (C) 2024 Huawei Device Co., Ltd.
* 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 "jsi_api.h"
#include "jsi_api_common.h"
#include "jsi_api_errcode.h"
#include "jsi_utils.h"
#include "jsi_list.h"
#include "securec.h"
#include "jsi.h"
#include "jsi_types.h"
#include "log.h"
namespace OHOS {
namespace ACELite {
JSIValue CryptoFrameworkLiteModule::CreateRandom(const JSIValue thisVal, const JSIValue *args, uint8_t argsNum)
{
HcfRand *randObj = nullptr;
HcfResult res = HcfRandCreate(&randObj);
if (res != HCF_SUCCESS) {
LOGE("CreateRandom is randObj err %d!", res);
return ThrowErrorCodeResult(res);
}
res = ListAddObjNode(JSI_ALG_RAND, (uint32_t)randObj);
if (res != HCF_SUCCESS) {
LOGE("rand add node is %d err!", res);
HcfObjDestroy((void *)randObj);
return ThrowErrorCodeResult(res);
}
JSIValue serviceObj = JSI::CreateObject();
JSIValue generateRandom = JSI::CreateFunction(GenerateRandom);
JSIValue generateRandomSync = JSI::CreateFunction(GenerateRandomSync);
JSIValue setSeed = JSI::CreateFunction(SetSeed);
JSI::SetNamedProperty(serviceObj, "generateRandom", generateRandom);
JSI::SetNamedProperty(serviceObj, "generateRandomSync", generateRandomSync);
JSI::SetNamedProperty(serviceObj, "setSeed", setSeed);
JSI::SetNumberProperty(serviceObj, "randObj", (double)(uint32_t)randObj);
JSI::ReleaseValueList(generateRandom, generateRandomSync, setSeed, ARGS_END);
return serviceObj;
}
JSIValue CryptoFrameworkLiteModule::GenerateRandom(const JSIValue thisVal, const JSIValue *args, uint8_t argsNum)
{
HcfRand *randObj = (HcfRand *)(uint32_t)JSI::GetNumberProperty(thisVal, "randObj");
if (randObj == nullptr) {
LOGE("GenerateRandom randObj is null!");
CallbackErrorCodeOrDataResult(thisVal, args[ARRAY_INDEX_ONE], HCF_INVALID_PARAMS, JSI::CreateUndefined());
return JSI::CreateUndefined();
}
if ((args == nullptr) || (argsNum != ARRAY_MAX_SIZE) || (args[ARRAY_INDEX_ONE] == nullptr)) {
LOGE("GenerateRandom params is err!");
CallbackErrorCodeOrDataResult(thisVal, args[ARRAY_INDEX_ONE], HCF_INVALID_PARAMS, JSI::CreateUndefined());
return JSI::CreateUndefined();
}
int32_t numBytes = (int32_t)JSI::ValueToNumber(args[0]);
if (numBytes <= 0) {
LOGE("GenerateRandom numBytes too small!");
CallbackErrorCodeOrDataResult(thisVal, args[ARRAY_INDEX_ONE], HCF_INVALID_PARAMS, JSI::CreateUndefined());
return JSI::CreateUndefined();
}
HcfBlob randBlob = { .data = nullptr, .len = 0 };
HcfResult res = randObj->generateRandom(randObj, numBytes, &randBlob);
if (res != HCF_SUCCESS) {
LOGE("GenerateRandom randObj not is success!");
CallbackErrorCodeOrDataResult(thisVal, args[ARRAY_INDEX_ONE], res, JSI::CreateUndefined());
return JSI::CreateUndefined();
}
JSIValue outVlaue = ConstructJSIReturnResult(&randBlob);
CallbackErrorCodeOrDataResult(thisVal, args[ARRAY_INDEX_ONE], res, outVlaue);
HcfBlobDataClearAndFree(&randBlob);
return JSI::CreateUndefined();
}
JSIValue CryptoFrameworkLiteModule::GenerateRandomSync(const JSIValue thisVal, const JSIValue *args, uint8_t argsNum)
{
HcfRand *randObj = (HcfRand *)(uint32_t)JSI::GetNumberProperty(thisVal, "randObj");
if (randObj == nullptr) {
LOGE("GenerateRandom randObj is null!!");
return ThrowErrorCodeResult(HCF_INVALID_PARAMS);
}
if ((args == nullptr) || (argsNum != ARRAY_INDEX_ONE)) {
LOGE("GenerateRandomSync params is err");
return ThrowErrorCodeResult(HCF_INVALID_PARAMS);
}
int32_t numBytes = (int32_t)JSI::ValueToNumber(args[0]);
if (numBytes <= 0) {
LOGE("GenerateRandomSync numBytes too small!");
return ThrowErrorCodeResult(HCF_INVALID_PARAMS);
}
HcfBlob randBlob = { .data = nullptr, .len = 0 };
HcfResult res = randObj->generateRandom(randObj, numBytes, &randBlob);
if (res != HCF_SUCCESS) {
LOGE("GenerateRandomSync randObj not is success!");
HcfBlobDataClearAndFree(&randBlob);
return ThrowErrorCodeResult(res);
}
JSIValue randomSyncData = ConstructJSIReturnResult(&randBlob);
HcfBlobDataClearAndFree(&randBlob);
return randomSyncData;
}
JSIValue CryptoFrameworkLiteModule::SetSeed(const JSIValue thisVal, const JSIValue *args, uint8_t argsNum)
{
HcfRand *randObj = (HcfRand *)(uint32_t)JSI::GetNumberProperty(thisVal, "randObj");
if (randObj == nullptr) {
LOGE("SetSeed randObj is null!!");
return ThrowErrorCodeResult(HCF_INVALID_PARAMS);
}
if ((args == nullptr) || (argsNum != ARRAY_INDEX_ONE)) {
LOGE("SetSeed params is null");
return ThrowErrorCodeResult(HCF_INVALID_PARAMS);
}
JSIValue inVlaue = JSI::GetNamedProperty(args[ARRAY_INDEX_ZERO], "data");
HcfBlob seedBlob = { .data = nullptr, .len = 0 };
HcfResult errCode = ParseUint8ArrayToBlob(inVlaue, &seedBlob);
if (errCode != HCF_SUCCESS) {
LOGE("SetSeed seedBlob is null!");
return ThrowErrorCodeResult(HCF_ERR_MALLOC);
}
HcfResult res = randObj->setSeed(randObj, &seedBlob);
HcfBlobDataClearAndFree(&seedBlob);
if (res != HCF_SUCCESS) {
LOGE("setSeed randObj not is success!");
return ThrowErrorCodeResult(res);
}
return ThrowErrorCodeResult(HCF_SUCCESS);
}
void CryptoFrameworkLiteModule::RandomDestroy(void)
{
ListDestroy(JSI_ALG_RAND);
}
} // namespace ACELite
} // namespace OHOS

View File

@ -0,0 +1,91 @@
/*
* Copyright (C) 2024 Huawei Device Co., Ltd.
* 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 "jsi_utils.h"
#include "jsi.h"
#include "jsi_types.h"
#include "memory.h"
#include "securec.h"
#include "utils.h"
#include "log.h"
namespace OHOS {
namespace ACELite {
HcfResult ParseUint8ArrayToBlob(JSIValue value, HcfBlob *blob)
{
if (!JSI::ValueIsTypedArray(value) || (blob == nullptr)) {
LOGE("value is not a typed array!");
return HCF_INVALID_PARAMS;
}
TypedArrayType arrayType;
size_t arraySize = 0;
size_t byteOffset = 0;
JSIValue arrayBuffer = nullptr;
uint8_t *dataArray;
HcfResult ret = HCF_SUCCESS;
do {
dataArray = JSI::GetTypedArrayInfo(value, arrayType, arraySize, arrayBuffer, byteOffset);
if (dataArray == nullptr) {
ret = HCF_ERR_CRYPTO_OPERATION;
break;
}
if (arrayType != TypedArrayType::JSI_UINT8_ARRAY) {
LOGE("value is not a uint8 array");
ret = HCF_INVALID_PARAMS;
break;
}
blob->data = (uint8_t *)HcfMalloc(arraySize, 0);
if (blob->data == nullptr) {
ret = HCF_ERR_MALLOC;
break;
}
memcpy_s(blob->data, arraySize, dataArray + byteOffset, arraySize);
blob->len = arraySize;
} while (0);
if (arrayBuffer != nullptr) {
JSI::ReleaseValue(arrayBuffer);
arrayBuffer = nullptr;
}
return ret;
}
JSIValue ConstructJSIReturnResult(const HcfBlob *blob)
{
JSIValue res;
do {
res = JSI::CreateObject();
if (res == nullptr) {
break;
}
if (blob->data != nullptr) {
uint8_t *arrayBuffer = nullptr;
JSIValue buffer = JSI::CreateArrayBuffer(blob->len, arrayBuffer);
if (arrayBuffer == nullptr) {
LOGE("create jsi array buffer failed");
JSI::ReleaseValue(buffer);
return res;
}
(void)memcpy_s(arrayBuffer, blob->len, blob->data, blob->len);
JSIValue typedArray = JSI::CreateTypedArray(TypedArrayType::JSI_UINT8_ARRAY, blob->len, buffer, 0);
JSI::ReleaseValue(buffer);
JSI::SetNamedProperty(res, "data", typedArray);
}
} while (0);
return res;
}
} // namespace ACELite
} // namespace OHOS

View File

@ -22,6 +22,7 @@
#include "object_base.h"
#define OPENSSL_RAND_ALGORITHM "CTR_DRBG"
#define MBEDTLS_RAND_ALGORITHM "CTR_DRBG_MBEDTLS"
typedef struct HcfRandSpi HcfRandSpi;

View File

@ -25,36 +25,55 @@ config("plugin_config") {
]
}
ohos_shared_library("crypto_openssl_plugin_lib") {
branch_protector_ret = "pac_ret"
subsystem_name = "security"
innerapi_tags = [ "platformsdk_indirect" ]
part_name = "crypto_framework"
public_configs = [ ":plugin_config" ]
include_dirs = plugin_inc_path + crypto_framwork_common_inc_path
if (os_level == "standard") {
ohos_shared_library("crypto_openssl_plugin_lib") {
branch_protector_ret = "pac_ret"
subsystem_name = "security"
innerapi_tags = [ "platformsdk_indirect" ]
part_name = "crypto_framework"
public_configs = [ ":plugin_config" ]
include_dirs = plugin_inc_path + crypto_framwork_common_inc_path
sources = plugin_files
sources = plugin_files
if (os_level == "standard") {
sanitize = {
cfi = true
cfi_cross_dso = true
debug = false
if (os_level == "standard") {
sanitize = {
cfi = true
cfi_cross_dso = true
debug = false
}
}
cflags = [
"-DHILOG_ENABLE",
"-fPIC",
"-Wall",
]
deps = [ "//base/security/crypto_framework/common:crypto_plugin_common" ]
external_deps = [
"c_utils:utils",
"hilog:libhilog",
"openssl:libcrypto_shared",
]
defines = [ "OPENSSL_SUPPRESS_DEPRECATED" ]
}
} else if (os_level == "mini") {
ohos_static_library("crypto_mbedtls_plugin_lib") {
subsystem_name = "security"
part_name = "crypto_framework"
public_configs = [ ":plugin_config" ]
include_dirs = crypto_framwork_common_inc_path + mbedtls_plugin_inc_path
include_dirs +=
[ "//base/hiviewdfx/hilog_lite/interfaces/native/kits/hilog_lite" ]
cflags = [
"-DHILOG_ENABLE",
"-fPIC",
"-Wall",
]
sources = mbedtls_plugin_files
deps = [ "//base/security/crypto_framework/common:crypto_plugin_common" ]
defines = [ "MINI_HILOG_ENABLE" ]
external_deps = [
"c_utils:utils",
"hilog:libhilog",
"openssl:libcrypto_shared",
]
defines = [ "OPENSSL_SUPPRESS_DEPRECATED" ]
deps = [ "//base/security/crypto_framework/common:crypto_common_lite" ]
configs = [ "${product_path}:product_public_configs" ]
}
}

View File

@ -0,0 +1,30 @@
/*
* Copyright (C) 2024 Huawei Device Co., Ltd.
* 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.
*/
#ifndef MBEDTLS_COMMON_H
#define MBEDTLS_COMMON_H
#include <stdint.h>
#include <stdbool.h>
#include "result.h"
#include "utils.h"
#define HCF_MBEDTLS_SUCCESS 0
#define HCF_MBEDTLS_FAILURE (-1)
#define HCF_BITS_PER_BYTE 8
#define HCF_EVP_MAX_MD_SIZE 64
#endif

View File

@ -0,0 +1,31 @@
/*
* Copyright (C) 2024 Huawei Device Co., Ltd.
* 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.
*/
#ifndef HCF_MBEDTLS_MD_H
#define HCF_MBEDTLS_MD_H
#include "md_spi.h"
#define HCF_MBEDTLS_INVALID_MD_LEN 0
#ifdef __cplusplus
extern "C" {
#endif
HcfResult MbedtlsMdSpiCreate(const char *mbedtlsAlgoName, HcfMdSpi **spiObj);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,197 @@
/*
* Copyright (C) 2024 Huawei Device Co., Ltd.
* 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 "mbedtls_md.h"
#include "mbedtls_common.h"
#include "mbedtls/md.h"
#include "securec.h"
#include "log.h"
#include "memory.h"
#include "config.h"
#include "utils.h"
typedef struct {
HcfMdSpi base;
mbedtls_md_context_t *ctx;
char mbedtlsAlgoName[HCF_MAX_ALGO_NAME_LEN];
} MbedtlsMdSpiImpl;
mbedtls_md_context_t *MbedtlsEvpMdCtxNew(void)
{
return (mbedtls_md_context_t *)HcfMalloc(sizeof(mbedtls_md_context_t), 0);
}
void MbedtlsEvpMdCtxFree(mbedtls_md_context_t *ctx)
{
HcfFree(ctx);
}
static const char *MbedtlsGetMdClass(void)
{
return "MbedtlsMd";
}
static mbedtls_md_context_t *MbedtlsGetMdCtx(HcfMdSpi *self)
{
if (!HcfIsClassMatch((HcfObjectBase *)self, MbedtlsGetMdClass())) {
LOGE("Class is not match.");
return NULL;
}
return ((MbedtlsMdSpiImpl *)self)->ctx;
}
static HcfResult MbedtlsEngineUpdateMd(HcfMdSpi *self, HcfBlob *input)
{
mbedtls_md_context_t *ctx = MbedtlsGetMdCtx(self);
if (ctx == NULL) {
LOGD("The CTX is NULL!");
return HCF_INVALID_PARAMS;
}
int32_t ret = mbedtls_md_update(ctx, (const unsigned char *)input->data, input->len);
if (ret != HCF_MBEDTLS_SUCCESS) {
LOGD("EVP_DigestUpdate return error %d!", ret);
return HCF_ERR_CRYPTO_OPERATION;
}
return HCF_SUCCESS;
}
static HcfResult MbedtlsEngineDoFinalMd(HcfMdSpi *self, HcfBlob *output)
{
if ((self == NULL) || (output == NULL)) {
LOGE("The input self ptr is NULL!");
return HCF_INVALID_PARAMS;
}
mbedtls_md_context_t *ctx = MbedtlsGetMdCtx(self);
if (ctx == NULL) {
LOGE("The CTX is NULL!");
return HCF_INVALID_PARAMS;
}
unsigned char outputBuf[HCF_EVP_MAX_MD_SIZE] = { 0 };
uint8_t outputLen = mbedtls_md_get_size(mbedtls_md_info_from_ctx(ctx));
if (outputLen == 0) {
LOGD("Failed to md get size is 0!");
return HCF_ERR_CRYPTO_OPERATION;
}
int32_t ret = mbedtls_md_finish(ctx, outputBuf);
if (ret != HCF_MBEDTLS_SUCCESS) {
LOGD("Failed to md finish return error is %d!", ret);
return HCF_ERR_CRYPTO_OPERATION;
}
output->data = (uint8_t *)HcfMalloc(outputLen, 0);
if (output->data == NULL) {
LOGE("Failed to allocate output->data memory!");
return HCF_ERR_MALLOC;
}
(void)memcpy_s(output->data, outputLen, outputBuf, outputLen);
output->len = outputLen;
return HCF_SUCCESS;
}
static uint32_t MbedtlsEngineGetMdLength(HcfMdSpi *self)
{
mbedtls_md_context_t *ctx = MbedtlsGetMdCtx(self);
if (ctx == NULL) {
LOGD("The CTX is NULL!");
return HCF_MBEDTLS_INVALID_MD_LEN;
}
uint8_t outputLen = mbedtls_md_get_size(mbedtls_md_info_from_ctx(ctx));
if ((outputLen == 0) || (outputLen > HCF_EVP_MAX_MD_SIZE)) {
LOGD("Get the overflow path length is %d in mbedtls!", outputLen);
return HCF_MBEDTLS_INVALID_MD_LEN;
}
return outputLen;
}
static void MbedtlsDestroyMd(HcfObjectBase *self)
{
if (self == NULL) {
LOGE("The input self ptr is NULL!");
return;
}
if (!HcfIsClassMatch(self, MbedtlsGetMdClass())) {
LOGE("Class is not match.");
return;
}
if (MbedtlsGetMdCtx((HcfMdSpi *)self) != NULL) {
mbedtls_md_free(MbedtlsGetMdCtx((HcfMdSpi *)self));
MbedtlsEvpMdCtxFree(MbedtlsGetMdCtx((HcfMdSpi *)self));
}
HcfFree(self);
}
typedef struct {
char *mdAlg;
mbedtls_md_type_t mdType;
} MdAlgTypeMap;
static MdAlgTypeMap g_mdAlgMap[] = {
{ "MD5", MBEDTLS_MD_MD5 },
{ "SHA1", MBEDTLS_MD_SHA1 },
{ "SHA256", MBEDTLS_MD_SHA256 },
{ "SHA512", MBEDTLS_MD_SHA512 },
};
int MbedtlsEvpDigestInitEx(mbedtls_md_context_t *ctx, const char *mbedtlsAlgoName)
{
for (uint32_t index = 0; index < sizeof(g_mdAlgMap) / sizeof(g_mdAlgMap[0]); index++) {
if (strcmp(g_mdAlgMap[index].mdAlg, mbedtlsAlgoName) == 0) {
mbedtls_md_init(ctx);
mbedtls_md_setup(ctx, mbedtls_md_info_from_type(g_mdAlgMap[index].mdType), 0);
mbedtls_md_starts(ctx);
return HCF_MBEDTLS_SUCCESS;
}
}
return HCF_MBEDTLS_FAILURE;
}
HcfResult MbedtlsMdSpiCreate(const char *mbedtlsAlgoName, HcfMdSpi **spiObj)
{
if (spiObj == NULL) {
LOGE("Invalid input parameter.");
return HCF_INVALID_PARAMS;
}
MbedtlsMdSpiImpl *returnSpiImpl = (MbedtlsMdSpiImpl *)HcfMalloc(sizeof(MbedtlsMdSpiImpl), 0);
if (returnSpiImpl == NULL) {
LOGE("Failed to allocate returnImpl memory!");
return HCF_ERR_MALLOC;
}
returnSpiImpl->ctx = MbedtlsEvpMdCtxNew();
if (returnSpiImpl->ctx == NULL) {
LOGE("Failed to create ctx!");
HcfFree(returnSpiImpl);
return HCF_ERR_MALLOC;
}
int32_t ret = MbedtlsEvpDigestInitEx(returnSpiImpl->ctx, mbedtlsAlgoName);
if (ret != HCF_MBEDTLS_SUCCESS) {
LOGD("Failed to init MD ret is %d!", ret);
MbedtlsEvpMdCtxFree(returnSpiImpl->ctx);
HcfFree(returnSpiImpl);
return HCF_ERR_CRYPTO_OPERATION;
}
returnSpiImpl->base.base.getClass = MbedtlsGetMdClass;
returnSpiImpl->base.base.destroy = MbedtlsDestroyMd;
returnSpiImpl->base.engineUpdateMd = MbedtlsEngineUpdateMd;
returnSpiImpl->base.engineDoFinalMd = MbedtlsEngineDoFinalMd;
returnSpiImpl->base.engineGetMdLength = MbedtlsEngineGetMdLength;
*spiObj = (HcfMdSpi *)returnSpiImpl;
return HCF_SUCCESS;
}

View File

@ -0,0 +1,29 @@
/*
* Copyright (C) 2024 Huawei Device Co., Ltd.
* 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.
*/
#ifndef HCF_MBEDTLS_RAND_H
#define HCF_MBEDTLS_RAND_H
#include "rand_spi.h"
#ifdef __cplusplus
extern "C" {
#endif
HcfResult MbedtlsRandSpiCreate(HcfRandSpi **spiObj);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,208 @@
/*
* Copyright (C) 2024 Huawei Device Co., Ltd.
* 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 "mbedtls_rand.h"
#include "mbedtls/entropy.h"
#include "mbedtls/ctr_drbg.h"
#include "securec.h"
#include "log.h"
#include "memory.h"
#include "utils.h"
typedef struct {
HcfRandSpi base;
mbedtls_entropy_context *entropy;
mbedtls_ctr_drbg_context *ctrDrbg;
} HcfRandSpiImpl;
static const char *GetMbedtlsRandClass(void)
{
return "RandMbedtls";
}
static mbedtls_entropy_context *MbedtlsGetMdEntropy(HcfRandSpi *self)
{
if (!HcfIsClassMatch((HcfObjectBase *)self, GetMbedtlsRandClass())) {
LOGE("Class is not match.");
return NULL;
}
return ((HcfRandSpiImpl *)self)->entropy;
}
static mbedtls_ctr_drbg_context *MbedtlsGetMdCtrDrbg(HcfRandSpi *self)
{
if (!HcfIsClassMatch((HcfObjectBase *)self, GetMbedtlsRandClass())) {
LOGE("Class is not match.");
return NULL;
}
return ((HcfRandSpiImpl *)self)->ctrDrbg;
}
static HcfResult MbedtlsGenerateRandom(HcfRandSpi *self, int32_t numBytes, HcfBlob *random)
{
if ((self == NULL) || (random == NULL)) {
LOGE("Invalid params!");
return HCF_INVALID_PARAMS;
}
if (numBytes <= 0) {
LOGE("Invalid numBytes!");
return HCF_INVALID_PARAMS;
}
mbedtls_ctr_drbg_context *ctrDrbg = MbedtlsGetMdCtrDrbg(self);
if (ctrDrbg == NULL) {
LOGE("Invalid ctrDrbg null!");
return HCF_INVALID_PARAMS;
}
random->data = (uint8_t *)HcfMalloc(numBytes, 0);
if (random->data == NULL) {
LOGE("Failed to allocate random->data memory!");
return HCF_ERR_MALLOC;
}
int32_t ret = mbedtls_ctr_drbg_random(ctrDrbg, random->data, numBytes);
if (ret != 0) {
LOGE("RAND_bytes return is %d error!", ret);
HcfFree(random->data);
random->data = NULL;
return HCF_ERR_CRYPTO_OPERATION;
}
random->len = numBytes;
return HCF_SUCCESS;
}
static const char *MbedtlsGetRandAlgoName(HcfRandSpi *self)
{
if (self == NULL) {
LOGE("Invalid input parameter.");
return NULL;
}
if (!HcfIsClassMatch((HcfObjectBase *)self, GetMbedtlsRandClass())) {
LOGE("Class is not match.");
return NULL;
}
return MBEDTLS_RAND_ALGORITHM;
}
static void MbedtlsSetSeed(HcfRandSpi *self, HcfBlob *seed)
{
if ((self == NULL) || (seed == NULL)) {
LOGE("Invalid params!");
return;
}
if ((seed->data == NULL) || (seed->len == 0)) {
LOGE("Invalid numBytes!");
return;
}
mbedtls_ctr_drbg_context *ctrDrbg = MbedtlsGetMdCtrDrbg(self);
if (ctrDrbg == NULL) {
LOGE("Invalid ctrDrbg params!");
return;
}
mbedtls_entropy_context *entropy = MbedtlsGetMdEntropy(self);
if (entropy == NULL) {
LOGE("Invalid entropy params!");
return;
}
int32_t ret = mbedtls_ctr_drbg_seed(ctrDrbg, mbedtls_entropy_func, entropy,
(const unsigned char *)seed->data, seed->len);
if (ret != 0) {
LOGE("seed return is %d error!", ret);
return;
}
}
static void DestroyMbedtlsRand(HcfObjectBase *self)
{
if (self == NULL) {
LOGE("Self ptr is NULL!");
return;
}
if (!HcfIsClassMatch(self, GetMbedtlsRandClass())) {
LOGE("Class is not match.");
return;
}
mbedtls_ctr_drbg_context *ctrDrbg = MbedtlsGetMdCtrDrbg((HcfRandSpi *)self);
if (ctrDrbg != NULL) {
mbedtls_ctr_drbg_free(ctrDrbg);
HcfFree(ctrDrbg);
}
mbedtls_entropy_context *entropy = MbedtlsGetMdEntropy((HcfRandSpi *)self);
if (entropy != NULL) {
mbedtls_entropy_free(entropy);
HcfFree(entropy);
}
HcfFree(self);
}
static int32_t MbedtlsRandInitEx(mbedtls_entropy_context **entropy, mbedtls_ctr_drbg_context **ctrDrbg)
{
if ((entropy == NULL) || (ctrDrbg == NULL)) {
LOGE("Invalid input parameter.");
return HCF_INVALID_PARAMS;
}
*entropy = (mbedtls_entropy_context *)HcfMalloc(sizeof(mbedtls_entropy_context), 0);
if (*entropy == NULL) {
LOGE("Failed to allocate *entropy memory!");
return HCF_ERR_MALLOC;
}
*ctrDrbg = (mbedtls_ctr_drbg_context *)HcfMalloc(sizeof(mbedtls_ctr_drbg_context), 0);
if (*ctrDrbg == NULL) {
HcfFree(*entropy);
LOGE("Failed to allocate *ctrDrbg memory!");
return HCF_ERR_MALLOC;
}
mbedtls_entropy_init(*entropy);
mbedtls_ctr_drbg_init(*ctrDrbg);
int32_t ret = mbedtls_ctr_drbg_seed(*ctrDrbg, mbedtls_entropy_func, *entropy, NULL, 0);
if (ret != 0) {
LOGE("Failed seed ret is %d!", ret);
mbedtls_entropy_free(*entropy);
mbedtls_ctr_drbg_free(*ctrDrbg);
HcfFree(*entropy);
HcfFree(*ctrDrbg);
return HCF_ERR_CRYPTO_OPERATION;
}
return HCF_SUCCESS;
}
HcfResult MbedtlsRandSpiCreate(HcfRandSpi **spiObj)
{
if (spiObj == NULL) {
LOGE("Invalid input parameter.");
return HCF_INVALID_PARAMS;
}
HcfRandSpiImpl *returnSpiImpl = (HcfRandSpiImpl *)HcfMalloc(sizeof(HcfRandSpiImpl), 0);
if (returnSpiImpl == NULL) {
LOGE("Failed to allocate *returnSpiImpl memory!");
return HCF_ERR_MALLOC;
}
int32_t ret = MbedtlsRandInitEx(&(returnSpiImpl->entropy), &(returnSpiImpl->ctrDrbg));
if (ret != HCF_SUCCESS) {
LOGE("Failed to allocate entropy ctrDrbg memory!");
return HCF_ERR_MALLOC;
}
returnSpiImpl->base.base.getClass = GetMbedtlsRandClass;
returnSpiImpl->base.base.destroy = DestroyMbedtlsRand;
returnSpiImpl->base.engineGenerateRandom = MbedtlsGenerateRandom;
returnSpiImpl->base.engineSetSeed = MbedtlsSetSeed;
returnSpiImpl->base.engineGetAlgoName = MbedtlsGetRandAlgoName;
*spiObj = (HcfRandSpi *)returnSpiImpl;
return HCF_SUCCESS;
}

View File

@ -96,3 +96,17 @@ plugin_files = plugin_asy_key_generator_files + plugin_key_agreement_files +
plugin_sym_key_files + plugin_cipher_files + plugin_hmac_files +
plugin_rand_files + plugin_md_files + plugin_signature_files +
plugin_common_files + plugin_kdf_files
mbedtls_plugin_inc_path = [
"${base_path}/interfaces/innerkits/common",
"${plugin_path}/mbedtls_plugin/common",
"${plugin_path}/mbedtls_plugin/md/inc",
"${plugin_path}/mbedtls_plugin/rand/inc",
"//base/security/crypto_framework/frameworks/spi",
"//base/security/crypto_framework/common/inc",
]
mbedtls_plugin_files = [
"${plugin_path}/mbedtls_plugin/md/src/mbedtls_md.c",
"${plugin_path}/mbedtls_plugin/rand/src/mbedtls_rand.c",
]