diff --git a/BUILD.gn b/BUILD.gn index c7ff8f3d16aad3249e7d61d87f1ef7d0b0438d8d..d8af064088fb7a142e104ec8dd2ae124b3dd94e6 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -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", + ] } } diff --git a/README_zh.md b/README_zh.md index 7cad669c1c0cf04775ae0c473812160b9adc5126..37a292dbcdd19de5e643215fc692e9912482e7d7 100644 --- a/README_zh.md +++ b/README_zh.md @@ -21,14 +21,17 @@ base/security/crypto_framwork ├── test # unitest ├── common # 内部依赖的公共方法 ├── plugin # 算法适配的插件实现 +│ ├── mbedtls_plugin # mbedtls 插件 │ └── openssl_plugin # openssl 插件 ├── frameworks # 框架实现层 │ ├── spi # SPI的接口 │ ├── js +│ ├── jsi # 通过jsi封装的JS接口代码实现 │ └── napi # 通过napi封装的JS接口代码实现 │ ├── algorithm_parameter # 算法参数 │ ├── crypto_operation # 算法操作,包括mac、md、加解密、签名验签、秘钥协商 │ ├── key # 秘钥材料 +│ ├── native # 对外提供算法库C接口 │ └── rand # 随机数 ``` diff --git a/bundle.json b/bundle.json index 0ea0526b9f5c8e5e429457508511350095b63e34..e64ffc4409a49fac16263ac85b38dbf38cf7f010 100644 --- a/bundle.json +++ b/bundle.json @@ -14,10 +14,23 @@ "component": { "name": "crypto_framework", "subsystem": "security", - "syscap": [ "SystemCapability.Security.CryptoFramework" ], + "syscap": [ + "SystemCapability.Security.CryptoFramework", + "SystemCapability.Security.CryptoFramework.Key", + "SystemCapability.Security.CryptoFramework.Key.SymKey", + "SystemCapability.Security.CryptoFramework.Key.AsymKey", + "SystemCapability.Security.CryptoFramework.Signature", + "SystemCapability.Security.CryptoFramework.Cipher", + "SystemCapability.Security.CryptoFramework.KeyAgreement", + "SystemCapability.Security.CryptoFramework.MessageDigest", + "SystemCapability.Security.CryptoFramework.Mac", + "SystemCapability.Security.CryptoFramework.Kdf", + "SystemCapability.Security.CryptoFramework.Rand" + ], "features": [ "crypto_framework_enabled" ], "adapted_system_type": [ - "standard" + "standard", + "mini" ], "rom": "2048KB", "ram": "", @@ -77,6 +90,34 @@ ], "header_base": "//base/security/crypto_framework/interfaces/innerkits" } + }, + { + "name": "//base/security/crypto_framework/frameworks/cj:cj_cryptoframework_ffi", + "header": { + "header_files": [ + "asy_key_generator_impl.h", + "asy_key_spec_generator_impl.h", + "cipher_impl.h", + "crypto_ffi.h", + "dh_key_util_impl.h", + "ecc_key_util_impl.h", + "kdf_impl.h", + "key_agreement_impl.h", + "key_impl.h", + "key_pair_impl.h", + "mac_impl.h", + "md_impl.h", + "pri_key_impl.h", + "pub_key_impl.h", + "random_impl.h", + "sign_impl.h", + "sm2_crypto_util_impl.h", + "sym_key_generator_impl.h", + "sym_key_impl.h", + "verify_impl.h" + ], + "header_base": "//base/security/crypto_framework/frameworks/cj/include" + } } ], "test": [ diff --git a/common/BUILD.gn b/common/BUILD.gn index f216116e63dfb9e5d80563c1d236932a79848f11..98419d94ded2e09e7d221b19a88683a9c3aeb0c1 100644 --- a/common/BUILD.gn +++ b/common/BUILD.gn @@ -14,30 +14,46 @@ import("//base/security/crypto_framework/common/common.gni") import("//build/ohos.gni") -ohos_static_library("crypto_plugin_common") { - subsystem_name = "security" - part_name = "crypto_framework" - include_dirs = crypto_framwork_common_inc_path - - sources = crypto_framwork_common_files - - if (os_level == "standard") { - sanitize = { - cfi = true - cfi_cross_dso = true - debug = false +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 + + 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", - ] - - external_deps = [ - "c_utils:utils", - "hilog:libhilog", - ] + sources = crypto_framwork_common_files_lite + + defines = [ "MINI_HILOG_ENABLE" ] + + configs = [ "${product_path}:product_public_configs" ] + } } diff --git a/common/common.gni b/common/common.gni index 5507276b51ab50a285b2a36ca91db3babe3e360d..b6c1865b30e679d88f3e79b03a32ed876bf5ea73 100644 --- a/common/common.gni +++ b/common/common.gni @@ -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", +] diff --git a/common/inc/log.h b/common/inc/log.h index 0a18450c811b3a843642860575c280f3da09a312..ded862155449711d8d984ad87c33d3f60b32c27c 100644 --- a/common/inc/log.h +++ b/common/inc/log.h @@ -19,7 +19,16 @@ #include #include -#ifdef HILOG_ENABLE +#if defined(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 defined(HILOG_ENABLE) enum HcfLogLevel { HCF_LOG_LEVEL_I, diff --git a/common/src/asy_key_params.c b/common/src/asy_key_params.c index 22843498ed8df059480f07882715147070751562..415ab5aca1521d04efe2d9ee12e91ab6f0874b7d 100644 --- a/common/src/asy_key_params.c +++ b/common/src/asy_key_params.c @@ -214,9 +214,11 @@ void DestroyEccPriKeySpec(HcfEccPriKeyParamsSpec *spec) return; } FreeEccCommParamsSpec(&(spec->base)); - (void)memset_s(spec->sk.data, spec->sk.len, 0, spec->sk.len); - HcfFree(spec->sk.data); - spec->sk.data = NULL; + if (spec->sk.data != NULL) { + (void)memset_s(spec->sk.data, spec->sk.len, 0, spec->sk.len); + HcfFree(spec->sk.data); + spec->sk.data = NULL; + } HcfFree(spec); } @@ -460,7 +462,7 @@ void FreeAsyKeySpec(HcfAsyKeyParamsSpec *spec) } HcfFreeParamsAsyKeySpec createFreeFunc = FindAsyKeySpecFreeAbility(spec); if (createFreeFunc != NULL) { - return createFreeFunc(spec); + createFreeFunc(spec); } else { LOGE("create freeFunc failed."); } diff --git a/common/src/hcf_parcel.c b/common/src/hcf_parcel.c index beb96674ea3f94a6d4ddd8cb43c920f5fd1d1275..9573128a64f4f4154eabf3e564c2c5ec8ac4e2f9 100644 --- a/common/src/hcf_parcel.c +++ b/common/src/hcf_parcel.c @@ -46,7 +46,7 @@ void DeleteParcel(HcParcel *parcel) if (parcel->data != NULL) { HcfFree(parcel->data); - parcel->data = 0; + parcel->data = NULL; } parcel->length = 0; parcel->beginPos = 0; @@ -66,7 +66,7 @@ uint32_t GetParcelDataSize(const HcParcel *parcel) const char *GetParcelData(const HcParcel *parcel) { - if (parcel == NULL) { + if (parcel == NULL || parcel->data == NULL) { return NULL; } return parcel->data + parcel->beginPos; @@ -122,9 +122,8 @@ static void ParcelRecycle(HcParcel *parcel) uint32_t contentSize = parcel->endPos - parcel->beginPos; if (contentSize > 0) { - if (memmove_s(parcel->data, parcel->endPos - parcel->beginPos, - parcel->data + parcel->beginPos, parcel->endPos - parcel->beginPos) != EOK) { - } + (void)memmove_s(parcel->data, parcel->endPos - parcel->beginPos, + parcel->data + parcel->beginPos, parcel->endPos - parcel->beginPos); } parcel->beginPos = 0; parcel->endPos = contentSize; diff --git a/common/src/hcf_string.c b/common/src/hcf_string.c index 8d1b3d628c50694c91a2a4119d5df39168faf115..e7ed836bf14f1660069b0a1f1f1842de18cbc671 100644 --- a/common/src/hcf_string.c +++ b/common/src/hcf_string.c @@ -129,7 +129,7 @@ int StringFind(const HcString *self, char c, uint32_t begin) if (self == NULL) { return -1; } - + uint32_t p = begin; // because the return value is int // so the string length cannot bigger than MAX_INT uint32_t strLen = StringLength(self); @@ -138,11 +138,11 @@ int StringFind(const HcString *self, char c, uint32_t begin) } const char* curChar = StringGet(self); - while (begin < strLen) { - if (*(curChar + begin) == c) { - return begin; + while (p < strLen) { + if (*(curChar + p) == c) { + return p; } - ++begin; + ++p; } return -1; } diff --git a/common/src/object_base.c b/common/src/object_base.c index d3ff9178b45dca9b5938a3410eb2debd934be213..15d10905e2ca4097b46909013ab4fd5131089bd2 100644 --- a/common/src/object_base.c +++ b/common/src/object_base.c @@ -19,7 +19,8 @@ void HcfObjDestroy(void *obj) { - if (obj != NULL) { - ((HcfObjectBase *)obj)->destroy((HcfObjectBase *)obj); + HcfObjectBase *tmp = (HcfObjectBase *)obj; + if (tmp != NULL && tmp->destroy != NULL) { + tmp->destroy(tmp); } } diff --git a/figures/zh-cn_crypto_framework_architecture.png b/figures/zh-cn_crypto_framework_architecture.png index a35cc52b27ea1b2dfd68eb762a1d0dd102bdd68d..7c73e2ebd609c95d76c3f075b31ff45062190de6 100755 Binary files a/figures/zh-cn_crypto_framework_architecture.png and b/figures/zh-cn_crypto_framework_architecture.png differ diff --git a/frameworks/BUILD.gn b/frameworks/BUILD.gn index 11b713af5b01fecc4f989bee07094114f07deee6..9d864090615f1b31e6914b37e66e2406b91b7b84 100644 --- a/frameworks/BUILD.gn +++ b/frameworks/BUILD.gn @@ -24,36 +24,67 @@ config("framework_config") { ] } -ohos_shared_library("crypto_framework_lib") { - 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 - - if (os_level == "standard") { - sanitize = { - cfi = true - cfi_cross_dso = true - debug = false +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 + + 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", + ] + } } diff --git a/frameworks/cj/BUILD.gn b/frameworks/cj/BUILD.gn index 72d493a156345430f39c1e699f49a968322830c9..849f114de32343cea0c1f251308141caaddc5def 100644 --- a/frameworks/cj/BUILD.gn +++ b/frameworks/cj/BUILD.gn @@ -16,7 +16,9 @@ import("//base/security/crypto_framework/frameworks/frameworks.gni") import("//build/ohos.gni") ohos_shared_library("cj_cryptoframework_ffi") { - include_dirs = framework_inc_path + branch_protector_ret = "pac_ret" + include_dirs = [ "include" ] + include_dirs += framework_inc_path if (os_level == "standard") { sanitize = { @@ -48,16 +50,26 @@ ohos_shared_library("cj_cryptoframework_ffi") { "napi:cj_bind_native", ] sources = [ + "src/asy_key_generator_impl.cpp", + "src/asy_key_spec_generator_impl.cpp", "src/cipher_impl.cpp", "src/crypto_ffi.cpp", - "src/crypto_utils.cpp", + "src/dh_key_util_impl.cpp", + "src/ecc_key_util_impl.cpp", + "src/kdf_impl.cpp", + "src/key_agreement_impl.cpp", "src/key_impl.cpp", + "src/key_pair_impl.cpp", "src/mac_impl.cpp", "src/md_impl.cpp", + "src/pri_key_impl.cpp", + "src/pub_key_impl.cpp", "src/random_impl.cpp", "src/sign_impl.cpp", - "src/symkey_generator_impl.cpp", - "src/symkey_impl.cpp", + "src/sm2_crypto_util_impl.cpp", + "src/sym_key_generator_impl.cpp", + "src/sym_key_impl.cpp", + "src/verify_impl.cpp", ] } else { defines += [ "PREVIEWER" ] diff --git a/frameworks/cj/include/asy_key_generator_impl.h b/frameworks/cj/include/asy_key_generator_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..c03ae02a9ee33535d4331ec56d495bc6d6c8b0e8 --- /dev/null +++ b/frameworks/cj/include/asy_key_generator_impl.h @@ -0,0 +1,34 @@ +/* + * 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 ASY_KEY_GENERATOR_IMPL_H +#define ASY_KEY_GENERATOR_IMPL_H + +#include "asy_key_generator.h" +#include "ffi_remote_data.h" + +namespace OHOS { +namespace CryptoFramework { +class AsyKeyGeneratorImpl : public OHOS::FFI::FFIData { + DECL_TYPE(AsyKeyGeneratorImpl, OHOS::FFI::FFIData) +public: + explicit AsyKeyGeneratorImpl(HcfAsyKeyGenerator *generator); + ~AsyKeyGeneratorImpl(); + HcfAsyKeyGenerator *GetAsyKeyGenerator(); +private: + HcfAsyKeyGenerator *generator_ = nullptr; +}; +} +} +#endif \ No newline at end of file diff --git a/frameworks/cj/include/asy_key_spec_generator_impl.h b/frameworks/cj/include/asy_key_spec_generator_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..d1b685ff73e10daa7778b6f19cf07e67030e7c95 --- /dev/null +++ b/frameworks/cj/include/asy_key_spec_generator_impl.h @@ -0,0 +1,34 @@ +/* + * 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 ASY_KEY_SPEC_GENERATOR_IMPL_H +#define ASY_KEY_SPEC_GENERATOR_IMPL_H + +#include "asy_key_generator.h" +#include "ffi_remote_data.h" + +namespace OHOS { +namespace CryptoFramework { +class AsyKeyGeneratorBySpecImpl : public OHOS::FFI::FFIData { + DECL_TYPE(AsyKeyGeneratorBySpecImpl, OHOS::FFI::FFIData) +public: + explicit AsyKeyGeneratorBySpecImpl(HcfAsyKeyGeneratorBySpec *generator); + ~AsyKeyGeneratorBySpecImpl(); + HcfAsyKeyGeneratorBySpec *GetAsyKeyGeneratorBySpec(); +private: + HcfAsyKeyGeneratorBySpec *generator_ = nullptr; +}; +} +} +#endif \ No newline at end of file diff --git a/frameworks/cj/src/cipher_impl.h b/frameworks/cj/include/cipher_impl.h similarity index 92% rename from frameworks/cj/src/cipher_impl.h rename to frameworks/cj/include/cipher_impl.h index 50e73f68e5cdfe5e2723a99059081f4f7b41082d..28b0033c8871db3ae185faca8f80483c3cb2d62a 100644 --- a/frameworks/cj/src/cipher_impl.h +++ b/frameworks/cj/include/cipher_impl.h @@ -1,45 +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. - */ -#ifndef CIPHER_IMPL_H -#define CIPHER_IMPL_H - -#include "ffi_remote_data.h" -#include "algorithm_parameter.h" -#include "key.h" -#include "cipher.h" -#include "blob.h" - -namespace OHOS { -namespace CryptoFramework { -class CipherImpl : public OHOS::FFI::FFIData { - DECL_TYPE(CipherImpl, OHOS::FFI::FFIData) -public: - explicit CipherImpl(HcfCipher *cipher); - ~CipherImpl(); - HcfResult CipherInit(HcfCryptoMode opMode, HcfKey *key, HcfParamsSpec *params); - HcfResult CipherUpdate(HcfBlob *input, HcfBlob *output); - HcfResult CipherDoFinal(HcfBlob *input, HcfBlob *output); - HcfResult SetCipherSpec(CipherSpecItem item, HcfBlob pSource); - HcfResult GetCipherSpecString(CipherSpecItem item, char **returnString); - HcfResult GetCipherSpecUint8Array(CipherSpecItem item, HcfBlob *returnUint8Array); - const char *GetAlgorithm(int32_t* errCode); - -private: - HcfCipher *cipher_; -}; -} -} - -#endif +/* + * 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 CIPHER_IMPL_H +#define CIPHER_IMPL_H + +#include "ffi_remote_data.h" +#include "algorithm_parameter.h" +#include "key.h" +#include "cipher.h" +#include "blob.h" + +namespace OHOS { +namespace CryptoFramework { +class CipherImpl : public OHOS::FFI::FFIData { + DECL_TYPE(CipherImpl, OHOS::FFI::FFIData) +public: + explicit CipherImpl(HcfCipher *cipher); + ~CipherImpl(); + HcfResult CipherInit(HcfCryptoMode opMode, HcfKey *key, HcfParamsSpec *params); + HcfResult CipherUpdate(HcfBlob *input, HcfBlob *output); + HcfResult CipherDoFinal(HcfBlob *input, HcfBlob *output); + HcfResult SetCipherSpec(CipherSpecItem item, HcfBlob pSource); + HcfResult GetCipherSpecString(CipherSpecItem item, char *returnString); + HcfResult GetCipherSpecUint8Array(CipherSpecItem item, HcfBlob *returnUint8Array); + const char *GetAlgorithm(int32_t* errCode); + +private: + HcfCipher *cipher_; +}; +} +} + +#endif diff --git a/frameworks/cj/src/crypto_ffi.h b/frameworks/cj/include/crypto_ffi.h similarity index 31% rename from frameworks/cj/src/crypto_ffi.h rename to frameworks/cj/include/crypto_ffi.h index b167b2a7824dc64205ed263b8146b8c3747aaf0d..8f6254b629bd96a61d1a28785b05d337f1f3b4ce 100644 --- a/frameworks/cj/src/crypto_ffi.h +++ b/frameworks/cj/include/crypto_ffi.h @@ -1,79 +1,194 @@ -/* - * 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 CRYPTO_FFI_H -#define CRYPTO_FFI_H - -#include "cj_common_ffi.h" -#include "blob.h" -#include "cipher.h" -#include "algorithm_parameter.h" - -extern "C" { - typedef struct { - HcfBlob iv; - HcfBlob add; - HcfBlob authTag; - } CParamsSpec; - - // random - FFI_EXPORT int64_t FfiOHOSCreateRandom(int32_t* errCode); - FFI_EXPORT const char *FfiOHOSRandomGetAlgName(int64_t id, int32_t* errCode); - FFI_EXPORT HcfBlob FfiOHOSGenerateRandom(int64_t id, int32_t numBytes, int32_t* errCode); - FFI_EXPORT void FfiOHOSSetSeed(int64_t id, HcfBlob *seed, int32_t* errCode); - - // md - FFI_EXPORT int64_t FfiOHOSCreateMd(char* algName, int32_t* errCode); - FFI_EXPORT int32_t FfiOHOSMdUpdate(int64_t id, HcfBlob *input); - FFI_EXPORT HcfBlob FfiOHOSDigest(int64_t id, int32_t* errCode); - FFI_EXPORT uint32_t FfiOHOSGetMdLength(int64_t id, int32_t* errCode); - - // symkeygenerator - FFI_EXPORT int64_t FfiOHOSCreateSymKeyGenerator(char* algName, int32_t* errCode); - FFI_EXPORT const char *FfiOHOSSymKeyGeneratorGetAlgName(int64_t id, int32_t* errCode); - FFI_EXPORT int64_t FfiOHOSGenerateSymKey(int64_t id, int32_t* errCode); - FFI_EXPORT int64_t FfiOHOSConvertKey(int64_t id, HcfBlob *key, int32_t* errCode); - - // symkey - FFI_EXPORT const char *FfiOHOSSymKeyGetAlgName(int64_t id, int32_t* errCode); - FFI_EXPORT const char *FfiOHOSSymKeyGetFormat(int64_t id, int32_t* errCode); - FFI_EXPORT int32_t FfiOHOSSymKeyGetEncoded(int64_t id, HcfBlob *returnBlob); - FFI_EXPORT void FfiOHOSClearMem(int64_t id); - FFI_EXPORT void* FfiOHOSSymKeyGetHcfKey(int64_t id); - - // cipher - FFI_EXPORT int64_t FfiOHOSCreateCipher(char* transformation, int32_t* errCode); - FFI_EXPORT int32_t FfiOHOSCipherInitByIv(int64_t id, int32_t opMode, void* key, HcfBlob blob1); - FFI_EXPORT int32_t FfiOHOSCipherInitByGcm(int64_t id, int32_t opMode, void* key, CParamsSpec spec); - FFI_EXPORT int32_t FfiOHOSCipherInitByCcm(int64_t id, int32_t opMode, void* key, CParamsSpec spec); - FFI_EXPORT int32_t FfiOHOSCipherInitWithOutParams(int64_t id, int32_t opMode, void* key); - FFI_EXPORT int32_t FfiOHOSCipherUpdate(int64_t id, HcfBlob *input, HcfBlob *output); - FFI_EXPORT int32_t FfiOHOSCipherDoFinal(int64_t id, HcfBlob *input, HcfBlob *output); - FFI_EXPORT int32_t FfiOHOSSetCipherSpec(int64_t id, int32_t item, HcfBlob pSource); - FFI_EXPORT int32_t FfiOHOSGetCipherSpecString(int64_t id, int32_t item, char **returnString); - FFI_EXPORT int32_t FfiOHOSGetCipherSpecUint8Array(int64_t id, int32_t item, HcfBlob *returnUint8Array); - FFI_EXPORT const char *FfiOHOSCipherGetAlgName(int64_t id, int32_t* errCode); - - // mac - FFI_EXPORT int64_t FFiOHOSCryptoMacConstructor(char* algName, int32_t* errCode); - FFI_EXPORT int32_t FfiOHOSCryptoMacInit(int64_t id, int64_t symKeyId); - FFI_EXPORT int32_t FfiOHOSCryptoMacUpdate(int64_t id, HcfBlob *input); - FFI_EXPORT HcfBlob FfiOHOSCryptoMacDoFinal(int64_t id, int32_t* errCode); - FFI_EXPORT uint32_t FfiOHOSGCryptoGetMacLength(int64_t id); - - // sign - FFI_EXPORT int64_t FFiOHOSCryptoSignConstructor(char* algName, int32_t* errCode); -} - -#endif +/* + * 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 CRYPTO_FFI_H +#define CRYPTO_FFI_H + +#include "asy_key_generator_impl.h" +#include "asy_key_spec_generator_impl.h" +#include "cipher_impl.h" +#include "dh_key_util_impl.h" +#include "detailed_iv_params.h" +#include "detailed_gcm_params.h" +#include "detailed_ccm_params.h" +#include "detailed_dsa_key_params.h" +#include "detailed_ecc_key_params.h" +#include "detailed_rsa_key_params.h" +#include "detailed_alg_25519_key_params.h" +#include "detailed_dh_key_params.h" +#include "ecc_key_util_impl.h" +#include "kdf_impl.h" +#include "key_agreement_impl.h" +#include "key_pair_impl.h" +#include "mac_impl.h" +#include "md_impl.h" +#include "pri_key_impl.h" +#include "pub_key_impl.h" +#include "random_impl.h" +#include "securec.h" +#include "sign_impl.h" +#include "sm2_crypto_util_impl.h" +#include "sym_key_generator_impl.h" +#include "sym_key_impl.h" +#include "verify_impl.h" + +extern "C" { + typedef struct { + HcfBlob iv; + HcfBlob add; + HcfBlob authTag; + } CParamsSpec; + + // random + FFI_EXPORT int64_t FfiOHOSCreateRandom(int32_t* errCode); + FFI_EXPORT const char *FfiOHOSRandomGetAlgName(int64_t id, int32_t* errCode); + FFI_EXPORT HcfBlob FfiOHOSGenerateRandom(int64_t id, int32_t numBytes, int32_t* errCode); + FFI_EXPORT void FfiOHOSSetSeed(int64_t id, HcfBlob *seed, int32_t* errCode); + + // md + FFI_EXPORT int64_t FfiOHOSCreateMd(char* algName, int32_t* errCode); + FFI_EXPORT int32_t FfiOHOSMdUpdate(int64_t id, HcfBlob *input); + FFI_EXPORT HcfBlob FfiOHOSDigest(int64_t id, int32_t* errCode); + FFI_EXPORT uint32_t FfiOHOSGetMdLength(int64_t id, int32_t* errCode); + + // symkeygenerator + FFI_EXPORT int64_t FfiOHOSCreateSymKeyGenerator(char* algName, int32_t* errCode); + FFI_EXPORT const char *FfiOHOSSymKeyGeneratorGetAlgName(int64_t id, int32_t* errCode); + FFI_EXPORT int64_t FfiOHOSGenerateSymKey(int64_t id, int32_t* errCode); + FFI_EXPORT int64_t FfiOHOSConvertKey(int64_t id, HcfBlob *key, int32_t* errCode); + + // symkey + FFI_EXPORT const char *FfiOHOSSymKeyGetAlgName(int64_t id, int32_t* errCode); + FFI_EXPORT const char *FfiOHOSSymKeyGetFormat(int64_t id, int32_t* errCode); + FFI_EXPORT int32_t FfiOHOSSymKeyGetEncoded(int64_t id, HcfBlob *returnBlob); + FFI_EXPORT void FfiOHOSClearMem(int64_t id); + FFI_EXPORT void* FfiOHOSSymKeyGetHcfKey(int64_t id); + + // cipher + FFI_EXPORT int64_t FfiOHOSCreateCipher(char* transformation, int32_t* errCode); + FFI_EXPORT int32_t FfiOHOSCipherInitByIv(int64_t id, int32_t opMode, void* key, HcfBlob blob1); + FFI_EXPORT int32_t FfiOHOSCipherInitByGcm(int64_t id, int32_t opMode, void* key, CParamsSpec spec); + FFI_EXPORT int32_t FfiOHOSCipherInitByCcm(int64_t id, int32_t opMode, void* key, CParamsSpec spec); + FFI_EXPORT int32_t FfiOHOSCipherInitWithOutParams(int64_t id, int32_t opMode, void* key); + FFI_EXPORT int32_t FfiOHOSCipherUpdate(int64_t id, HcfBlob *input, HcfBlob *output); + FFI_EXPORT int32_t FfiOHOSCipherDoFinal(int64_t id, HcfBlob *input, HcfBlob *output); + FFI_EXPORT int32_t FfiOHOSSetCipherSpec(int64_t id, int32_t item, HcfBlob pSource); + FFI_EXPORT int32_t FfiOHOSGetCipherSpecString(int64_t id, int32_t item, char *returnString); + FFI_EXPORT int32_t FfiOHOSGetCipherSpecUint8Array(int64_t id, int32_t item, HcfBlob *returnUint8Array); + FFI_EXPORT const char *FfiOHOSCipherGetAlgName(int64_t id, int32_t* errCode); + + // mac + FFI_EXPORT int64_t FFiOHOSCryptoMacConstructor(char* algName, int32_t* errCode); + FFI_EXPORT int32_t FfiOHOSCryptoMacInit(int64_t id, int64_t symKeyId); + FFI_EXPORT int32_t FfiOHOSCryptoMacUpdate(int64_t id, HcfBlob *input); + FFI_EXPORT HcfBlob FfiOHOSCryptoMacDoFinal(int64_t id, int32_t* errCode); + FFI_EXPORT uint32_t FfiOHOSCryptoGetMacLength(int64_t id); + + // sign + FFI_EXPORT int64_t FFiOHOSCryptoSignConstructor(char* algName, int32_t* errCode); + FFI_EXPORT int32_t FFiOHOSSignInit(int64_t sid, int64_t pid); + FFI_EXPORT int32_t FFiOHOSSignUpdate(int64_t id, HcfBlob input); + FFI_EXPORT int32_t FFiOHOSSignSign(int64_t id, HcfBlob *input, HcfBlob *output); + FFI_EXPORT int32_t FFiOHOSSignSetSignSpecByNum(int64_t id, int32_t itemValue); + FFI_EXPORT int32_t FFiOHOSSignSetSignSpecByArr(int64_t id, HcfBlob itemValue); + FFI_EXPORT int32_t FFiOHOSSignGetSignSpecString(int64_t id, SignSpecItem item, char *itemValue); + FFI_EXPORT int32_t FFiOHOSSignGetSignSpecNum(int64_t id, SignSpecItem item, int32_t *itemValue); + + // verify + FFI_EXPORT int64_t FFiOHOSVerifyConstructor(char* algName, int32_t* errCode); + FFI_EXPORT int32_t FFiOHOSVerifyInit(int64_t vid, int64_t pid); + FFI_EXPORT int32_t FFiOHOSVerifyUpdate(int64_t id, HcfBlob input); + FFI_EXPORT bool FFiOHOSVerifyVerify(int64_t id, HcfBlob *data, HcfBlob signatureData, int32_t* errCode); + FFI_EXPORT int32_t FFiOHOSVerifyRecover(int64_t id, HcfBlob input, HcfBlob *output); + FFI_EXPORT int32_t FFiOHOSVerifySetVerifySpecByNum(int64_t id, int32_t itemValue); + FFI_EXPORT int32_t FFiOHOSVerifySetVerifySpecByArr(int64_t id, HcfBlob itemValue); + FFI_EXPORT int32_t FFiOHOSVerifyGetVerifySpecString(int64_t id, SignSpecItem item, char *itemValue); + FFI_EXPORT int32_t FFiOHOSVerifyGetVerifySpecNum(int64_t id, SignSpecItem item, int32_t *itemValue); + + // asykeygenerator + FFI_EXPORT int64_t FFiOHOSAsyKeyGeneratorConstructor(char *algName, int32_t *errCode); + FFI_EXPORT int64_t FFiOHOSAsyKeyGeneratorGenerateKeyPair(int64_t id, int32_t *errCode); + FFI_EXPORT int64_t FFiOHOSAsyKeyGeneratorConvertKey(int64_t id, HcfBlob *pubKey, HcfBlob *priKey, int32_t *errCode); + FFI_EXPORT int64_t FFiOHOSAsyKeyGeneratorConvertPemKey(int64_t id, char *pubKey, char *priKey, int32_t *errCode); + + // asykeyspecgenerator + FFI_EXPORT int64_t FFiOHOSAsyKeyGeneratorByDsaCommonSpec(HcfDsaCommParamsSpec *spec, int32_t *errCode); + FFI_EXPORT int64_t FFiOHOSAsyKeyGeneratorByDsaPubKeySpec(HcfDsaPubKeyParamsSpec *spec, int32_t *errCode); + FFI_EXPORT int64_t FFiOHOSAsyKeyGeneratorByDsaKeyPairSpec(HcfDsaKeyPairParamsSpec *spec, int32_t *errCode); + FFI_EXPORT int64_t FFiOHOSAsyKeyGeneratorByEccCommonSpec(HcfEccCommParamsSpec *spec, int32_t *errCode); + FFI_EXPORT int64_t FFiOHOSAsyKeyGeneratorByEccPriKeySpec(HcfEccPriKeyParamsSpec *spec, int32_t *errCode); + FFI_EXPORT int64_t FFiOHOSAsyKeyGeneratorByEccPubKeySpec(HcfEccPubKeyParamsSpec *spec, int32_t *errCode); + FFI_EXPORT int64_t FFiOHOSAsyKeyGeneratorByEccKeyPairSpec(HcfEccKeyPairParamsSpec *spec, int32_t *errCode); + FFI_EXPORT int64_t FFiOHOSAsyKeyGeneratorByRsaPubKeySpec(HcfRsaPubKeyParamsSpec *spec, int32_t *errCode); + FFI_EXPORT int64_t FFiOHOSAsyKeyGeneratorByRsaKeyPairSpec(HcfRsaKeyPairParamsSpec *spec, int32_t *errCode); + FFI_EXPORT int64_t FFiOHOSAsyKeyGeneratorByAlg25519PriKeySpec(HcfAlg25519PriKeyParamsSpec *spec, int32_t *errCode); + FFI_EXPORT int64_t FFiOHOSAsyKeyGeneratorByAlg25519PubKeySpec(HcfAlg25519PubKeyParamsSpec *spec, int32_t *errCode); + FFI_EXPORT int64_t FFiOHOSAsyKeyGeneratorByAlg25519KeyPairSpec( + HcfAlg25519KeyPairParamsSpec *spec, int32_t *errCode); + FFI_EXPORT int64_t FFiOHOSAsyKeyGeneratorByDhPriKeySpec(HcfDhPriKeyParamsSpec *spec, int32_t *errCode); + FFI_EXPORT int64_t FFiOHOSAsyKeyGeneratorByDhPubKeySpec(HcfDhPubKeyParamsSpec *spec, int32_t *errCode); + FFI_EXPORT int64_t FFiOHOSAsyKeyGeneratorByDhKeyPairSpec(HcfDhKeyPairParamsSpec *spec, int32_t *errCode); + FFI_EXPORT int64_t FFiOHOSAsyKeyGeneratorByDhCommonSpec(HcfDhCommParamsSpec *spec, int32_t *errCode); + FFI_EXPORT int64_t FFiOHOSAsyKeyGeneratorBySpecGenerateKeyPair(int64_t id, int32_t *errCode); + FFI_EXPORT int64_t FFiOHOSAsyKeyGeneratorBySpecGeneratePriKey(int64_t id, int32_t *errCode); + FFI_EXPORT int64_t FFiOHOSAsyKeyGeneratorBySpecGeneratePubKey(int64_t id, int32_t *errCode); + + // prikey + FFI_EXPORT HcfBlob FFiOHOSPriKeyGetEncoded(int64_t id, int32_t *errCode); + FFI_EXPORT HcfBlob FFiOHOSPriKeyGetEncodedDer(int64_t id, char *format, int32_t *errCode); + FFI_EXPORT char *FFiOHOSPriKeyGetEncodedPem(int64_t id, char *format, int32_t *errCode); + FFI_EXPORT int32_t FFiOHOSPriKeyClearMem(int64_t id); + FFI_EXPORT int FFiOHOSPriKeyGetAsyKeySpecByNum(int64_t id, int32_t itemType, int32_t *errCode); + FFI_EXPORT char *FFiOHOSPriKeyGetAsyKeySpecByStr(int64_t id, int32_t itemType, int32_t *errCode); + FFI_EXPORT HcfBigInteger FFiOHOSPriKeyGetAsyKeySpecByBigInt(int64_t id, int32_t itemType, int32_t *errCode); + FFI_EXPORT const char *FfiOHOSPriKeyKeyGetFormat(int64_t id, int32_t* errCode); + + // pubkey + FFI_EXPORT HcfBlob FFiOHOSPubKeyGetEncoded(int64_t id, int32_t *errCode); + FFI_EXPORT HcfBlob FFiOHOSPubKeyGetEncodedDer(int64_t id, char *format, int32_t *errCode); + FFI_EXPORT char *FFiOHOSPubKeyGetEncodedPem(int64_t id, char *format, int32_t *errCode); + FFI_EXPORT int FFiOHOSPubKeyGetAsyKeySpecByNum(int64_t id, int32_t itemType, int32_t *errCode); + FFI_EXPORT char *FFiOHOSPubKeyGetAsyKeySpecByStr(int64_t id, int32_t itemType, int32_t *errCode); + FFI_EXPORT HcfBigInteger FFiOHOSPubKeyGetAsyKeySpecByBigInt(int64_t id, int32_t itemType, int32_t *errCode); + FFI_EXPORT const char *FfiOHOSPubKeyKeyGetFormat(int64_t id, int32_t* errCode); + + // keypair + FFI_EXPORT int64_t FFiOHOSKeyPairPubKey(int64_t id, int32_t *errCode); + FFI_EXPORT int64_t FFiOHOSKeyPairPriKey(int64_t id, int32_t *errCode); + + // kdf + FFI_EXPORT int64_t FFiOHOSKdfConstructor(char *algName, int32_t *errCode); + FFI_EXPORT int32_t FFiOHOSKdfGenerateSecretByPB(int64_t id, HcfPBKDF2ParamsSpec *params); + FFI_EXPORT int32_t FFiOHOSKdfGenerateSecretByH(int64_t id, HcfHkdfParamsSpec *params); + + // ecc_key_util + FFI_EXPORT HcfEccCommParamsSpec *FFiOHOSECCKeyUtilGenECCCommonParamsSpec(char *curveName, int32_t *errCode); + FFI_EXPORT HcfPoint FFiOHOSECCKeyUtilConvertPoint(char *curveName, HcfBlob encodedPoint, int32_t *errCode); + FFI_EXPORT HcfBlob FFiOHOSECCKeyUtilGetEncodedPoint( + char *curveName, HcfPoint point, char *format, int32_t *errCode); + + // keyagreement + FFI_EXPORT int64_t FFiOHOSKeyAgreementConstructor(char *algName, int32_t *errCode); + FFI_EXPORT HcfBlob FFiOHOSKeyAgreementGenerateSecret(int64_t id, int64_t priId, int64_t pubId, int32_t *errCode); + + // dh_key_util + FFI_EXPORT HcfDhCommParamsSpec *FFiOHOSDHKeyUtilGenDHCommonParamsSpec( + int32_t pLen, int32_t skLen, int32_t *errCode); + + // sm2_crypto_util + FFI_EXPORT HcfBlob FFiOHOSSm2CryptoUtilGenCipherTextBySpec(Sm2CipherTextSpec spec, char *mode, int32_t *errCode); + FFI_EXPORT Sm2CipherTextSpec *FFiOHOSSm2CryptoUtilGetCipherTextSpec(HcfBlob input, char *mode, int32_t *errCode); +} + +#endif diff --git a/frameworks/cj/include/dh_key_util_impl.h b/frameworks/cj/include/dh_key_util_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..1e94ea2f16a7aafea6feff4ddedf814ea5c7330c --- /dev/null +++ b/frameworks/cj/include/dh_key_util_impl.h @@ -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 DH_KEY_UTIL_IMPL_H +#define DH_KEY_UTIL_IMPL_H + +#include "dh_key_util.h" +#include "blob.h" + +namespace OHOS { +namespace CryptoFramework { +class DHKeyUtilImpl { +public: + explicit DHKeyUtilImpl(); + ~DHKeyUtilImpl(); + static HcfDhCommParamsSpec *GenDHCommonParamsSpec(int32_t pLen, int32_t skLen, int32_t *errCode); +}; +} +} +#endif \ No newline at end of file diff --git a/frameworks/cj/include/ecc_key_util_impl.h b/frameworks/cj/include/ecc_key_util_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..447e329477fec9ab3ed3c450b7e70e742b2223a9 --- /dev/null +++ b/frameworks/cj/include/ecc_key_util_impl.h @@ -0,0 +1,33 @@ +/* + * 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 ECC_KEY_UTIL_IMPL_H +#define ECC_KEY_UTIL_IMPL_H + +#include "ecc_key_util.h" +#include "blob.h" + +namespace OHOS { +namespace CryptoFramework { +class ECCKeyUtilImpl { +public: + explicit ECCKeyUtilImpl(); + ~ECCKeyUtilImpl(); + static HcfEccCommParamsSpec *GenECCCommonParamsSpec(char *algName, int32_t *errCode); + static HcfPoint ConvertPoint(char *curveName, HcfBlob encodedPoint, int32_t *errCode); + static HcfBlob GetEncodedPoint(char *curveName, HcfPoint point, char *format, int32_t *errCode); +}; +} +} +#endif \ No newline at end of file diff --git a/frameworks/cj/include/kdf_impl.h b/frameworks/cj/include/kdf_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..81b045844523ef3c9ec377727a6e154bb33463ff --- /dev/null +++ b/frameworks/cj/include/kdf_impl.h @@ -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. + */ +#ifndef KDF_IMPL_H +#define KDF_IMPL_H + +#include "ffi_remote_data.h" +#include "blob.h" +#include "kdf.h" +#include "kdf_params.h" +#include "detailed_pbkdf2_params.h" +#include "detailed_hkdf_params.h" + +namespace OHOS { +namespace CryptoFramework { +class KdfImpl : public OHOS::FFI::FFIData { + DECL_TYPE(KdfImpl, OHOS::FFI::FFIData) +public: + explicit KdfImpl(HcfKdf *kdf); + ~KdfImpl(); + HcfKdf *GetKdf() const; + int32_t GenerateSecret(HcfKdfParamsSpec *paramsSpec); +private: + HcfKdf *kdf = nullptr; +}; +} +} +#endif \ No newline at end of file diff --git a/frameworks/cj/include/key_agreement_impl.h b/frameworks/cj/include/key_agreement_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..2002d2618f2f30b4cdf85b38b37d10ec5b09aaa9 --- /dev/null +++ b/frameworks/cj/include/key_agreement_impl.h @@ -0,0 +1,37 @@ +/* + * 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 KEY_AGREEMENT_IMPL_H +#define KEY_AGREEMENT_IMPL_H + +#include "ffi_remote_data.h" +#include "key_agreement.h" +#include "pri_key.h" +#include "pub_key.h" + +namespace OHOS { +namespace CryptoFramework { +class KeyAgreementImpl : public OHOS::FFI::FFIData { + DECL_TYPE(KeyAgreementImpl, OHOS::FFI::FFIData) +public: + explicit KeyAgreementImpl(HcfKeyAgreement *keyAgreement); + ~KeyAgreementImpl(); + HcfKeyAgreement *GetKeyAgreement(); + HcfBlob GenerateSecret(HcfPriKey *priKey, HcfPubKey *pubKey, int32_t *errCode); +private: + HcfKeyAgreement *keyAgreement_ = nullptr; +}; +} +} +#endif diff --git a/frameworks/cj/src/key_impl.h b/frameworks/cj/include/key_impl.h similarity index 96% rename from frameworks/cj/src/key_impl.h rename to frameworks/cj/include/key_impl.h index f579eb9781609d3ae8a0cd52e533ee2820ba50ee..dc16865e6f420c09565e828483df581c534394da 100644 --- a/frameworks/cj/src/key_impl.h +++ b/frameworks/cj/include/key_impl.h @@ -1,40 +1,40 @@ -/* - * 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 KEY_IMPL_H -#define KEY_IMPL_H - -#include "ffi_remote_data.h" -#include "result.h" -#include "key.h" - -namespace OHOS { -namespace CryptoFramework { -class KeyImpl : public OHOS::FFI::FFIData { - DECL_TYPE(KeyImpl, OHOS::FFI::FFIData) -public: - explicit KeyImpl(HcfKey *hcfKey); - virtual ~KeyImpl(); - HcfKey *GetHcfKey() const; - const char *GetFormat(int32_t* errCode); - const char *GetAlgorithm(int32_t* errCode); - HcfResult GetEncoded(HcfBlob *returnBlob); - -protected: - HcfKey *hcfKey_; -}; -} -} - -#endif +/* + * 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 KEY_IMPL_H +#define KEY_IMPL_H + +#include "ffi_remote_data.h" +#include "result.h" +#include "key.h" + +namespace OHOS { +namespace CryptoFramework { +class KeyImpl : public OHOS::FFI::FFIData { + DECL_TYPE(KeyImpl, OHOS::FFI::FFIData) +public: + explicit KeyImpl(HcfKey *hcfKey); + virtual ~KeyImpl(); + HcfKey *GetHcfKey() const; + const char *GetFormat(int32_t* errCode); + const char *GetAlgorithm(int32_t* errCode); + HcfResult GetEncoded(HcfBlob *returnBlob); + +protected: + HcfKey *hcfKey_; +}; +} +} + +#endif diff --git a/frameworks/cj/include/key_pair_impl.h b/frameworks/cj/include/key_pair_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..570f83bb69a3612a538190c2b9c9be2b26cbd010 --- /dev/null +++ b/frameworks/cj/include/key_pair_impl.h @@ -0,0 +1,36 @@ +/* + * 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 KEY_PAIR_IMPL_H +#define KEY_PAIR_IMPL_H + +#include +#include "key_pair.h" +#include "ffi_remote_data.h" + +namespace OHOS { +namespace CryptoFramework { +class KeyPairImpl : public OHOS::FFI::FFIData { +public: + explicit KeyPairImpl(HcfKeyPair *keyPair); + HcfKeyPair *GetHcfKeyPair(); + ~KeyPairImpl(); + +private: + HcfKeyPair *keyPair_ = nullptr; +}; +} // namespace CryptoFramework +} // namespace OHOS +#endif diff --git a/frameworks/cj/src/mac_impl.h b/frameworks/cj/include/mac_impl.h similarity index 96% rename from frameworks/cj/src/mac_impl.h rename to frameworks/cj/include/mac_impl.h index 0e9d3c1b76b4655d91804a251134fa36f2775219..80a4b94b271c41f195a7276caf369799d010056f 100644 --- a/frameworks/cj/src/mac_impl.h +++ b/frameworks/cj/include/mac_impl.h @@ -1,41 +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 MAC_IMPL_H -#define MAC_IMPL_H - -#include "ffi_remote_data.h" -#include "mac.h" -#include "blob.h" - -namespace OHOS { -namespace CryptoFramework { -class MacImpl : public OHOS::FFI::FFIData { - DECL_TYPE(MacImpl, OHOS::FFI::FFIData) -public: - explicit MacImpl(HcfMac *macObj); - ~MacImpl(); - HcfResult MacInit(HcfSymKey *symKey); - HcfResult MacUpdate(HcfBlob *input); - HcfResult MacDoFinal(HcfBlob *output); - uint32_t GetMacLength(); - -private: - HcfMac *macObj_ = nullptr; -}; -} -} - -#endif // MAC_IMPL_H +/* + * 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 MAC_IMPL_H +#define MAC_IMPL_H + +#include "ffi_remote_data.h" +#include "mac.h" +#include "blob.h" +#include "log.h" +#include "result.h" + +namespace OHOS { +namespace CryptoFramework { +class MacImpl : public OHOS::FFI::FFIData { + DECL_TYPE(MacImpl, OHOS::FFI::FFIData) +public: + explicit MacImpl(HcfMac *macObj); + ~MacImpl(); + HcfResult MacInit(HcfSymKey *symKey); + HcfResult MacUpdate(HcfBlob *input); + HcfResult MacDoFinal(HcfBlob *output); + uint32_t GetMacLength(); + +private: + HcfMac *macObj_ = nullptr; +}; +} +} + +#endif // MAC_IMPL_H diff --git a/frameworks/cj/src/md_impl.h b/frameworks/cj/include/md_impl.h similarity index 96% rename from frameworks/cj/src/md_impl.h rename to frameworks/cj/include/md_impl.h index ab2c8783c1222b79b2f449068e5d6080c5a51f1f..b5ea593f41bacdc2a5547528461d6f97af17611d 100644 --- a/frameworks/cj/src/md_impl.h +++ b/frameworks/cj/include/md_impl.h @@ -1,39 +1,41 @@ -/* - * 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 MD_IMPL_H -#define MD_IMPL_H - -#include "ffi_remote_data.h" -#include "md.h" -#include "blob.h" - -namespace OHOS { -namespace CryptoFramework { -class MdImpl : public OHOS::FFI::FFIData { - DECL_TYPE(MdImpl, OHOS::FFI::FFIData) -public: - explicit MdImpl(HcfMd *mdObj); - ~MdImpl(); - HcfResult MdUpdate(HcfBlob *input); - HcfResult MdDoFinal(HcfBlob *output); - uint32_t GetMdLength(int32_t* errCode); - -private: - HcfMd *mdObj_ = nullptr; -}; -} -} - -#endif +/* + * 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 MD_IMPL_H +#define MD_IMPL_H + +#include "ffi_remote_data.h" +#include "md.h" +#include "blob.h" +#include "log.h" +#include "result.h" + +namespace OHOS { +namespace CryptoFramework { +class MdImpl : public OHOS::FFI::FFIData { + DECL_TYPE(MdImpl, OHOS::FFI::FFIData) +public: + explicit MdImpl(HcfMd *mdObj); + ~MdImpl(); + HcfResult MdUpdate(HcfBlob *input); + HcfResult MdDoFinal(HcfBlob *output); + uint32_t GetMdLength(int32_t* errCode); + +private: + HcfMd *mdObj_ = nullptr; +}; +} +} + +#endif diff --git a/frameworks/cj/include/pri_key_impl.h b/frameworks/cj/include/pri_key_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..65bb7979262d17f55115c26cfa1c6a87662d1977 --- /dev/null +++ b/frameworks/cj/include/pri_key_impl.h @@ -0,0 +1,33 @@ +/* + * 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 PRI_KEY_IMPL_H +#define PRI_KEY_IMPL_H + +#include "key_impl.h" +#include "pri_key.h" +#include "ffi_remote_data.h" + +namespace OHOS { +namespace CryptoFramework { +class PriKeyImpl : public KeyImpl { + DECL_TYPE(PriKeyImpl, OHOS::FFI::FFIData) +public: + explicit PriKeyImpl(HcfPriKey *priKey); + ~PriKeyImpl() override; + HcfPriKey *GetPriKey(); +}; +} +} +#endif \ No newline at end of file diff --git a/frameworks/cj/include/pub_key_impl.h b/frameworks/cj/include/pub_key_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..d9c39c9f130f6bb335aad8c01b7a441d90ea4026 --- /dev/null +++ b/frameworks/cj/include/pub_key_impl.h @@ -0,0 +1,33 @@ +/* + * 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 PUB_KEY_IMPL_H +#define PUB_KEY_IMPL_H + +#include "key_impl.h" +#include "pub_key.h" +#include "ffi_remote_data.h" + +namespace OHOS { +namespace CryptoFramework { +class PubKeyImpl : public KeyImpl { + DECL_TYPE(PubKeyImpl, OHOS::FFI::FFIData) +public: + explicit PubKeyImpl(HcfPubKey *pubKey); + ~PubKeyImpl() override; + HcfPubKey *GetPubKey(); +}; +} +} +#endif \ No newline at end of file diff --git a/frameworks/cj/src/random_impl.h b/frameworks/cj/include/random_impl.h similarity index 96% rename from frameworks/cj/src/random_impl.h rename to frameworks/cj/include/random_impl.h index dc164b3ee1e3289f9c910254de49c96d267b6f83..54c7ac231ccf664c16f985139a80b5961208b9b2 100644 --- a/frameworks/cj/src/random_impl.h +++ b/frameworks/cj/include/random_impl.h @@ -1,39 +1,41 @@ -/* - * 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 RANDOM_IMPL_H -#define RANDOM_IMPL_H - -#include "ffi_remote_data.h" -#include "rand.h" -#include "blob.h" - -namespace OHOS { -namespace CryptoFramework { -class RandomImpl : public OHOS::FFI::FFIData { - DECL_TYPE(RandomImpl, OHOS::FFI::FFIData) -public: - explicit RandomImpl(HcfRand *randObj); - ~RandomImpl(); - const char *GetAlgName(int32_t* errCode); - HcfBlob GenerateRandom(int32_t numBytes, int32_t* errCode); - void SetSeed(HcfBlob *seed, int32_t* errCode); - -private: - HcfRand *randObj_ = nullptr; -}; -} -} - -#endif +/* + * 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 RANDOM_IMPL_H +#define RANDOM_IMPL_H + +#include "ffi_remote_data.h" +#include "rand.h" +#include "blob.h" +#include "result.h" +#include "log.h" + +namespace OHOS { +namespace CryptoFramework { +class RandomImpl : public OHOS::FFI::FFIData { + DECL_TYPE(RandomImpl, OHOS::FFI::FFIData) +public: + explicit RandomImpl(HcfRand *randObj); + ~RandomImpl(); + const char *GetAlgName(int32_t* errCode); + HcfBlob GenerateRandom(int32_t numBytes, int32_t* errCode); + void SetSeed(HcfBlob *seed, int32_t* errCode); + +private: + HcfRand *randObj_ = nullptr; +}; +} +} + +#endif diff --git a/frameworks/cj/src/sign_impl.h b/frameworks/cj/include/sign_impl.h similarity index 70% rename from frameworks/cj/src/sign_impl.h rename to frameworks/cj/include/sign_impl.h index e59b0d71f59dc5564dbf17f3af3f68cfeb60945a..33d92190653e5c188fb861229187dcefc2df6546 100644 --- a/frameworks/cj/src/sign_impl.h +++ b/frameworks/cj/include/sign_impl.h @@ -1,37 +1,46 @@ -/* - * 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 SIGN_IMPL_H -#define SIGN_IMPL_H - -#include "ffi_remote_data.h" -#include "signature.h" -#include "blob.h" - -namespace OHOS { -namespace CryptoFramework { -class SignImpl : public OHOS::FFI::FFIData { - DECL_TYPE(SignImpl, OHOS::FFI::FFIData) -public: - explicit SignImpl(HcfSign *signObj); - ~SignImpl(); - -private: - HcfSign *signObj_ = nullptr; -}; -} -} - -#endif // SIGN_IMPL_H +/* + * 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 SIGN_IMPL_H +#define SIGN_IMPL_H + +#include "ffi_remote_data.h" +#include "signature.h" +#include "blob.h" +#include "result.h" +#include "pri_key.h" + +namespace OHOS { +namespace CryptoFramework { +class SignImpl : public OHOS::FFI::FFIData { + DECL_TYPE(SignImpl, OHOS::FFI::FFIData) +public: + explicit SignImpl(HcfSign *signObj); + ~SignImpl(); + HcfResult Init(HcfPriKey *priKey); + HcfResult Update(HcfBlob *input); + HcfResult Sign(HcfBlob *input, HcfBlob *output); + HcfResult SetSignSpecByNum(int32_t itemValue); + HcfResult SetSignSpecByArr(HcfBlob itemValue); + HcfResult GetSignSpecString(SignSpecItem item, char *itemValue); + HcfResult GetSignSpecNum(SignSpecItem item, int32_t *itemValue); + +private: + HcfSign *signObj_ = nullptr; +}; +} +} + +#endif // SIGN_IMPL_H diff --git a/frameworks/cj/include/sm2_crypto_util_impl.h b/frameworks/cj/include/sm2_crypto_util_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..1fec07fb1ad60dbb4398a5d9ba7ae7f56f276cd3 --- /dev/null +++ b/frameworks/cj/include/sm2_crypto_util_impl.h @@ -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 SM2_CRYPTO_UTIL_IMPL_H +#define SM2_CRYPTO_UTIL_IMPL_H + +#include "sm2_crypto_util.h" + +namespace OHOS { +namespace CryptoFramework { +class Sm2CryptoUtilImpl { +public: + explicit Sm2CryptoUtilImpl(); + ~Sm2CryptoUtilImpl(); + static HcfBlob GenCipherTextBySpec(Sm2CipherTextSpec spec, char *mode, int32_t *errCode); + static Sm2CipherTextSpec *GetCipherTextSpec(HcfBlob input, char *mode, int32_t *errCode); +}; +} +} +#endif \ No newline at end of file diff --git a/frameworks/cj/src/symkey_generator_impl.h b/frameworks/cj/include/sym_key_generator_impl.h similarity index 91% rename from frameworks/cj/src/symkey_generator_impl.h rename to frameworks/cj/include/sym_key_generator_impl.h index f57ec02f4be30129486ce3e844a5381402bf6963..92254808cb5a6682b39087dce97b9a7efbf07ea8 100644 --- a/frameworks/cj/src/symkey_generator_impl.h +++ b/frameworks/cj/include/sym_key_generator_impl.h @@ -1,40 +1,41 @@ -/* - * 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 SYMKEY_GENERATOR_IMPL_H -#define SYMKEY_GENERATOR_IMPL_H - -#include "ffi_remote_data.h" -#include "sym_key.h" -#include "result.h" -#include "sym_key_generator.h" - -namespace OHOS { -namespace CryptoFramework { -class SymKeyGeneratorImpl : public OHOS::FFI::FFIData { - DECL_TYPE(SymKeyGeneratorImpl, OHOS::FFI::FFIData) -public: - explicit SymKeyGeneratorImpl(HcfSymKeyGenerator *generator); - ~SymKeyGeneratorImpl(); - const char *GetAlgName(int32_t* errCode); - HcfResult GenerateSymKey(HcfSymKey **symKey); - HcfResult ConvertKey(const HcfBlob key, HcfSymKey **symKey); - -private: - HcfSymKeyGenerator *generator_; -}; -} -} - -#endif +/* + * 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 SYM_KEY_GENERATOR_IMPL_H +#define SYM_KEY_GENERATOR_IMPL_H + +#include "ffi_remote_data.h" +#include "sym_key.h" +#include "result.h" +#include "sym_key_generator.h" +#include "log.h" + +namespace OHOS { +namespace CryptoFramework { +class SymKeyGeneratorImpl : public OHOS::FFI::FFIData { + DECL_TYPE(SymKeyGeneratorImpl, OHOS::FFI::FFIData) +public: + explicit SymKeyGeneratorImpl(HcfSymKeyGenerator *generator); + ~SymKeyGeneratorImpl(); + const char *GetAlgName(int32_t* errCode); + HcfResult GenerateSymKey(HcfSymKey **symKey); + HcfResult ConvertKey(const HcfBlob key, HcfSymKey **symKey); + +private: + HcfSymKeyGenerator *generator_; +}; +} +} + +#endif diff --git a/frameworks/cj/src/symkey_impl.h b/frameworks/cj/include/sym_key_impl.h similarity index 92% rename from frameworks/cj/src/symkey_impl.h rename to frameworks/cj/include/sym_key_impl.h index f125b014612774fb1ca855c5d2fbf32df11b4100..b3effdeb86be0d46cd787dafd9ddde7f085f35ba 100644 --- a/frameworks/cj/src/symkey_impl.h +++ b/frameworks/cj/include/sym_key_impl.h @@ -1,35 +1,37 @@ -/* - * 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 SYMKEY_IMPL_H -#define SYMKEY_IMPL_H - -#include "ffi_remote_data.h" -#include "sym_key.h" -#include "key_impl.h" - -namespace OHOS { -namespace CryptoFramework { -class SymKeyImpl : public KeyImpl { - DECL_TYPE(SymKeyImpl, OHOS::FFI::FFIData) -public: - explicit SymKeyImpl(HcfSymKey *symKey); - ~SymKeyImpl() override; - HcfSymKey *GetSymKey() const; - void ClearMem(); -}; -} -} - -#endif +/* + * 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 SYM_KEY_IMPL_H +#define SYM_KEY_IMPL_H + +#include "ffi_remote_data.h" +#include "sym_key.h" +#include "key_impl.h" +#include "result.h" +#include "log.h" + +namespace OHOS { +namespace CryptoFramework { +class SymKeyImpl : public KeyImpl { + DECL_TYPE(SymKeyImpl, OHOS::FFI::FFIData) +public: + explicit SymKeyImpl(HcfSymKey *symKey); + ~SymKeyImpl() override; + HcfSymKey *GetSymKey() const; + void ClearMem(); +}; +} +} + +#endif diff --git a/frameworks/cj/include/verify_impl.h b/frameworks/cj/include/verify_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..14b5b03d42cc3e26e3e6ddd786f0ea85949e4ff0 --- /dev/null +++ b/frameworks/cj/include/verify_impl.h @@ -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 VERIFY_IMPL_H +#define VERIFY_IMPL_H + +#include "ffi_remote_data.h" +#include "pub_key.h" +#include "signature.h" + +namespace OHOS { +namespace CryptoFramework { +class VerifyImpl : public OHOS::FFI::FFIData { + DECL_TYPE(VerifyImpl, OHOS::FFI::FFIData) +public: + explicit VerifyImpl(HcfVerify *verify); + ~VerifyImpl(); + HcfVerify *GetVerify(); + HcfResult Init(HcfPubKey *pubKey); + HcfResult Update(HcfBlob *input); + bool Verify(HcfBlob *data, HcfBlob signatureData, int32_t *errCode); + HcfResult Recover(HcfBlob input, HcfBlob *output); + HcfResult SetVerifySpecByNum(int32_t itemValue); + HcfResult SetVerifySpecByArr(HcfBlob itemValue); + HcfResult GetVerifySpecString(SignSpecItem item, char *itemValue); + HcfResult GetVerifySpecNum(SignSpecItem item, int32_t *itemValue); +private: + HcfVerify *verify_ = nullptr; +}; +} +} +#endif \ No newline at end of file diff --git a/frameworks/cj/src/crypto_utils.cpp b/frameworks/cj/src/asy_key_generator_impl.cpp similarity index 61% rename from frameworks/cj/src/crypto_utils.cpp rename to frameworks/cj/src/asy_key_generator_impl.cpp index 9a6ca6302f255686f75abdf8112954118a019955..2e6663991a8cf75559dfc5dbf3a9a7f82b13065a 100644 --- a/frameworks/cj/src/crypto_utils.cpp +++ b/frameworks/cj/src/asy_key_generator_impl.cpp @@ -1,28 +1,34 @@ -/* - * 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 "crypto_utils.h" - -char* Utils::MallocCString(const std::string& origin) -{ - if (origin.empty()) { - return nullptr; - } - auto len = origin.length() + 1; - char* res = static_cast(malloc(sizeof(char) * len)); - if (res == nullptr) { - return nullptr; - } - return std::char_traits::copy(res, origin.c_str(), len); +/* + * 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 "asy_key_generator_impl.h" + +namespace OHOS { +namespace CryptoFramework { +AsyKeyGeneratorImpl::AsyKeyGeneratorImpl(HcfAsyKeyGenerator *generator) +{ + this->generator_ = generator; +} + +AsyKeyGeneratorImpl::~AsyKeyGeneratorImpl() +{ + HcfObjDestroy(this->generator_); +} + +HcfAsyKeyGenerator *AsyKeyGeneratorImpl::GetAsyKeyGenerator() +{ + return this->generator_; +} +} } \ No newline at end of file diff --git a/frameworks/cj/src/asy_key_spec_generator_impl.cpp b/frameworks/cj/src/asy_key_spec_generator_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d8bd7d85bd19ed63655182eddc89726c19a5b3b1 --- /dev/null +++ b/frameworks/cj/src/asy_key_spec_generator_impl.cpp @@ -0,0 +1,34 @@ +/* + * 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 "asy_key_spec_generator_impl.h" + +namespace OHOS { +namespace CryptoFramework { +AsyKeyGeneratorBySpecImpl::AsyKeyGeneratorBySpecImpl(HcfAsyKeyGeneratorBySpec *generator) +{ + this->generator_ = generator; +} + +AsyKeyGeneratorBySpecImpl::~AsyKeyGeneratorBySpecImpl() +{ + HcfObjDestroy(this->generator_); +} + +HcfAsyKeyGeneratorBySpec *AsyKeyGeneratorBySpecImpl::GetAsyKeyGeneratorBySpec() +{ + return this->generator_; +} +} +} \ No newline at end of file diff --git a/frameworks/cj/src/cipher_impl.cpp b/frameworks/cj/src/cipher_impl.cpp index 0ac176138aa0cc5d129caae9679082248186b461..1ff866085f2f40cc4013c53ad0984442b5fdb178 100644 --- a/frameworks/cj/src/cipher_impl.cpp +++ b/frameworks/cj/src/cipher_impl.cpp @@ -1,102 +1,99 @@ -/* - * 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 "cipher_impl.h" -#include "log.h" - -namespace OHOS { - namespace CryptoFramework { - CipherImpl::CipherImpl(HcfCipher *cipher) - { - cipher_ = cipher; - } - - CipherImpl::~CipherImpl() - { - HcfObjDestroy(this->cipher_); - } - - HcfResult CipherImpl::CipherInit(HcfCryptoMode opMode, HcfKey *key, HcfParamsSpec *params) - { - if (cipher_ == nullptr) { - LOGE("fail to get cipher obj!"); - return HCF_ERR_MALLOC; - } - HcfResult res = cipher_->init(cipher_, opMode, key, params); - return res; - } - - HcfResult CipherImpl::CipherUpdate(HcfBlob *input, HcfBlob *output) - { - if (cipher_ == nullptr) { - LOGE("fail to get cipher obj!"); - return HCF_ERR_MALLOC; - } - HcfResult res = cipher_->update(cipher_, input, output); - return res; - } - - HcfResult CipherImpl::CipherDoFinal(HcfBlob *input, HcfBlob *output) - { - if (cipher_ == nullptr) { - LOGE("fail to get cipher obj!"); - return HCF_ERR_MALLOC; - } - HcfResult res = cipher_->doFinal(cipher_, input, output); - return res; - } - - HcfResult CipherImpl::SetCipherSpec(CipherSpecItem item, HcfBlob pSource) - { - if (cipher_ == nullptr) { - LOGE("fail to get cipher obj!"); - return HCF_ERR_MALLOC; - } - HcfResult res = cipher_->setCipherSpecUint8Array(cipher_, item, pSource); - return res; - } - - HcfResult CipherImpl::GetCipherSpecString(CipherSpecItem item, char **returnString) - { - if (cipher_ == nullptr) { - LOGE("fail to get cipher obj!"); - return HCF_ERR_MALLOC; - } - HcfResult res = cipher_->getCipherSpecString(cipher_, item, returnString); - return res; - } - - HcfResult CipherImpl::GetCipherSpecUint8Array(CipherSpecItem item, HcfBlob *returnUint8Array) - { - if (cipher_ == nullptr) { - LOGE("fail to get cipher obj!"); - return HCF_ERR_MALLOC; - } - HcfResult res = cipher_->getCipherSpecUint8Array(cipher_, item, returnUint8Array); - return res; - } - - const char *CipherImpl::GetAlgorithm(int32_t* errCode) - { - if (cipher_ == nullptr) { - LOGE("fail to get cipher obj!"); - *errCode = HCF_ERR_MALLOC; - return nullptr; - } - const char *algo = cipher_->getAlgorithm(cipher_); - *errCode = HCF_SUCCESS; - return algo; - } - } +/* + * 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 "cipher_impl.h" +#include "log.h" + +namespace OHOS { + namespace CryptoFramework { + CipherImpl::CipherImpl(HcfCipher *cipher) + { + cipher_ = cipher; + } + + CipherImpl::~CipherImpl() + { + HcfObjDestroy(this->cipher_); + } + + HcfResult CipherImpl::CipherInit(HcfCryptoMode opMode, HcfKey *key, HcfParamsSpec *params) + { + if (cipher_ == nullptr) { + LOGE("fail to get cipher obj!"); + return HCF_ERR_MALLOC; + } + HcfResult res = cipher_->init(cipher_, opMode, key, params); + return res; + } + + HcfResult CipherImpl::CipherUpdate(HcfBlob *input, HcfBlob *output) + { + if (cipher_ == nullptr) { + LOGE("fail to get cipher obj!"); + return HCF_ERR_MALLOC; + } + HcfResult res = cipher_->update(cipher_, input, output); + return res; + } + + HcfResult CipherImpl::CipherDoFinal(HcfBlob *input, HcfBlob *output) + { + if (cipher_ == nullptr) { + LOGE("fail to get cipher obj!"); + return HCF_ERR_MALLOC; + } + HcfResult res = cipher_->doFinal(cipher_, input, output); + return res; + } + + HcfResult CipherImpl::SetCipherSpec(CipherSpecItem item, HcfBlob pSource) + { + if (cipher_ == nullptr) { + LOGE("fail to get cipher obj!"); + return HCF_INVALID_PARAMS; + } + return cipher_->setCipherSpecUint8Array(cipher_, item, pSource); + } + + HcfResult CipherImpl::GetCipherSpecString(CipherSpecItem item, char *returnString) + { + if (cipher_ == nullptr) { + LOGE("fail to get cipher obj!"); + return HCF_INVALID_PARAMS; + } + return cipher_->getCipherSpecString(cipher_, item, &returnString); + } + + HcfResult CipherImpl::GetCipherSpecUint8Array(CipherSpecItem item, HcfBlob *returnUint8Array) + { + if (cipher_ == nullptr) { + LOGE("fail to get cipher obj!"); + return HCF_INVALID_PARAMS; + } + return cipher_->getCipherSpecUint8Array(cipher_, item, returnUint8Array); + } + + const char *CipherImpl::GetAlgorithm(int32_t* errCode) + { + if (cipher_ == nullptr) { + LOGE("fail to get cipher obj!"); + *errCode = HCF_ERR_MALLOC; + return nullptr; + } + const char *algo = cipher_->getAlgorithm(cipher_); + *errCode = HCF_SUCCESS; + return algo; + } + } } \ No newline at end of file diff --git a/frameworks/cj/src/crypto_ffi.cpp b/frameworks/cj/src/crypto_ffi.cpp index ca2e02ae7928f71432847f6be5dfc49d68898b96..dd618492bdaf25a366f4e249d900885cd540145d 100644 --- a/frameworks/cj/src/crypto_ffi.cpp +++ b/frameworks/cj/src/crypto_ffi.cpp @@ -1,727 +1,1817 @@ -/* - * 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 "crypto_ffi.h" -#include "random_impl.h" -#include "mac_impl.h" -#include "md_impl.h" -#include "log.h" -#include "sign_impl.h" -#include "symkey_generator_impl.h" -#include "symkey_impl.h" -#include "cipher_impl.h" -#include "detailed_iv_params.h" -#include "detailed_gcm_params.h" -#include "detailed_ccm_params.h" -#include "securec.h" - -#define MAX_MEMORY_SIZE (5 * 1024 * 1024) - -using namespace OHOS::FFI; - -namespace OHOS { - namespace CryptoFramework { - extern "C" { - //-------------------random - int64_t FfiOHOSCreateRandom(int32_t* errCode) - { - LOGD("[Random] CreateRandom start"); - HcfRand *randObj = nullptr; - HcfResult res = HcfRandCreate(&randObj); - *errCode = static_cast(res); - if (res != HCF_SUCCESS) { - LOGE("create c randObj failed."); - return 0; - } - auto native = FFIData::Create(randObj); - if (!native) { - LOGE("[Random] CreateRandom failed"); - HcfObjDestroy(randObj); - *errCode = HCF_ERR_MALLOC; - return 0; - } - LOGD("[Randome] CreateRandom success"); - return native->GetID(); - } - - const char *FfiOHOSRandomGetAlgName(int64_t id, int32_t* errCode) - { - LOGD("[Random] GetAlgName start"); - auto instance = FFIData::GetData(id); - if (!instance) { - LOGE("[Random] instance not exist."); - *errCode = HCF_ERR_MALLOC; - return nullptr; - } - const char* res = instance->GetAlgName(errCode); - LOGD("[Randome] GetAlgName success"); - return res; - } - - HcfBlob FfiOHOSGenerateRandom(int64_t id, int32_t numBytes, int32_t* errCode) - { - LOGD("[Random] GenerateRandom start"); - HcfBlob randBlob; - auto instance = FFIData::GetData(id); - if (!instance) { - LOGE("[Random] instance not exist."); - *errCode = HCF_ERR_MALLOC; - return randBlob; - } - randBlob = instance->GenerateRandom(numBytes, errCode); - LOGD("[Randome] GenerateRandom success"); - return randBlob; - } - - void FfiOHOSSetSeed(int64_t id, HcfBlob *seed, int32_t* errCode) - { - LOGD("[Random] SetSeed start"); - auto instance = FFIData::GetData(id); - if (!instance) { - LOGE("[Random] instance not exist."); - *errCode = HCF_ERR_MALLOC; - return; - } - instance->SetSeed(seed, errCode); - LOGD("[Randome] SetSeed success"); - } - - //--------------------- md - int64_t FfiOHOSCreateMd(char* algName, int32_t* errCode) - { - LOGD("[Md] CreateMd start"); - HcfMd *mdObj = nullptr; - HcfResult res = HcfMdCreate(algName, &mdObj); - *errCode = static_cast(res); - if (res != HCF_SUCCESS) { - LOGE("create c mdObj failed."); - return 0; - } - auto native = FFIData::Create(mdObj); - if (!native) { - LOGE("[Md] CreateMd failed"); - HcfObjDestroy(mdObj); - *errCode = HCF_ERR_MALLOC; - return 0; - } - LOGD("[Md] CreateMd success"); - return native->GetID(); - } - - int32_t FfiOHOSMdUpdate(int64_t id, HcfBlob *input) - { - LOGD("[Md] FfiOHOSMdUpdate start"); - HcfResult res = HCF_ERR_MALLOC; - auto instance = FFIData::GetData(id); - if (!instance) { - LOGE("[Md] instance not exist."); - return res; - } - res = instance->MdUpdate(input); - LOGD("[Md] FfiOHOSMdUpdate success"); - return res; - } - - HcfBlob FfiOHOSDigest(int64_t id, int32_t* errCode) - { - LOGD("[Md] FfiOHOSDigest start"); - auto instance = FFIData::GetData(id); - HcfBlob blob = { .data = nullptr, .len = 0}; - if (!instance) { - LOGE("[Md] instance not exist."); - *errCode = HCF_ERR_MALLOC; - return blob; - } - HcfResult res = instance->MdDoFinal(&blob); - *errCode = static_cast(res); - if (res != HCF_SUCCESS) { - LOGE("doFinal failed!"); - return blob; - } - LOGD("[Md] FfiOHOSDigest success"); - return blob; - } - - uint32_t FfiOHOSGetMdLength(int64_t id, int32_t* errCode) - { - LOGD("[Md] FfiOHOSGetMdLength start"); - auto instance = FFIData::GetData(id); - uint32_t res = 0; - if (!instance) { - LOGE("[Md] instance not exist."); - *errCode = HCF_ERR_MALLOC; - return res; - } - res = instance->GetMdLength(errCode); - LOGD("[Md] FfiOHOSGetMdLength success"); - return res; - } - - //-------------------symkeygenerator - int64_t FfiOHOSCreateSymKeyGenerator(char* algName, int32_t* errCode) - { - LOGD("[SymKeyGenerator] CreateSymKeyGenerator start"); - HcfSymKeyGenerator *generator = nullptr; - HcfResult res = HcfSymKeyGeneratorCreate(algName, &generator); - *errCode = static_cast(res); - if (res != HCF_SUCCESS) { - LOGE("create C generator fail."); - return 0; - } - auto native = FFIData::Create(generator); - if (native == nullptr) { - LOGE("[SymKeyGenerator] CreateSymKeyGenerator failed"); - HcfObjDestroy(generator); - *errCode = HCF_ERR_MALLOC; - return 0; - } - LOGD("[SymKeyGenerator] CreateSymKeyGenerator success"); - return native->GetID(); - } - - const char* FfiOHOSSymKeyGeneratorGetAlgName(int64_t id, int32_t* errCode) - { - LOGD("[SymKeyGenerator] GetAlgName start"); - auto instance = FFIData::GetData(id); - if (!instance) { - LOGE("[SymKeyGenerator] instance not exist."); - *errCode = HCF_ERR_MALLOC; - return nullptr; - } - const char* res = instance->GetAlgName(errCode); - LOGD("[SymKeyGenerator] GetAlgName success"); - return res; - } - - int64_t FfiOHOSGenerateSymKey(int64_t id, int32_t* errCode) - { - LOGD("[SymKeyGenerator] GenerateSymKey start"); - auto instance = FFIData::GetData(id); - if (!instance) { - LOGE("[SymKeyGenerator] instance not exist."); - *errCode = HCF_ERR_MALLOC; - return 0; - } - HcfSymKey *key = nullptr; - HcfResult res = instance->GenerateSymKey(&key); - *errCode = static_cast(res); - if (res != HCF_SUCCESS) { - LOGE("generate sym key failed."); - return 0; - } - auto native = FFIData::Create(key); - if (native == nullptr) { - LOGE("[SymKeyGenerator] GenerateSymKey failed"); - HcfObjDestroy(key); - *errCode = HCF_ERR_MALLOC; - return 0; - } - LOGD("[SymKeyGenerator] GenerateSymKey success"); - return native->GetID(); - } - - int64_t FfiOHOSConvertKey(int64_t id, HcfBlob *key, int32_t* errCode) - { - LOGD("[SymKeyGenerator] ConvertKey start"); - auto instance = FFIData::GetData(id); - if (!instance) { - LOGE("[SymKeyGenerator] instance not exist."); - *errCode = HCF_ERR_MALLOC; - return 0; - } - HcfSymKey *symkey = nullptr; - HcfResult res = instance->ConvertKey(*key, &symkey); - *errCode = static_cast(res); - if (res != HCF_SUCCESS) { - LOGE("generate sym key failed."); - return 0; - } - auto native = FFIData::Create(symkey); - if (native == nullptr) { - LOGE("[SymKeyGenerator] ConvertKey failed"); - HcfObjDestroy(key); - *errCode = HCF_ERR_MALLOC; - return 0; - } - LOGD("[SymKeyGenerator] ConvertKey success"); - return native->GetID(); - } - - //-------------------symkey - const char *FfiOHOSSymKeyGetAlgName(int64_t id, int32_t* errCode) - { - LOGD("[SymKey] GetAlgName start"); - auto instance = FFIData::GetData(id); - if (!instance) { - LOGE("[SymKey] instance not exist."); - *errCode = HCF_ERR_MALLOC; - return nullptr; - } - const char* res = instance->GetAlgorithm(errCode); - LOGD("[SymKey] GetAlgName success"); - return res; - } - - const char *FfiOHOSSymKeyGetFormat(int64_t id, int32_t* errCode) - { - LOGD("[SymKey] GetFormat start"); - auto instance = FFIData::GetData(id); - if (!instance) { - LOGE("[SymKey] instance not exist."); - *errCode = HCF_ERR_MALLOC; - return nullptr; - } - const char* res = instance->GetFormat(errCode); - LOGD("[SymKey] GetFormat success"); - return res; - } - - int32_t FfiOHOSSymKeyGetEncoded(int64_t id, HcfBlob *returnBlob) - { - LOGD("[SymKey] GetEncoded start"); - auto instance = FFIData::GetData(id); - if (!instance) { - LOGE("[SymKey] instance not exist."); - return HCF_ERR_MALLOC; - } - HcfResult res = instance->GetEncoded(returnBlob); - LOGD("[SymKey] GetEncoded success"); - return res; - } - - void FfiOHOSClearMem(int64_t id) - { - LOGD("[SymKey] ClearMem start"); - auto instance = FFIData::GetData(id); - if (!instance) { - LOGE("[SymKey] instance not exist."); - return; - } - instance->ClearMem(); - LOGD("[SymKey] ClearMem success"); - } - - void* FfiOHOSSymKeyGetHcfKey(int64_t id) - { - LOGD("[SymKey] GetHcfKey start"); - auto instance = FFIData::GetData(id); - if (!instance) { - LOGE("[SymKey] instance not exist."); - return nullptr; - } - HcfKey *key = instance->GetHcfKey(); - LOGD("[SymKey] GetHcfKey success"); - return key; - } - - // cipher - const std::string IV_PARAMS_SPEC = "IvParamsSpec"; - const std::string GCM_PARAMS_SPEC = "GcmParamsSpec"; - const std::string CCM_PARAMS_SPEC = "CcmParamsSpec"; - const size_t GCM_AUTH_TAG_LEN = 16; - const size_t CCM_AUTH_TAG_LEN = 12; - static const char *GetIvParamsSpecType() - { - return IV_PARAMS_SPEC.c_str(); - } - - static const char *GetGcmParamsSpecType() - { - return GCM_PARAMS_SPEC.c_str(); - } - - static const char *GetCcmParamsSpecType() - { - return CCM_PARAMS_SPEC.c_str(); - } - - void *HcfMalloc(uint32_t size, char val) - { - if ((size == 0) || (size > MAX_MEMORY_SIZE)) { - LOGE("malloc size is invalid"); - return nullptr; - } - void *addr = malloc(size); - if (addr != nullptr) { - (void)memset_s(addr, size, val, size); - } - return addr; - } - - void HcfFree(void *addr) - { - if (addr != nullptr) { - free(addr); - } - } - - int64_t FfiOHOSCreateCipher(char* transformation, int32_t* errCode) - { - LOGD("[Cipher] CreateCipher start"); - HcfCipher *cipher = nullptr; - HcfResult res = HcfCipherCreate(transformation, &cipher); - *errCode = static_cast(res); - if (res != HCF_SUCCESS) { - LOGE("create C cipher fail!"); - return 0; - } - auto native = FFIData::Create(cipher); - if (native == nullptr) { - LOGE("[Cipher] CreateCipher failed"); - HcfObjDestroy(cipher); - *errCode = HCF_ERR_MALLOC; - return 0; - } - LOGD("[Cipher] CreateCipher success"); - return native->GetID(); - } - - int32_t FfiOHOSCipherInitByIv(int64_t id, int32_t opMode, void* key, HcfBlob blob1) - { - LOGD("[Cipher] FfiOHOSCipherInitByIv start"); - if (key == nullptr) { - LOGE("[Cipher] key can not be nullptr."); - return HCF_INVALID_PARAMS; - } - auto instance = FFIData::GetData(id); - if (!instance) { - LOGE("[Cipher] instance not exist."); - return HCF_ERR_MALLOC; - } - HcfIvParamsSpec *ivParamsSpec = reinterpret_cast( - HcfMalloc(sizeof(HcfIvParamsSpec), 0)); - if (ivParamsSpec == nullptr) { - LOGE("ivParamsSpec malloc failed!"); - return HCF_INVALID_PARAMS; - } - ivParamsSpec->base.getType = GetIvParamsSpecType; - ivParamsSpec->iv = blob1; - HcfCryptoMode mode = HcfCryptoMode(opMode); - HcfParamsSpec *paramsSpec = reinterpret_cast(ivParamsSpec); - ivParamsSpec = nullptr; - HcfResult res = instance->CipherInit(mode, static_cast(key), paramsSpec); - HcfFree(paramsSpec); - paramsSpec = nullptr; - LOGD("[Cipher] FfiOHOSCipherInitByIv success"); - return res; - } - - int32_t FfiOHOSCipherInitByGcm(int64_t id, int32_t opMode, void* key, CParamsSpec spec) - { - LOGD("[Cipher] FfiOHOSCipherInitByGcm start"); - if (key == nullptr) { - LOGE("[Cipher] key can not be nullptr."); - return HCF_INVALID_PARAMS; - } - auto instance = FFIData::GetData(id); - if (!instance) { - LOGE("[Cipher] instance not exist."); - return HCF_ERR_MALLOC; - } - HcfGcmParamsSpec *gcmParamsSpec = reinterpret_cast( - HcfMalloc(sizeof(HcfGcmParamsSpec), 0)); - if (gcmParamsSpec == nullptr) { - LOGE("gcmParamsSpec malloc failed!"); - return HCF_INVALID_PARAMS; - } - HcfCryptoMode mode = HcfCryptoMode(opMode); - HcfBlob authTag = {}; - if (mode == DECRYPT_MODE) { - gcmParamsSpec->tag = spec.authTag; - } else if (mode == ENCRYPT_MODE) { - authTag.data = static_cast(HcfMalloc(GCM_AUTH_TAG_LEN, 0)); - if (authTag.data == nullptr) { - HcfFree(gcmParamsSpec); - return HCF_INVALID_PARAMS; - } - authTag.len = GCM_AUTH_TAG_LEN; - gcmParamsSpec->tag = authTag; - } - gcmParamsSpec->base.getType = GetGcmParamsSpecType; - gcmParamsSpec->iv = spec.iv; - gcmParamsSpec->aad = spec.add; - HcfParamsSpec *paramsSpec = reinterpret_cast(gcmParamsSpec); - gcmParamsSpec = nullptr; - HcfResult res = instance->CipherInit(mode, static_cast(key), paramsSpec); - HcfBlobDataFree(&authTag); - HcfFree(paramsSpec); - paramsSpec = nullptr; - LOGD("[Cipher] FfiOHOSCipherInitByGcm success"); - return res; - } - - int32_t FfiOHOSCipherInitByCcm(int64_t id, int32_t opMode, void* key, CParamsSpec spec) - { - LOGD("[Cipher] FfiOHOSCipherInitByCcm start"); - if (key == nullptr) { - LOGE("[Cipher] key can not be nullptr."); - return HCF_INVALID_PARAMS; - } - auto instance = FFIData::GetData(id); - if (!instance) { - LOGE("[Cipher] instance not exist."); - return HCF_ERR_MALLOC; - } - HcfCcmParamsSpec *ccmParamsSpec = reinterpret_cast( - HcfMalloc(sizeof(HcfCcmParamsSpec), 0)); - if (ccmParamsSpec == nullptr) { - LOGE("ccmParamsSpec malloc failed!"); - return HCF_INVALID_PARAMS; - } - HcfBlob authTag = {}; - HcfCryptoMode mode = HcfCryptoMode(opMode); - if (mode == DECRYPT_MODE) { - ccmParamsSpec->tag = spec.authTag; - } else if (mode == ENCRYPT_MODE) { - authTag.data = static_cast(HcfMalloc(CCM_AUTH_TAG_LEN, 0)); - if (authTag.data == nullptr) { - HcfFree(ccmParamsSpec); - return HCF_INVALID_PARAMS; - } - authTag.len = CCM_AUTH_TAG_LEN; - ccmParamsSpec->tag = authTag; - } - ccmParamsSpec->base.getType = GetCcmParamsSpecType; - ccmParamsSpec->iv = spec.iv; - ccmParamsSpec->aad = spec.add; - HcfParamsSpec *paramsSpec = reinterpret_cast(ccmParamsSpec); - ccmParamsSpec = nullptr; - HcfResult res = instance->CipherInit(mode, static_cast(key), paramsSpec); - HcfBlobDataFree(&authTag); - HcfFree(paramsSpec); - paramsSpec = nullptr; - LOGD("[Cipher] FfiOHOSCipherInitByCcm success"); - return res; - } - - int32_t FfiOHOSCipherInitWithOutParams(int64_t id, int32_t opMode, void* key) - { - LOGD("[Cipher] FfiOHOSCipherInitWithOutParams start"); - if (key == nullptr) { - LOGE("[Cipher] key can not be nullptr."); - return HCF_INVALID_PARAMS; - } - auto instance = FFIData::GetData(id); - if (!instance) { - LOGE("[Cipher] instance not exist."); - return HCF_ERR_MALLOC; - } - HcfParamsSpec *paramsSpec = nullptr; - HcfCryptoMode mode = HcfCryptoMode(opMode); - HcfResult res = instance->CipherInit(mode, static_cast(key), paramsSpec); - LOGD("[Cipher] FfiOHOSCipherInitWithOutParams success"); - return res; - } - - int32_t FfiOHOSCipherUpdate(int64_t id, HcfBlob *input, HcfBlob *output) - { - LOGD("[Cipher] CipherUpdate start"); - auto instance = FFIData::GetData(id); - if (!instance) { - LOGE("[Cipher] instance not exist."); - return HCF_ERR_MALLOC; - } - HcfResult res = instance->CipherUpdate(input, output); - LOGD("[Cipher] CipherUpdate success"); - return res; - } - - int32_t FfiOHOSCipherDoFinal(int64_t id, HcfBlob *input, HcfBlob *output) - { - LOGD("[Cipher] CipherDoFinal start"); - auto instance = FFIData::GetData(id); - if (!instance) { - LOGE("[Cipher] instance not exist."); - return HCF_ERR_MALLOC; - } - HcfResult res = instance->CipherDoFinal(input, output); - LOGD("[Cipher] CipherDoFinal success %{public}d", res); - return res; - } - - int32_t FfiOHOSSetCipherSpec(int64_t id, int32_t item, HcfBlob pSource) - { - LOGD("[Cipher] SetCipherSpec start"); - auto instance = FFIData::GetData(id); - if (!instance) { - LOGE("[Cipher] instance not exist."); - return HCF_ERR_MALLOC; - } - CipherSpecItem csi = CipherSpecItem(item); - HcfResult res = instance->SetCipherSpec(csi, pSource); - LOGD("[Cipher] SetCipherSpec success"); - return res; - } - - int32_t FfiOHOSGetCipherSpecString(int64_t id, int32_t item, char **returnString) - { - LOGD("[Cipher] GetCipherSpecString start"); - auto instance = FFIData::GetData(id); - if (!instance) { - LOGE("[Cipher] instance not exist."); - return HCF_ERR_MALLOC; - } - CipherSpecItem csi = CipherSpecItem(item); - HcfResult res = instance->GetCipherSpecString(csi, returnString); - LOGD("[Cipher] GetCipherSpecString success"); - return res; - } - - int32_t FfiOHOSGetCipherSpecUint8Array(int64_t id, int32_t item, HcfBlob *returnUint8Array) - { - LOGD("[Cipher] GetCipherSpecUint8Array start"); - auto instance = FFIData::GetData(id); - if (!instance) { - LOGE("[Cipher] instance not exist."); - return HCF_ERR_MALLOC; - } - CipherSpecItem csi = CipherSpecItem(item); - HcfResult res = instance->GetCipherSpecUint8Array(csi, returnUint8Array); - LOGD("[Cipher] GetCipherSpecUint8Array success"); - return res; - } - - const char *FfiOHOSCipherGetAlgName(int64_t id, int32_t* errCode) - { - LOGD("[Cipher] GetAlgName start"); - auto instance = FFIData::GetData(id); - if (!instance) { - LOGE("[SymKey] instance not exist."); - *errCode = HCF_ERR_MALLOC; - return nullptr; - } - const char* res = instance->GetAlgorithm(errCode); - LOGD("[Cipher] GetAlgName success"); - return res; - } - - //--------------------- mac - int64_t FFiOHOSCryptoMacConstructor(char* algName, int32_t* errCode) - { - LOGD("[Mac] CreateMac start"); - HcfMac *macObj = nullptr; - HcfResult res = HcfMacCreate(algName, &macObj); - *errCode = static_cast(res); - if (res != HCF_SUCCESS) { - LOGE("create c macObj failed."); - return 0; - } - auto native = FFIData::Create(macObj); - if (native == nullptr) { - LOGE("[Mac] CreateMac failed"); - HcfObjDestroy(macObj); - *errCode = HCF_ERR_MALLOC; - return 0; - } - LOGD("[Mac] CreateMac success"); - return native->GetID(); - } - - int32_t FfiOHOSCryptoMacInit(int64_t id, int64_t symKeyId) - { - LOGD("[MAC] FfiOHOSCryptoMacInit start"); - auto instance = FFIData::GetData(id); - if (!instance) { - LOGE("[MAC] MacImpl instance not exist."); - return HCF_ERR_MALLOC; - } - - auto keyInstance = FFIData::GetData(symKeyId); - if (!instance) { - LOGE("[MAC] SymKeyImpl instance not exist."); - return HCF_ERR_MALLOC; - } - - HcfResult res = instance->MacInit(keyInstance->GetSymKey()); - if (res != HCF_SUCCESS) { - LOGE("[MAC] MacInit error %{public}d", res); - } else { - LOGD("[MAC] FfiOHOSCryptoMacInit success"); - } - - return res; - } - - int32_t FfiOHOSCryptoMacUpdate(int64_t id, HcfBlob *input) - { - LOGD("[Mac] FfiOHOSCryptoMacUpdate start"); - HcfResult res = HCF_ERR_MALLOC; - auto instance = FFIData::GetData(id); - if (!instance) { - LOGE("[Mac] instance not exist."); - return res; - } - res = instance->MacUpdate(input); - LOGD("[Mac] FfiOHOSCryptoMacUpdate success"); - return res; - } - - HcfBlob FfiOHOSCryptoMacDoFinal(int64_t id, int32_t* errCode) - { - LOGD("[Mac] FfiOHOSCryptoMacDoFinal start"); - auto instance = FFIData::GetData(id); - HcfBlob blob = { .data = nullptr, .len = 0}; - if (!instance) { - LOGE("[Mac] instance not exist."); - *errCode = HCF_ERR_MALLOC; - return blob; - } - HcfResult res = instance->MacDoFinal(&blob); - *errCode = static_cast(res); - if (res != HCF_SUCCESS) { - LOGE("doFinal failed!"); - return blob; - } - LOGD("[Mac] FfiOHOSCryptoMacDoFinal success"); - return blob; - } - - uint32_t FfiOHOSGCryptoGetMacLength(int64_t id) - { - LOGD("[Mac] FfiOHOSGCryptoGetMacLength start"); - auto instance = FFIData::GetData(id); - uint32_t res = 0; - if (!instance) { - LOGE("[Mac] instance not exist."); - return res; - } - res = instance->GetMacLength(); - LOGD("[Mac] FfiOHOSGCryptoGetMacLength success"); - return res; - } - - //--------------------- sign - int64_t FFiOHOSCryptoSignConstructor(char* algName, int32_t* errCode) - { - LOGD("[Sign] CreateSign start"); - HcfSign *signObj = nullptr; - HcfResult res = HcfSignCreate(algName, &signObj); - *errCode = static_cast(res); - if (res != HCF_SUCCESS) { - LOGE("create c signObj failed."); - return 0; - } - auto native = FFIData::Create(signObj); - if (native == nullptr) { - LOGE("[Sign] CreateSign failed"); - HcfObjDestroy(signObj); - *errCode = HCF_ERR_MALLOC; - return 0; - } - LOGD("[Sign] CreateSign success"); - return native->GetID(); - } - } - } // namespace CryptoFramework +/* + * 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 "crypto_ffi.h" + +#define MAX_MEMORY_SIZE (5 * 1024 * 1024) + +using namespace OHOS::FFI; + +namespace OHOS { + namespace CryptoFramework { + extern "C" { + //-------------------random + int64_t FfiOHOSCreateRandom(int32_t* errCode) + { + LOGD("[Random] CreateRandom start"); + HcfRand *randObj = nullptr; + HcfResult res = HcfRandCreate(&randObj); + *errCode = static_cast(res); + if (res != HCF_SUCCESS) { + LOGE("create c randObj failed."); + return 0; + } + auto native = FFIData::Create(randObj); + if (!native) { + LOGE("[Random] CreateRandom failed"); + HcfObjDestroy(randObj); + *errCode = HCF_ERR_MALLOC; + return 0; + } + LOGD("[Randome] CreateRandom success"); + return native->GetID(); + } + + const char *FfiOHOSRandomGetAlgName(int64_t id, int32_t* errCode) + { + LOGD("[Random] GetAlgName start"); + auto instance = FFIData::GetData(id); + if (!instance) { + LOGE("[Random] instance not exist."); + *errCode = HCF_ERR_MALLOC; + return nullptr; + } + const char* res = instance->GetAlgName(errCode); + LOGD("[Randome] GetAlgName success"); + return res; + } + + HcfBlob FfiOHOSGenerateRandom(int64_t id, int32_t numBytes, int32_t* errCode) + { + LOGD("[Random] GenerateRandom start"); + HcfBlob randBlob; + auto instance = FFIData::GetData(id); + if (!instance) { + LOGE("[Random] instance not exist."); + *errCode = HCF_ERR_MALLOC; + return randBlob; + } + randBlob = instance->GenerateRandom(numBytes, errCode); + LOGD("[Randome] GenerateRandom success"); + return randBlob; + } + + void FfiOHOSSetSeed(int64_t id, HcfBlob *seed, int32_t* errCode) + { + LOGD("[Random] SetSeed start"); + auto instance = FFIData::GetData(id); + if (!instance) { + LOGE("[Random] instance not exist."); + *errCode = HCF_ERR_MALLOC; + return; + } + instance->SetSeed(seed, errCode); + LOGD("[Randome] SetSeed success"); + } + + //--------------------- md + int64_t FfiOHOSCreateMd(char* algName, int32_t* errCode) + { + LOGD("[Md] CreateMd start"); + HcfMd *mdObj = nullptr; + HcfResult res = HcfMdCreate(algName, &mdObj); + *errCode = static_cast(res); + if (res != HCF_SUCCESS) { + LOGE("create c mdObj failed."); + return 0; + } + auto native = FFIData::Create(mdObj); + if (!native) { + LOGE("[Md] CreateMd failed"); + HcfObjDestroy(mdObj); + *errCode = HCF_ERR_MALLOC; + return 0; + } + LOGD("[Md] CreateMd success"); + return native->GetID(); + } + + int32_t FfiOHOSMdUpdate(int64_t id, HcfBlob *input) + { + LOGD("[Md] FfiOHOSMdUpdate start"); + HcfResult res = HCF_ERR_MALLOC; + auto instance = FFIData::GetData(id); + if (!instance) { + LOGE("[Md] instance not exist."); + return res; + } + res = instance->MdUpdate(input); + LOGD("[Md] FfiOHOSMdUpdate success"); + return res; + } + + HcfBlob FfiOHOSDigest(int64_t id, int32_t* errCode) + { + LOGD("[Md] FfiOHOSDigest start"); + auto instance = FFIData::GetData(id); + HcfBlob blob = { .data = nullptr, .len = 0}; + if (!instance) { + LOGE("[Md] instance not exist."); + *errCode = HCF_ERR_MALLOC; + return blob; + } + HcfResult res = instance->MdDoFinal(&blob); + *errCode = static_cast(res); + if (res != HCF_SUCCESS) { + LOGE("doFinal failed!"); + return blob; + } + LOGD("[Md] FfiOHOSDigest success"); + return blob; + } + + uint32_t FfiOHOSGetMdLength(int64_t id, int32_t* errCode) + { + LOGD("[Md] FfiOHOSGetMdLength start"); + auto instance = FFIData::GetData(id); + uint32_t res = 0; + if (!instance) { + LOGE("[Md] instance not exist."); + *errCode = HCF_ERR_MALLOC; + return res; + } + res = instance->GetMdLength(errCode); + LOGD("[Md] FfiOHOSGetMdLength success"); + return res; + } + + //-------------------symkeygenerator + int64_t FfiOHOSCreateSymKeyGenerator(char* algName, int32_t* errCode) + { + LOGD("[SymKeyGenerator] CreateSymKeyGenerator start"); + HcfSymKeyGenerator *generator = nullptr; + HcfResult res = HcfSymKeyGeneratorCreate(algName, &generator); + *errCode = static_cast(res); + if (res != HCF_SUCCESS) { + LOGE("create C generator fail."); + return 0; + } + auto native = FFIData::Create(generator); + if (native == nullptr) { + LOGE("[SymKeyGenerator] CreateSymKeyGenerator failed"); + HcfObjDestroy(generator); + *errCode = HCF_ERR_MALLOC; + return 0; + } + LOGD("[SymKeyGenerator] CreateSymKeyGenerator success"); + return native->GetID(); + } + + const char* FfiOHOSSymKeyGeneratorGetAlgName(int64_t id, int32_t* errCode) + { + LOGD("[SymKeyGenerator] GetAlgName start"); + auto instance = FFIData::GetData(id); + if (!instance) { + LOGE("[SymKeyGenerator] instance not exist."); + *errCode = HCF_ERR_MALLOC; + return nullptr; + } + const char* res = instance->GetAlgName(errCode); + LOGD("[SymKeyGenerator] GetAlgName success"); + return res; + } + + int64_t FfiOHOSGenerateSymKey(int64_t id, int32_t* errCode) + { + LOGD("[SymKeyGenerator] GenerateSymKey start"); + auto instance = FFIData::GetData(id); + if (!instance) { + LOGE("[SymKeyGenerator] instance not exist."); + *errCode = HCF_ERR_MALLOC; + return 0; + } + HcfSymKey *key = nullptr; + HcfResult res = instance->GenerateSymKey(&key); + *errCode = static_cast(res); + if (res != HCF_SUCCESS) { + LOGE("generate sym key failed."); + return 0; + } + auto native = FFIData::Create(key); + if (native == nullptr) { + LOGE("[SymKeyGenerator] GenerateSymKey failed"); + HcfObjDestroy(key); + *errCode = HCF_ERR_MALLOC; + return 0; + } + LOGD("[SymKeyGenerator] GenerateSymKey success"); + return native->GetID(); + } + + int64_t FfiOHOSConvertKey(int64_t id, HcfBlob *key, int32_t* errCode) + { + LOGD("[SymKeyGenerator] ConvertKey start"); + auto instance = FFIData::GetData(id); + if (!instance) { + LOGE("[SymKeyGenerator] instance not exist."); + *errCode = HCF_ERR_MALLOC; + return 0; + } + HcfSymKey *symkey = nullptr; + HcfResult res = instance->ConvertKey(*key, &symkey); + *errCode = static_cast(res); + if (res != HCF_SUCCESS) { + LOGE("generate sym key failed."); + return 0; + } + auto native = FFIData::Create(symkey); + if (native == nullptr) { + LOGE("[SymKeyGenerator] ConvertKey failed"); + HcfObjDestroy(key); + *errCode = HCF_ERR_MALLOC; + return 0; + } + LOGD("[SymKeyGenerator] ConvertKey success"); + return native->GetID(); + } + + //-------------------symkey + const char *FfiOHOSSymKeyGetAlgName(int64_t id, int32_t* errCode) + { + LOGD("[SymKey] GetAlgName start"); + auto instance = FFIData::GetData(id); + if (!instance) { + LOGE("[SymKey] instance not exist."); + *errCode = HCF_ERR_MALLOC; + return nullptr; + } + const char* res = instance->GetAlgorithm(errCode); + LOGD("[SymKey] GetAlgName success"); + return res; + } + + const char *FfiOHOSSymKeyGetFormat(int64_t id, int32_t* errCode) + { + LOGD("[SymKey] GetFormat start"); + auto instance = FFIData::GetData(id); + if (!instance) { + LOGE("[SymKey] instance not exist."); + *errCode = HCF_ERR_MALLOC; + return nullptr; + } + const char* res = instance->GetFormat(errCode); + LOGD("[SymKey] GetFormat success"); + return res; + } + + int32_t FfiOHOSSymKeyGetEncoded(int64_t id, HcfBlob *returnBlob) + { + LOGD("[SymKey] GetEncoded start"); + auto instance = FFIData::GetData(id); + if (!instance) { + LOGE("[SymKey] instance not exist."); + return HCF_ERR_MALLOC; + } + HcfResult res = instance->GetEncoded(returnBlob); + LOGD("[SymKey] GetEncoded success"); + return res; + } + + void FfiOHOSClearMem(int64_t id) + { + LOGD("[SymKey] ClearMem start"); + auto instance = FFIData::GetData(id); + if (!instance) { + LOGE("[SymKey] instance not exist."); + return; + } + instance->ClearMem(); + LOGD("[SymKey] ClearMem success"); + } + + void* FfiOHOSSymKeyGetHcfKey(int64_t id) + { + LOGD("[SymKey] GetHcfKey start"); + auto instance = FFIData::GetData(id); + if (!instance) { + LOGE("[SymKey] instance not exist."); + return nullptr; + } + HcfKey *key = instance->GetHcfKey(); + LOGD("[SymKey] GetHcfKey success"); + return key; + } + + // cipher + const std::string IV_PARAMS_SPEC = "IvParamsSpec"; + const std::string GCM_PARAMS_SPEC = "GcmParamsSpec"; + const std::string CCM_PARAMS_SPEC = "CcmParamsSpec"; + const size_t GCM_AUTH_TAG_LEN = 16; + const size_t CCM_AUTH_TAG_LEN = 12; + static const char *GetIvParamsSpecType() + { + return IV_PARAMS_SPEC.c_str(); + } + + static const char *GetGcmParamsSpecType() + { + return GCM_PARAMS_SPEC.c_str(); + } + + static const char *GetCcmParamsSpecType() + { + return CCM_PARAMS_SPEC.c_str(); + } + + void *HcfMalloc(uint32_t size, char val) + { + if ((size == 0) || (size > MAX_MEMORY_SIZE)) { + LOGE("malloc size is invalid"); + return nullptr; + } + void *addr = malloc(size); + if (addr != nullptr) { + (void)memset_s(addr, size, val, size); + } + return addr; + } + + void HcfFree(void *addr) + { + if (addr != nullptr) { + free(addr); + } + } + + int64_t FfiOHOSCreateCipher(char* transformation, int32_t* errCode) + { + LOGD("[Cipher] CreateCipher start"); + HcfCipher *cipher = nullptr; + HcfResult res = HcfCipherCreate(transformation, &cipher); + *errCode = static_cast(res); + if (res != HCF_SUCCESS) { + LOGE("create C cipher fail!"); + return 0; + } + auto native = FFIData::Create(cipher); + if (native == nullptr) { + LOGE("[Cipher] CreateCipher failed"); + HcfObjDestroy(cipher); + *errCode = HCF_ERR_MALLOC; + return 0; + } + LOGD("[Cipher] CreateCipher success"); + return native->GetID(); + } + + int32_t FfiOHOSCipherInitByIv(int64_t id, int32_t opMode, void* key, HcfBlob blob1) + { + LOGD("[Cipher] FfiOHOSCipherInitByIv start"); + if (key == nullptr) { + LOGE("[Cipher] key can not be nullptr."); + return HCF_INVALID_PARAMS; + } + auto instance = FFIData::GetData(id); + if (!instance) { + LOGE("[Cipher] instance not exist."); + return HCF_ERR_MALLOC; + } + HcfIvParamsSpec *ivParamsSpec = reinterpret_cast( + HcfMalloc(sizeof(HcfIvParamsSpec), 0)); + if (ivParamsSpec == nullptr) { + LOGE("ivParamsSpec malloc failed!"); + return HCF_INVALID_PARAMS; + } + ivParamsSpec->base.getType = GetIvParamsSpecType; + ivParamsSpec->iv = blob1; + HcfCryptoMode mode = HcfCryptoMode(opMode); + HcfParamsSpec *paramsSpec = reinterpret_cast(ivParamsSpec); + ivParamsSpec = nullptr; + HcfResult res = instance->CipherInit(mode, static_cast(key), paramsSpec); + HcfFree(paramsSpec); + paramsSpec = nullptr; + LOGD("[Cipher] FfiOHOSCipherInitByIv success"); + return res; + } + + int32_t FfiOHOSCipherInitByGcm(int64_t id, int32_t opMode, void* key, CParamsSpec spec) + { + LOGD("[Cipher] FfiOHOSCipherInitByGcm start"); + if (key == nullptr) { + LOGE("[Cipher] key can not be nullptr."); + return HCF_INVALID_PARAMS; + } + auto instance = FFIData::GetData(id); + if (!instance) { + LOGE("[Cipher] instance not exist."); + return HCF_ERR_MALLOC; + } + HcfGcmParamsSpec *gcmParamsSpec = reinterpret_cast( + HcfMalloc(sizeof(HcfGcmParamsSpec), 0)); + if (gcmParamsSpec == nullptr) { + LOGE("gcmParamsSpec malloc failed!"); + return HCF_INVALID_PARAMS; + } + HcfCryptoMode mode = HcfCryptoMode(opMode); + HcfBlob authTag = {}; + if (mode == DECRYPT_MODE) { + gcmParamsSpec->tag = spec.authTag; + } else if (mode == ENCRYPT_MODE) { + authTag.data = static_cast(HcfMalloc(GCM_AUTH_TAG_LEN, 0)); + if (authTag.data == nullptr) { + HcfFree(gcmParamsSpec); + return HCF_INVALID_PARAMS; + } + authTag.len = GCM_AUTH_TAG_LEN; + gcmParamsSpec->tag = authTag; + } + gcmParamsSpec->base.getType = GetGcmParamsSpecType; + gcmParamsSpec->iv = spec.iv; + gcmParamsSpec->aad = spec.add; + HcfParamsSpec *paramsSpec = reinterpret_cast(gcmParamsSpec); + gcmParamsSpec = nullptr; + HcfResult res = instance->CipherInit(mode, static_cast(key), paramsSpec); + HcfBlobDataFree(&authTag); + HcfFree(paramsSpec); + paramsSpec = nullptr; + LOGD("[Cipher] FfiOHOSCipherInitByGcm success"); + return res; + } + + int32_t FfiOHOSCipherInitByCcm(int64_t id, int32_t opMode, void* key, CParamsSpec spec) + { + LOGD("[Cipher] FfiOHOSCipherInitByCcm start"); + if (key == nullptr) { + LOGE("[Cipher] key can not be nullptr."); + return HCF_INVALID_PARAMS; + } + auto instance = FFIData::GetData(id); + if (!instance) { + LOGE("[Cipher] instance not exist."); + return HCF_ERR_MALLOC; + } + HcfCcmParamsSpec *ccmParamsSpec = reinterpret_cast( + HcfMalloc(sizeof(HcfCcmParamsSpec), 0)); + if (ccmParamsSpec == nullptr) { + LOGE("ccmParamsSpec malloc failed!"); + return HCF_INVALID_PARAMS; + } + HcfBlob authTag = {}; + HcfCryptoMode mode = HcfCryptoMode(opMode); + if (mode == DECRYPT_MODE) { + ccmParamsSpec->tag = spec.authTag; + } else if (mode == ENCRYPT_MODE) { + authTag.data = static_cast(HcfMalloc(CCM_AUTH_TAG_LEN, 0)); + if (authTag.data == nullptr) { + HcfFree(ccmParamsSpec); + return HCF_INVALID_PARAMS; + } + authTag.len = CCM_AUTH_TAG_LEN; + ccmParamsSpec->tag = authTag; + } + ccmParamsSpec->base.getType = GetCcmParamsSpecType; + ccmParamsSpec->iv = spec.iv; + ccmParamsSpec->aad = spec.add; + HcfParamsSpec *paramsSpec = reinterpret_cast(ccmParamsSpec); + ccmParamsSpec = nullptr; + HcfResult res = instance->CipherInit(mode, static_cast(key), paramsSpec); + HcfBlobDataFree(&authTag); + HcfFree(paramsSpec); + paramsSpec = nullptr; + LOGD("[Cipher] FfiOHOSCipherInitByCcm success"); + return res; + } + + int32_t FfiOHOSCipherInitWithOutParams(int64_t id, int32_t opMode, void* key) + { + LOGD("[Cipher] FfiOHOSCipherInitWithOutParams start"); + if (key == nullptr) { + LOGE("[Cipher] key can not be nullptr."); + return HCF_INVALID_PARAMS; + } + auto instance = FFIData::GetData(id); + if (!instance) { + LOGE("[Cipher] instance not exist."); + return HCF_ERR_MALLOC; + } + HcfParamsSpec *paramsSpec = nullptr; + HcfCryptoMode mode = HcfCryptoMode(opMode); + HcfResult res = instance->CipherInit(mode, static_cast(key), paramsSpec); + LOGD("[Cipher] FfiOHOSCipherInitWithOutParams success"); + return res; + } + + int32_t FfiOHOSCipherUpdate(int64_t id, HcfBlob *input, HcfBlob *output) + { + LOGD("[Cipher] CipherUpdate start"); + auto instance = FFIData::GetData(id); + if (!instance) { + LOGE("[Cipher] instance not exist."); + return HCF_ERR_MALLOC; + } + HcfResult res = instance->CipherUpdate(input, output); + LOGD("[Cipher] CipherUpdate success"); + return res; + } + + int32_t FfiOHOSCipherDoFinal(int64_t id, HcfBlob *input, HcfBlob *output) + { + LOGD("[Cipher] CipherDoFinal start"); + auto instance = FFIData::GetData(id); + if (!instance) { + LOGE("[Cipher] instance not exist."); + return HCF_ERR_MALLOC; + } + HcfResult res = instance->CipherDoFinal(input, output); + LOGD("[Cipher] CipherDoFinal success %{public}d", res); + return res; + } + + int32_t FfiOHOSSetCipherSpec(int64_t id, int32_t item, HcfBlob pSource) + { + LOGD("[Cipher] SetCipherSpec start"); + auto instance = FFIData::GetData(id); + if (!instance) { + LOGE("[Cipher] instance not exist."); + return HCF_ERR_MALLOC; + } + CipherSpecItem csi = CipherSpecItem(item); + HcfResult res = instance->SetCipherSpec(csi, pSource); + LOGD("[Cipher] SetCipherSpec success"); + return res; + } + + int32_t FfiOHOSGetCipherSpecString(int64_t id, int32_t item, char *returnString) + { + LOGD("[Cipher] GetCipherSpecString start"); + auto instance = FFIData::GetData(id); + if (!instance) { + LOGE("[Cipher] instance not exist."); + return HCF_ERR_MALLOC; + } + CipherSpecItem csi = CipherSpecItem(item); + HcfResult res = instance->GetCipherSpecString(csi, returnString); + LOGD("[Cipher] GetCipherSpecString success"); + return res; + } + + int32_t FfiOHOSGetCipherSpecUint8Array(int64_t id, int32_t item, HcfBlob *returnUint8Array) + { + LOGD("[Cipher] GetCipherSpecUint8Array start"); + auto instance = FFIData::GetData(id); + if (!instance) { + LOGE("[Cipher] instance not exist."); + return HCF_ERR_MALLOC; + } + CipherSpecItem csi = CipherSpecItem(item); + HcfResult res = instance->GetCipherSpecUint8Array(csi, returnUint8Array); + LOGD("[Cipher] GetCipherSpecUint8Array success"); + return res; + } + + const char *FfiOHOSCipherGetAlgName(int64_t id, int32_t* errCode) + { + LOGD("[Cipher] GetAlgName start"); + auto instance = FFIData::GetData(id); + if (!instance) { + LOGE("[SymKey] instance not exist."); + *errCode = HCF_ERR_MALLOC; + return nullptr; + } + const char* res = instance->GetAlgorithm(errCode); + LOGD("[Cipher] GetAlgName success"); + return res; + } + + //--------------------- mac + int64_t FFiOHOSCryptoMacConstructor(char* algName, int32_t* errCode) + { + LOGD("[Mac] CreateMac start"); + HcfMac *macObj = nullptr; + HcfResult res = HcfMacCreate(algName, &macObj); + *errCode = static_cast(res); + if (res != HCF_SUCCESS) { + LOGE("create c macObj failed."); + return 0; + } + auto native = FFIData::Create(macObj); + if (native == nullptr) { + LOGE("[Mac] CreateMac failed"); + HcfObjDestroy(macObj); + *errCode = HCF_ERR_MALLOC; + return 0; + } + LOGD("[Mac] CreateMac success"); + return native->GetID(); + } + + int32_t FfiOHOSCryptoMacInit(int64_t id, int64_t symKeyId) + { + LOGD("[MAC] FfiOHOSCryptoMacInit start"); + auto instance = FFIData::GetData(id); + if (!instance) { + LOGE("[MAC] MacImpl instance not exist."); + return HCF_ERR_MALLOC; + } + + auto keyInstance = FFIData::GetData(symKeyId); + if (!instance) { + LOGE("[MAC] SymKeyImpl instance not exist."); + return HCF_ERR_MALLOC; + } + + HcfResult res = instance->MacInit(keyInstance->GetSymKey()); + if (res != HCF_SUCCESS) { + LOGE("[MAC] MacInit error %{public}d", res); + } else { + LOGD("[MAC] FfiOHOSCryptoMacInit success"); + } + + return res; + } + + int32_t FfiOHOSCryptoMacUpdate(int64_t id, HcfBlob *input) + { + LOGD("[Mac] FfiOHOSCryptoMacUpdate start"); + HcfResult res = HCF_ERR_MALLOC; + auto instance = FFIData::GetData(id); + if (!instance) { + LOGE("[Mac] instance not exist."); + return res; + } + res = instance->MacUpdate(input); + LOGD("[Mac] FfiOHOSCryptoMacUpdate success"); + return res; + } + + HcfBlob FfiOHOSCryptoMacDoFinal(int64_t id, int32_t* errCode) + { + LOGD("[Mac] FfiOHOSCryptoMacDoFinal start"); + auto instance = FFIData::GetData(id); + HcfBlob blob = { .data = nullptr, .len = 0}; + if (!instance) { + LOGE("[Mac] instance not exist."); + *errCode = HCF_ERR_MALLOC; + return blob; + } + HcfResult res = instance->MacDoFinal(&blob); + *errCode = static_cast(res); + if (res != HCF_SUCCESS) { + LOGE("doFinal failed!"); + return blob; + } + LOGD("[Mac] FfiOHOSCryptoMacDoFinal success"); + return blob; + } + + uint32_t FfiOHOSCryptoGetMacLength(int64_t id) + { + LOGD("[Mac] FfiOHOSGCryptoGetMacLength start"); + auto instance = FFIData::GetData(id); + uint32_t res = 0; + if (!instance) { + LOGE("[Mac] instance not exist."); + return res; + } + res = instance->GetMacLength(); + LOGD("[Mac] FfiOHOSGCryptoGetMacLength success"); + return res; + } + + //--------------------- sign + int64_t FFiOHOSCryptoSignConstructor(char* algName, int32_t* errCode) + { + LOGD("[Sign] FFiOHOSCryptoSignConstructor start"); + HcfSign *signObj = nullptr; + HcfResult res = HcfSignCreate(algName, &signObj); + *errCode = static_cast(res); + if (res != HCF_SUCCESS) { + LOGE("[Sign] FFiOHOSCryptoSignConstructor create c signObj failed."); + return 0; + } + auto native = FFIData::Create(signObj); + if (native == nullptr) { + LOGE("[Sign] FFiOHOSCryptoSignConstructor create failed"); + HcfObjDestroy(signObj); + *errCode = HCF_ERR_MALLOC; + return 0; + } + LOGD("[Sign] FFiOHOSCryptoSignConstructor success"); + return native->GetID(); + } + + int32_t FFiOHOSSignInit(int64_t sid, int64_t pid) + { + LOGD("[Sign] FFiOHOSSignInit start"); + auto sign = FFIData::GetData(sid); + if (sign == nullptr) { + LOGE("[Sign] FFiOHOSSignInit failed to get sign obj."); + return HCF_INVALID_PARAMS; + } + auto priKeyImpl = FFIData::GetData(pid); + if (priKeyImpl == nullptr) { + LOGE("[Sign] FFiOHOSSignInit failed to get priKeyImpl obj."); + return HCF_INVALID_PARAMS; + } + HcfPriKey *priKey = priKeyImpl->GetPriKey(); + if (priKey == nullptr) { + LOGE("[Sign] FFiOHOSSignInit failed to get priKey obj."); + return HCF_INVALID_PARAMS; + } + LOGD("[Sign] FFiOHOSSignInit success"); + return sign->Init(priKey); + } + + int32_t FFiOHOSSignUpdate(int64_t id, HcfBlob input) + { + LOGD("[Sign] FFiOHOSSignUpdate start"); + auto sign = FFIData::GetData(id); + if (sign == nullptr) { + LOGE("[Sign] FFiOHOSSignUpdate failed to get sign obj."); + return HCF_INVALID_PARAMS; + } + LOGD("[Sign] FFiOHOSSignUpdate success"); + return sign->Update(&input); + } + + int32_t FFiOHOSSignSign(int64_t id, HcfBlob *input, HcfBlob *output) + { + LOGD("[Sign] FFiOHOSSignSign start"); + auto sign = FFIData::GetData(id); + if (sign == nullptr) { + LOGE("[Sign] FFiOHOSSignSign failed to get sign obj."); + return HCF_INVALID_PARAMS; + } + LOGD("[Sign] FFiOHOSSignSign success"); + return sign->Sign(input, output); + } + + int32_t FFiOHOSSignSetSignSpecByNum(int64_t id, int32_t itemValue) + { + LOGD("[Sign] FFiOHOSSignSetSignSpecByNum start"); + auto sign = FFIData::GetData(id); + if (sign == nullptr) { + LOGE("[Sign] FFiOHOSSignSetSignSpecByNum failed to get sign obj."); + return HCF_INVALID_PARAMS; + } + LOGD("[Sign] FFiOHOSSignSetSignSpecByNum success"); + return sign->SetSignSpecByNum(itemValue); + } + + int32_t FFiOHOSSignSetSignSpecByArr(int64_t id, HcfBlob itemValue) + { + LOGD("[Sign] FFiOHOSSignSetSignSpecByArr start"); + auto sign = FFIData::GetData(id); + if (sign == nullptr) { + LOGE("[Sign] FFiOHOSSignSetSignSpecByArr failed to get sign obj."); + return HCF_INVALID_PARAMS; + } + LOGD("[Sign] FFiOHOSSignSetSignSpecByArr success"); + return sign->SetSignSpecByArr(itemValue); + } + + int32_t FFiOHOSSignGetSignSpecString(int64_t id, SignSpecItem item, char *itemValue) + { + LOGD("[Sign] FFiOHOSSignGetSignSpecString start"); + auto sign = FFIData::GetData(id); + if (sign == nullptr) { + LOGE("[Sign] FFiOHOSSignGetSignSpecString failed to get sign obj."); + return HCF_INVALID_PARAMS; + } + LOGD("[Sign] FFiOHOSSignGetSignSpecString success"); + return sign->GetSignSpecString(item, itemValue); + } + + int32_t FFiOHOSSignGetSignSpecNum(int64_t id, SignSpecItem item, int32_t *itemValue) + { + LOGD("[Sign] FFiOHOSSignGetSignSpecNum start"); + auto sign = FFIData::GetData(id); + if (sign == nullptr) { + LOGE("[Sign] FFiOHOSSignGetSignSpecNum failed to get sign obj."); + return HCF_INVALID_PARAMS; + } + LOGD("[Sign] FFiOHOSSignGetSignSpecNum success"); + return sign->GetSignSpecNum(item, itemValue); + } + + //--------------------- verify + int64_t FFiOHOSVerifyConstructor(char* algName, int32_t* errCode) + { + LOGD("[Verify]FFiOHOSVerifyConstructor start"); + HcfVerify *verify = nullptr; + HcfResult res = HcfVerifyCreate(algName, &verify); + *errCode = static_cast(res); + if (res != HCF_SUCCESS) { + LOGE("[Verify] FFiOHOSVerifyConstructor create c verifyObj failed."); + return 0; + } + auto native = FFIData::Create(verify); + if (native == nullptr) { + LOGE("[Verify] FFiOHOSVerifyConstructor create failed"); + HcfObjDestroy(verify); + *errCode = HCF_ERR_MALLOC; + return 0; + } + LOGD("[Verify] FFiOHOSVerifyConstructor success"); + return native->GetID(); + } + + int32_t FFiOHOSVerifyInit(int64_t sid, int64_t pid) + { + LOGD("[Verify] FFiOHOSVerifyInit start"); + auto verify = FFIData::GetData(sid); + if (verify == nullptr) { + LOGE("[Verify] FFiOHOSVerifyInit failed to get verify obj."); + return HCF_INVALID_PARAMS; + } + auto pubKeyImpl = FFIData::GetData(pid); + if (pubKeyImpl == nullptr) { + LOGE("[Verify] FFiOHOSVerifyInit failed to get priKeyImpl obj."); + return HCF_INVALID_PARAMS; + } + HcfPubKey *pubKey = pubKeyImpl->GetPubKey(); + if (pubKey == nullptr) { + LOGE("[Verify] FFiOHOSVerifyInit failed to get priKey obj."); + return HCF_INVALID_PARAMS; + } + LOGD("[Verify] FFiOHOSVerifyInit success"); + return verify->Init(pubKey); + } + + int32_t FFiOHOSVerifyUpdate(int64_t id, HcfBlob input) + { + LOGD("[Verify] FFiOHOSVerifyUpdate start"); + auto verify = FFIData::GetData(id); + if (verify == nullptr) { + LOGE("[Verify] FFiOHOSVerifyUpdate failed to get verify obj."); + return HCF_INVALID_PARAMS; + } + LOGD("[Verify] FFiOHOSVerifyUpdate success"); + return verify->Update(&input); + } + + bool FFiOHOSVerifyVerify(int64_t id, HcfBlob *data, HcfBlob signatureData, int32_t* errCode) + { + LOGD("[Verify] FFiOHOSVerifyVerify start"); + auto verify = FFIData::GetData(id); + if (verify == nullptr) { + LOGE("[Verify] FFiOHOSVerifyVerify failed to get verify obj."); + return HCF_INVALID_PARAMS; + } + LOGD("[Verify] FFiOHOSVerifyVerify success"); + return verify->Verify(data, signatureData, errCode); + } + + int32_t FFiOHOSVerifyRecover(int64_t id, HcfBlob input, HcfBlob *output) + { + LOGD("[Verify] FFiOHOSVerifyRecover start"); + auto verify = FFIData::GetData(id); + if (verify == nullptr) { + LOGE("[Verify] FFiOHOSVerifyVerify failed to get verify obj."); + return HCF_INVALID_PARAMS; + } + LOGD("[Verify] FFiOHOSVerifyRecover success"); + return verify->Recover(input, output); + } + + + int32_t FFiOHOSVerifySetVerifySpecByNum(int64_t id, int32_t itemValue) + { + LOGD("[Verify] FFiOHOSVerifySetVerifySpecByNum start"); + auto verify = FFIData::GetData(id); + if (verify == nullptr) { + LOGE("[Verify] FFiOHOSVerifySetVerifySpecByNum failed to get verify obj."); + return HCF_INVALID_PARAMS; + } + LOGD("[Verify] FFiOHOSVerifySetVerifySpecByNum success"); + return verify->SetVerifySpecByNum(itemValue); + } + + int32_t FFiOHOSVerifySetVerifySpecByArr(int64_t id, HcfBlob itemValue) + { + LOGD("[Verify] FFiOHOSVerifySetVerifySpecByArr start"); + auto verify = FFIData::GetData(id); + if (verify == nullptr) { + LOGE("[Verify] FFiOHOSVerifySetVerifySpecByArr failed to get verify obj."); + return HCF_INVALID_PARAMS; + } + LOGD("[Verify] FFiOHOSVerifySetVerifySpecByArr success"); + return verify->SetVerifySpecByArr(itemValue); + } + + int32_t FFiOHOSVerifyGetVerifySpecString(int64_t id, SignSpecItem item, char *itemValue) + { + LOGD("[Verify] FFiOHOSVerifyGetVerifySpecString start"); + auto verify = FFIData::GetData(id); + if (verify == nullptr) { + LOGE("[Verify] FFiOHOSVerifyGetVerifySpecString failed to get verify obj."); + return HCF_INVALID_PARAMS; + } + LOGD("[Verify] FFiOHOSVerifyGetVerifySpecString success"); + return verify->GetVerifySpecString(item, itemValue); + } + + int32_t FFiOHOSVerifyGetVerifySpecNum(int64_t id, SignSpecItem item, int32_t *itemValue) + { + LOGD("[Verify] FFiOHOSVerifyGetVerifySpecNum start"); + auto verify = FFIData::GetData(id); + if (verify == nullptr) { + LOGE("[Verify] FFiOHOSVerifyGetVerifySpecNum failed to get verify obj."); + return HCF_INVALID_PARAMS; + } + LOGD("[Verify] FFiOHOSVerifyGetVerifySpecNum success"); + return verify->GetVerifySpecNum(item, itemValue); + } + + //--------------------- asykeygenerator + int64_t FFiOHOSAsyKeyGeneratorConstructor(char *algName, int32_t *errCode) + { + LOGD("[AsyKeyGenerator] FFiOHOSAsyKeyGeneratorConstructor start"); + HcfAsyKeyGenerator *generator = nullptr; + *errCode = HcfAsyKeyGeneratorCreate(algName, &generator); + if (*errCode != HCF_SUCCESS) { + *errCode = HCF_INVALID_PARAMS; + LOGE("create c generator fail."); + return 0; + } + auto instance = FFIData::Create(generator); + if (!instance) { + *errCode = HCF_ERR_MALLOC; + HcfObjDestroy(generator); + LOGE("new asy key generator failed"); + return 0; + } + LOGD("[AsyKeyGenerator] FFiOHOSAsyKeyGeneratorConstructor end"); + return instance->GetID(); + } + + int64_t FFiOHOSAsyKeyGeneratorGenerateKeyPair(int64_t id, int32_t *errCode) + { + LOGD("[AsyKeyGenerator] FFiOHOSAsyKeyGenerateKeyPair start"); + auto instance = FFIData::GetData(id); + if (!instance) { + *errCode = HCF_INVALID_PARAMS; + LOGE("build instance fail."); + return 0; + } + HcfAsyKeyGenerator *generator = instance->GetAsyKeyGenerator(); + if (generator == nullptr) { + *errCode = HCF_INVALID_PARAMS; + LOGE("build generator fail."); + return 0; + } + HcfKeyPair *returnKeyPair = nullptr; + HcfParamsSpec *params = nullptr; + *errCode = generator->generateKeyPair(generator, params, &returnKeyPair); + if (*errCode != HCF_SUCCESS) { + LOGD("generate key pair fail."); + return 0; + } + auto keyPair = FFIData::Create(returnKeyPair); + if (keyPair == nullptr) { + *errCode = HCF_ERR_MALLOC; + HcfObjDestroy(returnKeyPair); + LOGE("new key pair failed"); + return 0; + } + LOGD("[AsyKeyGenerator] FFiOHOSAsyKeyGenerateKeyPair end"); + return keyPair->GetID(); + } + + int64_t FFiOHOSAsyKeyGeneratorConvertKey(int64_t id, HcfBlob *pubKey, HcfBlob *priKey, int32_t *errCode) + { + LOGD("[AsyKeyGenerator] FFiOHOSAsyKeyConvertKey start"); + auto instance = FFIData::GetData(id); + if (!instance) { + *errCode = HCF_INVALID_PARAMS; + LOGE("build instance fail."); + return 0; + } + HcfAsyKeyGenerator *generator = instance->GetAsyKeyGenerator(); + if (generator == nullptr) { + *errCode = HCF_INVALID_PARAMS; + LOGE("build generator fail."); + return 0; + } + HcfKeyPair *returnKeyPair = nullptr; + HcfParamsSpec *params = nullptr; + *errCode = generator->convertKey(generator, params, pubKey, priKey, &returnKeyPair); + if (*errCode != HCF_SUCCESS) { + LOGD("convert key fail."); + return 0; + } + auto keyPair = FFIData::Create(returnKeyPair); + if (keyPair == nullptr) { + *errCode = HCF_ERR_MALLOC; + HcfObjDestroy(returnKeyPair); + LOGE("new key pair failed"); + return 0; + } + LOGD("[AsyKeyGenerator] FFiOHOSAsyKeyConvertKey end"); + return keyPair->GetID(); + } + + int64_t FFiOHOSAsyKeyGeneratorConvertPemKey(int64_t id, char *pubKey, char *priKey, int32_t *errCode) + { + LOGD("[AsyKeyGenerator] FFiOHOSAsyKeyConvertPemKey start"); + auto instance = FFIData::GetData(id); + if (!instance) { + *errCode = HCF_INVALID_PARAMS; + LOGE("build instance fail."); + return 0; + } + HcfAsyKeyGenerator *generator = instance->GetAsyKeyGenerator(); + if (generator == nullptr) { + *errCode = HCF_INVALID_PARAMS; + LOGE("build generator fail."); + return 0; + } + HcfKeyPair *returnKeyPair = nullptr; + HcfParamsSpec *params = nullptr; + *errCode = generator->convertPemKey(generator, params, pubKey, priKey, &returnKeyPair); + if (*errCode != HCF_SUCCESS) { + LOGE("ConvertPemKey fail."); + return 0; + } + auto keyPair = FFIData::Create(returnKeyPair); + if (keyPair == nullptr) { + *errCode = HCF_ERR_MALLOC; + HcfObjDestroy(returnKeyPair); + LOGE("new key pair failed"); + return 0; + } + LOGD("[AsyKeyGenerator] FFiOHOSAsyKeyConvertPemKey end"); + return keyPair->GetID(); + } + + //--------------------- asykeyspecgenerator + int64_t AsyKeyGeneratorBySpecConstructor(HcfAsyKeyParamsSpec *asyKeySpec, int32_t *errCode) + { + HcfAsyKeyGeneratorBySpec *generator = nullptr; + *errCode = HcfAsyKeyGeneratorBySpecCreate(asyKeySpec, &generator); + if (*errCode != HCF_SUCCESS) { + *errCode = HCF_INVALID_PARAMS; + LOGE("create C generator by sepc fail."); + return 0; + } + auto instance = FFIData::Create(generator); + if (!instance) { + *errCode = HCF_ERR_MALLOC; + HcfObjDestroy(generator); + LOGE("new asy key generator by spec failed!"); + return 0; + } + return instance->GetID(); + } + + int64_t FFiOHOSAsyKeyGeneratorByDsaCommonSpec(HcfDsaCommParamsSpec *spec, int32_t *errCode) + { + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorByDsaCommonSpec start"); + HcfAsyKeyParamsSpec *asyKeySpec = reinterpret_cast(spec); + int64_t id = AsyKeyGeneratorBySpecConstructor(asyKeySpec, errCode); + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorByDsaCommonSpec end"); + return id; + } + + int64_t FFiOHOSAsyKeyGeneratorByDsaPubKeySpec(HcfDsaPubKeyParamsSpec *spec, int32_t *errCode) + { + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorByDsaPubKeySpec start"); + HcfAsyKeyParamsSpec *asyKeySpec = reinterpret_cast(spec); + int64_t id = AsyKeyGeneratorBySpecConstructor(asyKeySpec, errCode); + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorByDsaPubKeySpec end"); + return id; + } + + int64_t FFiOHOSAsyKeyGeneratorByDsaKeyPairSpec(HcfDsaKeyPairParamsSpec *spec, int32_t *errCode) + { + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorByDsaKeyPairSpec start"); + HcfAsyKeyParamsSpec *asyKeySpec = reinterpret_cast(spec); + int64_t id = AsyKeyGeneratorBySpecConstructor(asyKeySpec, errCode); + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorByDsaKeyPairSpec end"); + return id; + } + + int64_t FFiOHOSAsyKeyGeneratorByEccCommonSpec(HcfEccCommParamsSpec *spec, int32_t *errCode) + { + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorByEccCommonSpec start"); + HcfAsyKeyParamsSpec *asyKeySpec = reinterpret_cast(spec); + int64_t id = AsyKeyGeneratorBySpecConstructor(asyKeySpec, errCode); + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorByEccCommonSpec end"); + return id; + } + + int64_t FFiOHOSAsyKeyGeneratorByEccPriKeySpec(HcfEccPriKeyParamsSpec *spec, int32_t *errCode) + { + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorByEccPriKeySpec start"); + HcfAsyKeyParamsSpec *asyKeySpec = reinterpret_cast(spec); + int64_t id = AsyKeyGeneratorBySpecConstructor(asyKeySpec, errCode); + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorByEccPriKeySpec end"); + return id; + } + + int64_t FFiOHOSAsyKeyGeneratorByEccPubKeySpec(HcfEccPubKeyParamsSpec *spec, int32_t *errCode) + { + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorByEccPubKeySpec start"); + HcfAsyKeyParamsSpec *asyKeySpec = reinterpret_cast(spec); + int64_t id = AsyKeyGeneratorBySpecConstructor(asyKeySpec, errCode); + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorByEccPubKeySpec end"); + return id; + } + + int64_t FFiOHOSAsyKeyGeneratorByEccKeyPairSpec(HcfEccKeyPairParamsSpec *spec, int32_t *errCode) + { + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorByEccKeyPairSpec start"); + HcfAsyKeyParamsSpec *asyKeySpec = reinterpret_cast(spec); + int64_t id = AsyKeyGeneratorBySpecConstructor(asyKeySpec, errCode); + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorByEccKeyPairSpec end"); + return id; + } + + int64_t FFiOHOSAsyKeyGeneratorByRsaPubKeySpec(HcfRsaPubKeyParamsSpec *spec, int32_t *errCode) + { + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorByRsaPubKeySpec start"); + HcfAsyKeyParamsSpec *asyKeySpec = reinterpret_cast(spec); + int64_t id = AsyKeyGeneratorBySpecConstructor(asyKeySpec, errCode); + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorByRsaPubKeySpec end"); + return id; + } + + int64_t FFiOHOSAsyKeyGeneratorByRsaKeyPairSpec(HcfRsaKeyPairParamsSpec *spec, int32_t *errCode) + { + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorByRsaKeyPairSpec start"); + HcfAsyKeyParamsSpec *asyKeySpec = reinterpret_cast(spec); + int64_t id = AsyKeyGeneratorBySpecConstructor(asyKeySpec, errCode); + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorByRsaKeyPairSpec end"); + return id; + } + + int64_t FFiOHOSAsyKeyGeneratorByAlg25519PriKeySpec(HcfAlg25519PriKeyParamsSpec *spec, int32_t *errCode) + { + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorByAlg25519PriKeySpec start"); + HcfAsyKeyParamsSpec *asyKeySpec = reinterpret_cast(spec); + int64_t id = AsyKeyGeneratorBySpecConstructor(asyKeySpec, errCode); + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorByAlg25519PriKeySpec end"); + return id; + } + + int64_t FFiOHOSAsyKeyGeneratorByAlg25519PubKeySpec(HcfAlg25519PubKeyParamsSpec *spec, int32_t *errCode) + { + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorByAlg25519PubKeySpec start"); + HcfAsyKeyParamsSpec *asyKeySpec = reinterpret_cast(spec); + int64_t id = AsyKeyGeneratorBySpecConstructor(asyKeySpec, errCode); + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorByAlg25519PubKeySpec end"); + return id; + } + + int64_t FFiOHOSAsyKeyGeneratorByAlg25519KeyPairSpec(HcfAlg25519KeyPairParamsSpec *spec, int32_t *errCode) + { + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorByAlg25519KeyPairSpec start"); + HcfAsyKeyParamsSpec *asyKeySpec = reinterpret_cast(spec); + int64_t id = AsyKeyGeneratorBySpecConstructor(asyKeySpec, errCode); + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorByAlg25519KeyPairSpec end"); + return id; + } + + int64_t FFiOHOSAsyKeyGeneratorByDhPriKeySpec(HcfDhPriKeyParamsSpec *spec, int32_t *errCode) + { + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorByDhPriKeySpec start"); + HcfAsyKeyParamsSpec *asyKeySpec = reinterpret_cast(spec); + int64_t id = AsyKeyGeneratorBySpecConstructor(asyKeySpec, errCode); + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorByDhPriKeySpec end"); + return id; + } + + int64_t FFiOHOSAsyKeyGeneratorByDhPubKeySpec(HcfDhPubKeyParamsSpec *spec, int32_t *errCode) + { + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorByDhPubKeySpec start"); + HcfAsyKeyParamsSpec *asyKeySpec = reinterpret_cast(spec); + int64_t id = AsyKeyGeneratorBySpecConstructor(asyKeySpec, errCode); + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorByDhPubKeySpec end"); + return id; + } + + int64_t FFiOHOSAsyKeyGeneratorByDhKeyPairSpec(HcfDhKeyPairParamsSpec *spec, int32_t *errCode) + { + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorByDhKeyPairSpec start"); + HcfAsyKeyParamsSpec *asyKeySpec = reinterpret_cast(spec); + int64_t id = AsyKeyGeneratorBySpecConstructor(asyKeySpec, errCode); + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorByDhKeyPairSpecc end"); + return id; + } + + int64_t FFiOHOSAsyKeyGeneratorByDhCommonSpec(HcfDhCommParamsSpec *spec, int32_t *errCode) + { + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorBytDhCommonSpec start"); + HcfAsyKeyParamsSpec *asyKeySpec = reinterpret_cast(spec); + int64_t id = AsyKeyGeneratorBySpecConstructor(asyKeySpec, errCode); + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorBytDhCommonSpec end"); + return id; + } + + int64_t FFiOHOSAsyKeyGeneratorBySpecGenerateKeyPair(int64_t id, int32_t *errCode) + { + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorBySpecGenerateKeyPair start"); + auto instance = FFIData::GetData(id); + if (!instance) { + *errCode = HCF_INVALID_PARAMS; + LOGE("build instance fail."); + return 0; + } + HcfAsyKeyGeneratorBySpec *generator = instance->GetAsyKeyGeneratorBySpec(); + if (generator == nullptr) { + *errCode = HCF_INVALID_PARAMS; + LOGE("build generator fail."); + return 0; + } + HcfKeyPair *returnKeyPair = nullptr; + *errCode = generator->generateKeyPair(generator, &returnKeyPair); + if (*errCode != HCF_SUCCESS) { + LOGD("generate key pair fail."); + return 0; + } + auto keyPair = FFIData::Create(returnKeyPair); + if (keyPair == nullptr) { + *errCode = HCF_ERR_MALLOC; + HcfObjDestroy(returnKeyPair); + LOGE("new key pair failed"); + return 0; + } + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorBySpecGenerateKeyPair end"); + return keyPair->GetID(); + } + + int64_t FFiOHOSAsyKeyGeneratorBySpecGeneratePriKey(int64_t id, int32_t *errCode) + { + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorBySpecGeneratePriKey start"); + auto instance = FFIData::GetData(id); + if (!instance) { + *errCode = HCF_INVALID_PARAMS; + LOGE("build instance fail."); + return 0; + } + HcfAsyKeyGeneratorBySpec *generator = instance->GetAsyKeyGeneratorBySpec(); + if (generator == nullptr) { + *errCode = HCF_INVALID_PARAMS; + LOGE("build generator fail."); + return 0; + } + HcfPriKey *returnPriKey = nullptr; + *errCode = generator->generatePriKey(generator, &returnPriKey); + if (*errCode != HCF_SUCCESS) { + LOGD("generate PriKey fail."); + return 0; + } + auto priKey = FFIData::Create(returnPriKey); + if (priKey == nullptr) { + *errCode = HCF_ERR_MALLOC; + HcfObjDestroy(returnPriKey); + LOGE("new pri key failed"); + return 0; + } + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorBySpecGeneratePriKey end"); + return priKey->GetID(); + } + + int64_t FFiOHOSAsyKeyGeneratorBySpecGeneratePubKey(int64_t id, int32_t *errCode) + { + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorBySpecGeneratePubKey start"); + auto instance = FFIData::GetData(id); + if (!instance) { + *errCode = HCF_INVALID_PARAMS; + LOGE("build instance fail."); + return 0; + } + HcfAsyKeyGeneratorBySpec *generator = instance->GetAsyKeyGeneratorBySpec(); + if (generator == nullptr) { + *errCode = HCF_INVALID_PARAMS; + LOGE("build generator fail."); + return 0; + } + HcfPubKey *returnPubKey = nullptr; + *errCode = generator->generatePubKey(generator, &returnPubKey); + if (*errCode != HCF_SUCCESS) { + LOGD("generate PubKey fail."); + return 0; + } + auto pubKey = FFIData::Create(returnPubKey); + if (pubKey == nullptr) { + *errCode = HCF_ERR_MALLOC; + HcfObjDestroy(returnPubKey); + LOGE("new pub key failed"); + return 0; + } + LOGD("[AsyKeyGeneratorBySpec] FFiOHOSAsyKeyGeneratorBySpecGeneratePubKey end"); + return pubKey->GetID(); + } + + //--------------------- prikey + HcfBlob FFiOHOSPriKeyGetEncoded(int64_t id, int32_t *errCode) + { + LOGD("[PriKey] FFiOHOSPriKeyGetEncoded start"); + HcfBlob ret = { .data = nullptr, .len = 0 }; + auto instance = FFIData::GetData(id); + if (!instance) { + LOGE("[PriKey] FFiOHOSPriKeyGetEncoded failed to unwrap private key obj!"); + *errCode = HCF_INVALID_PARAMS; + return ret; + } + HcfPriKey *priKey = instance->GetPriKey(); + if (priKey == nullptr) { + LOGE("[PriKey] FFiOHOSPriKeyGetEncoded failed to get private key obj!"); + *errCode = HCF_INVALID_PARAMS; + return ret; + } + *errCode = priKey->base.getEncoded(&priKey->base, &ret); + LOGD("[PriKey] FFiOHOSPriKeyGetEncoded end"); + return ret; + } + + HcfBlob FFiOHOSPriKeyGetEncodedDer(int64_t id, char *format, int32_t *errCode) + { + LOGD("[PriKey] FFiOHOSPriKeyGetEncodedDer start"); + HcfBlob ret = { .data = nullptr, .len = 0 }; + auto instance = FFIData::GetData(id); + if (!instance) { + LOGE("[PriKey] FFiOHOSPriKeyGetEncodedDer failed to unwrap private key obj!"); + *errCode = HCF_INVALID_PARAMS; + return ret; + } + HcfPriKey *priKey = instance->GetPriKey(); + if (priKey == nullptr) { + LOGE("[PriKey] FFiOHOSPriKeyGetEncodedDer failed to get private key obj!"); + *errCode = HCF_INVALID_PARAMS; + return ret; + } + *errCode = priKey->getEncodedDer(priKey, format, &ret); + LOGD("[PriKey] FFiOHOSPriKeyGetEncodedDer end"); + return ret; + } + + char *FFiOHOSPriKeyGetEncodedPem(int64_t id, char *format, int32_t *errCode) + { + LOGD("[PriKey] FFiOHOSPriKeyGetEncodedPem start"); + char *ret = nullptr; + auto instance = FFIData::GetData(id); + if (!instance) { + LOGE("[PriKey] FFiOHOSPriKeyGetEncodedPem failed to unwrap private key obj!"); + *errCode = HCF_INVALID_PARAMS; + return ret; + } + HcfPriKey *priKey = instance->GetPriKey(); + if (priKey == nullptr) { + LOGE("[PriKey] FFiOHOSPriKeyGetEncodedPem failed to get private key obj!"); + *errCode = HCF_INVALID_PARAMS; + return ret; + } + *errCode = priKey->base.getEncodedPem(&priKey->base, format, &ret); + LOGD("[PriKey] FFiOHOSPriKeyGetEncodedPem end"); + return ret; + } + + int32_t FFiOHOSPriKeyClearMem(int64_t id) + { + LOGD("[PriKey] FFiOHOSPriKeyClearMem start"); + auto instance = FFIData::GetData(id); + if (!instance) { + LOGE("[PriKey] FFiOHOSPriKeyClearMem failed to unwrap private key obj!"); + return HCF_INVALID_PARAMS; + } + HcfPriKey *priKey = instance->GetPriKey(); + if (priKey == nullptr) { + LOGE("[PriKey] FFiOHOSPriKeyClearMem failed to get private key obj!"); + return HCF_INVALID_PARAMS; + } + priKey->clearMem(priKey); + LOGD("[PriKey] FFiOHOSPriKeyClearMem end"); + return HCF_SUCCESS; + } + + int FFiOHOSPriKeyGetAsyKeySpecByNum(int64_t id, int32_t itemType, int32_t *errCode) + { + LOGD("[PriKey] FFiOHOSPriKeyGetAsyKeySpec start"); + auto instance = FFIData::GetData(id); + int ret = 0; + if (!instance) { + LOGE("[PriKey] FFiOHOSPriKeyGetAsyKeySpec failed to unwrap private key obj!"); + *errCode = HCF_INVALID_PARAMS; + return ret; + } + HcfPriKey *priKey = instance->GetPriKey(); + if (priKey == nullptr) { + LOGE("[PriKey] FFiOHOSPriKeyGetAsyKeySpec failed to get private key obj!"); + *errCode = HCF_INVALID_PARAMS; + return ret; + } + AsyKeySpecItem item = AsyKeySpecItem(itemType); + *errCode = priKey->getAsyKeySpecInt(priKey, item, &ret); + LOGD("[PriKey] FFiOHOSPriKeyGetAsyKeySpec end"); + return ret; + } + + char *FFiOHOSPriKeyGetAsyKeySpecByStr(int64_t id, int32_t itemType, int32_t *errCode) + { + LOGD("[PriKey] FFiOHOSPriKeyGetAsyKeySpec start"); + auto instance = FFIData::GetData(id); + char *ret = nullptr; + if (!instance) { + LOGE("[PriKey] FFiOHOSPriKeyGetAsyKeySpec failed to unwrap private key obj!"); + *errCode = HCF_INVALID_PARAMS; + return ret; + } + HcfPriKey *priKey = instance->GetPriKey(); + if (priKey == nullptr) { + LOGE("[PriKey] FFiOHOSPriKeyGetAsyKeySpec failed to get private key obj!"); + *errCode = HCF_INVALID_PARAMS; + return ret; + } + AsyKeySpecItem item = AsyKeySpecItem(itemType); + *errCode = priKey->getAsyKeySpecString(priKey, item, &ret); + LOGD("[PriKey] FFiOHOSPriKeyGetAsyKeySpec end"); + return ret; + } + + HcfBigInteger FFiOHOSPriKeyGetAsyKeySpecByBigInt(int64_t id, int32_t itemType, int32_t *errCode) + { + LOGD("[PriKey] FFiOHOSPriKeyGetAsyKeySpec start"); + auto instance = FFIData::GetData(id); + HcfBigInteger ret = { 0 }; + if (!instance) { + LOGE("[PriKey] FFiOHOSPriKeyGetAsyKeySpec failed to unwrap private key obj!"); + *errCode = HCF_INVALID_PARAMS; + return ret; + } + HcfPriKey *priKey = instance->GetPriKey(); + if (priKey == nullptr) { + LOGE("[PriKey] FFiOHOSPriKeyGetAsyKeySpec failed to get private key obj!"); + *errCode = HCF_INVALID_PARAMS; + return ret; + } + AsyKeySpecItem item = AsyKeySpecItem(itemType); + *errCode = priKey->getAsyKeySpecBigInteger(priKey, item, &ret); + LOGD("[PriKey] FFiOHOSPriKeyGetAsyKeySpec end"); + return ret; + } + + const char *FfiOHOSPriKeyGetFormat(int64_t id, int32_t* errCode) + { + LOGD("[PriKey] GetFormat start"); + auto instance = FFIData::GetData(id); + if (!instance) { + LOGE("[PriKey] instance not exist."); + *errCode = HCF_ERR_MALLOC; + return nullptr; + } + const char* res = instance->GetFormat(errCode); + LOGD("[PriKey] GetFormat success"); + return res; + } + + //--------------------- pubkey + HcfBlob FFiOHOSPubKeyGetEncoded(int64_t id, int32_t *errCode) + { + LOGD("[PubKey] FFiOHOSPubKeyGetEncoded start"); + HcfBlob ret = { .data = nullptr, .len = 0 }; + auto instance = FFIData::GetData(id); + if (!instance) { + LOGE("[PubKey] FFiOHOSPubKeyGetEncoded failed to unwrap public key obj!"); + *errCode = HCF_INVALID_PARAMS; + return ret; + } + HcfPubKey *pubKey = instance->GetPubKey(); + if (pubKey == nullptr) { + LOGE("[PubKey] FFiOHOSPubKeyGetEncoded failed to get public key obj!"); + *errCode = HCF_INVALID_PARAMS; + return ret; + } + *errCode = pubKey->base.getEncoded(&pubKey->base, &ret); + LOGD("[PubKey] FFiOHOSPubKeyGetEncoded end"); + return ret; + } + + HcfBlob FFiOHOSPubKeyGetEncodedDer(int64_t id, char *format, int32_t *errCode) + { + LOGD("[PubKey] FFiOHOSPubKeyGetEncodedDer start"); + HcfBlob ret = { .data = nullptr, .len = 0 }; + auto instance = FFIData::GetData(id); + if (!instance) { + LOGE("[PubKey] FFiOHOSPubKeyGetEncodedDer failed to unwrap public key obj!"); + *errCode = HCF_INVALID_PARAMS; + return ret; + } + HcfPubKey *pubKey = instance->GetPubKey(); + if (pubKey == nullptr) { + LOGE("[PubKey] FFiOHOSPubKeyGetEncodedDer failed to get public key obj!"); + *errCode = HCF_INVALID_PARAMS; + return ret; + } + *errCode = pubKey->getEncodedDer(pubKey, format, &ret); + LOGD("[PubKey] FFiOHOSPubKeyGetEncodedDer end"); + return ret; + } + + char *FFiOHOSPubKeyGetEncodedPem(int64_t id, char *format, int32_t *errCode) + { + LOGD("[PubKey] FFiOHOSPubKeyGetEncodedPem start"); + char *ret = nullptr; + auto instance = FFIData::GetData(id); + if (!instance) { + LOGE("[PubKey] FFiOHOSPubKeyGetEncodedPem failed to unwrap public key obj!"); + *errCode = HCF_INVALID_PARAMS; + return ret; + } + HcfPubKey *pubKey = instance->GetPubKey(); + if (pubKey == nullptr) { + LOGE("[PubKey] FFiOHOSPubKeyGetEncodedPem failed to get public key obj!"); + *errCode = HCF_INVALID_PARAMS; + return ret; + } + *errCode = pubKey->base.getEncodedPem(&pubKey->base, format, &ret); + LOGD("[PubKey] FFiOHOSPubKeyGetEncodedPem end"); + return ret; + } + + int FFiOHOSPubKeyGetAsyKeySpecByNum(int64_t id, int32_t itemType, int32_t *errCode) + { + LOGD("[PubKey] FFiOHOSPubKeyGetAsyKeySpec start"); + auto instance = FFIData::GetData(id); + int ret = 0; + if (!instance) { + LOGE("[PubKey] FFiOHOSPubKeyGetAsyKeySpec failed to unwrap public key obj!"); + *errCode = HCF_INVALID_PARAMS; + return ret; + } + HcfPubKey *pubKey = instance->GetPubKey(); + if (pubKey == nullptr) { + LOGE("[PubKey] FFiOHOSPubKeyGetAsyKeySpec failed to get public key obj!"); + *errCode = HCF_INVALID_PARAMS; + return ret; + } + AsyKeySpecItem item = AsyKeySpecItem(itemType); + *errCode = pubKey->getAsyKeySpecInt(pubKey, item, &ret); + LOGD("[PubKey] FFiOHOSPubKeyGetAsyKeySpec end"); + return ret; + } + + char *FFiOHOSPubKeyGetAsyKeySpecByStr(int64_t id, int32_t itemType, int32_t *errCode) + { + LOGD("[PubKey] FFiOHOSPubKeyGetAsyKeySpec start"); + auto instance = FFIData::GetData(id); + char *ret = nullptr; + if (!instance) { + LOGE("[PubKey] FFiOHOSPubKeyGetAsyKeySpec failed to unwrap public key obj!"); + *errCode = HCF_INVALID_PARAMS; + return ret; + } + HcfPubKey *pubKey = instance->GetPubKey(); + if (pubKey == nullptr) { + LOGE("[PubKey] FFiOHOSPubKeyGetAsyKeySpec failed to get public key obj!"); + *errCode = HCF_INVALID_PARAMS; + return ret; + } + AsyKeySpecItem item = AsyKeySpecItem(itemType); + *errCode = pubKey->getAsyKeySpecString(pubKey, item, &ret); + LOGD("[PubKey] FFiOHOSPubKeyGetAsyKeySpec end"); + return ret; + } + + HcfBigInteger FFiOHOSPubKeyGetAsyKeySpecByBigInt(int64_t id, int32_t itemType, int32_t *errCode) + { + LOGD("[PubKey] FFiOHOSPubKeyGetAsyKeySpec start"); + auto instance = FFIData::GetData(id); + HcfBigInteger ret = { 0 }; + if (!instance) { + LOGE("[PubKey] FFiOHOSPubKeyGetAsyKeySpec failed to unwrap public key obj!"); + *errCode = HCF_INVALID_PARAMS; + return ret; + } + HcfPubKey *pubKey = instance->GetPubKey(); + if (pubKey == nullptr) { + LOGE("[PubKey] FFiOHOSPubKeyGetAsyKeySpec failed to get public key obj!"); + *errCode = HCF_INVALID_PARAMS; + return ret; + } + AsyKeySpecItem item = AsyKeySpecItem(itemType); + *errCode = pubKey->getAsyKeySpecBigInteger(pubKey, item, &ret); + LOGD("[PubKey] FFiOHOSPubKeyGetAsyKeySpec end"); + return ret; + } + + const char *FfiOHOSPubKeyGetFormat(int64_t id, int32_t* errCode) + { + LOGD("[PubKey] GetFormat start"); + auto instance = FFIData::GetData(id); + if (!instance) { + LOGE("[PubKey] instance not exist."); + *errCode = HCF_ERR_MALLOC; + return nullptr; + } + const char* res = instance->GetFormat(errCode); + LOGD("[PubKey] GetFormat success"); + return res; + } + + // ------------------------------------keypair + int64_t FFiOHOSKeyPairPubKey(int64_t id, int32_t *errCode) + { + LOGD("[KeyPair] FFiOHOSKeyPairPubKey start"); + auto instance = FFIData::GetData(id); + if (!instance) { + *errCode = HCF_INVALID_PARAMS; + LOGE("build instance fail."); + return 0; + } + HcfKeyPair *keyPair = instance->GetHcfKeyPair(); + if (keyPair == nullptr) { + *errCode = HCF_INVALID_PARAMS; + LOGE("get keyPair fail."); + return 0; + } + HcfPubKey *pubKey = keyPair->pubKey; + if (pubKey == nullptr) { + *errCode = HCF_INVALID_PARAMS; + LOGE("get pubKey fail."); + return 0; + } + auto pub = FFIData::Create(pubKey); + if (pub == nullptr) { + *errCode = HCF_ERR_MALLOC; + LOGE("new pub key failed"); + return 0; + } + LOGD("[KeyPair] FFiOHOSKeyPairPubKey end"); + return pub->GetID(); + } + + int64_t FFiOHOSKeyPairPriKey(int64_t id, int32_t *errCode) + { + LOGD("[KeyPair] FFiOHOSKeyPairPriKey start"); + auto instance = FFIData::GetData(id); + if (!instance) { + *errCode = HCF_INVALID_PARAMS; + LOGE("build instance fail."); + return 0; + } + HcfKeyPair *keyPair = instance->GetHcfKeyPair(); + if (keyPair == nullptr) { + *errCode = HCF_INVALID_PARAMS; + LOGE("get keyPair fail."); + return 0; + } + HcfPriKey *priKey = keyPair->priKey; + if (priKey == nullptr) { + *errCode = HCF_INVALID_PARAMS; + LOGE("get priKey fail."); + return 0; + } + auto pri = FFIData::Create(priKey); + if (pri == nullptr) { + *errCode = HCF_ERR_MALLOC; + LOGE("new pri key failed"); + return 0; + } + LOGD("[KeyPair] FFiOHOSKeyPairPriKey end"); + return pri->GetID(); + } + + // ------------------------------------kdf + int64_t FFiOHOSKdfConstructor(char *algName, int32_t *errCode) + { + LOGD("[Kdf] FFiOHOSKdfConstructor start"); + HcfKdf *kdf = nullptr; + *errCode = HcfKdfCreate(algName, &kdf); + if (*errCode != HCF_SUCCESS) { + *errCode = HCF_INVALID_PARAMS; + LOGE("create c kdf fail."); + return 0; + } + auto instance = FFIData::Create(kdf); + if (!instance) { + *errCode = HCF_ERR_MALLOC; + HcfObjDestroy(kdf); + LOGE("new kdf failed!"); + return 0; + } + LOGD("[Kdf] FFiOHOSKdfConstructor end"); + return instance->GetID(); + } + + int32_t FFiOHOSKdfGenerateSecretByPB(int64_t id, HcfPBKDF2ParamsSpec *params) + { + LOGD("[Kdf] FiOHOSKdfGenerateSecretByPB start"); + auto instance = FFIData::GetData(id); + if (!instance) { + LOGE("[PubKey] FiOHOSKdfGenerateSecretByPB failed to get kdf impl obj!"); + return HCF_INVALID_PARAMS; + } + HcfKdfParamsSpec *tmp = reinterpret_cast(params); + LOGD("[Kdf] FiOHOSKdfGenerateSecretByPB end"); + return instance->GenerateSecret(tmp); + } + + int32_t FFiOHOSKdfGenerateSecretByH(int64_t id, HcfHkdfParamsSpec *params) + { + LOGD("[Kdf] FFiOHOSKdfGenerateSecretByH start"); + auto instance = FFIData::GetData(id); + if (!instance) { + LOGE("[PubKey] F FFiOHOSKdfGenerateSecretByH failed to get kdf impl obj!"); + return HCF_INVALID_PARAMS; + } + HcfKdfParamsSpec *tmp = reinterpret_cast(params); + LOGD("[Kdf] FFiOHOSKdfGenerateSecretByH end"); + return instance->GenerateSecret(tmp); + } + + // --------------------------ecc_key_util + HcfEccCommParamsSpec *FFiOHOSECCKeyUtilGenECCCommonParamsSpec(char *curveName, int32_t *errCode) + { + return ECCKeyUtilImpl::GenECCCommonParamsSpec(curveName, errCode); + } + + HcfPoint FFiOHOSECCKeyUtilConvertPoint(char *curveName, HcfBlob encodedPoint, int32_t *errCode) + { + return ECCKeyUtilImpl::ConvertPoint(curveName, encodedPoint, errCode); + } + + HcfBlob FFiOHOSECCKeyUtilGetEncodedPoint(char *curveName, HcfPoint point, char *format, int32_t *errCode) + { + return ECCKeyUtilImpl::GetEncodedPoint(curveName, point, format, errCode); + } + + // ---------------------------keyagreement + int64_t FFiOHOSKeyAgreementConstructor(char *algName, int32_t *errCode) + { + LOGD("[KeyAgreement] FFiOHOSKdfConstructor start"); + HcfKeyAgreement *keyAgreement = nullptr; + *errCode = HcfKeyAgreementCreate(algName, &keyAgreement); + if (*errCode != HCF_SUCCESS) { + *errCode = HCF_INVALID_PARAMS; + LOGE("create c keyAgreement fail."); + return 0; + } + auto instance = FFIData::Create(keyAgreement); + if (!instance) { + *errCode = HCF_ERR_MALLOC; + HcfObjDestroy(keyAgreement); + LOGE("new key agreement failed!"); + return 0; + } + LOGD("[KeyAgreement] FFiOHOSKdfConstructor end"); + return instance->GetID(); + } + + HcfBlob FFiOHOSKeyAgreementGenerateSecret(int64_t id, int64_t priId, int64_t pubId, int32_t *errCode) + { + LOGD("[KeyAgreement] FFiOHOSKeyAgreementGenerateSecret start"); + auto instance = FFIData::GetData(id); + HcfBlob blob = { 0 }; + if (!instance) { + LOGE("[KeyAgreement] FFiOHOSKeyAgreementGenerateSecret failed to get key agreement obj!"); + *errCode = HCF_INVALID_PARAMS; + return blob; + } + auto priKey = FFIData::GetData(priId); + if (!priKey) { + LOGE("[KeyAgreement] FFiOHOSKeyAgreementGenerateSecret failed to get priKey obj!"); + *errCode = HCF_INVALID_PARAMS; + return blob; + } + auto pubKey = FFIData::GetData(pubId); + if (!pubKey) { + LOGE("[KeyAgreement] FFiOHOSKeyAgreementGenerateSecret failed to get priKey obj!"); + *errCode = HCF_INVALID_PARAMS; + return blob; + } + LOGD("[KeyAgreement] FFiOHOSKeyAgreementGenerateSecret end"); + return instance->GenerateSecret(priKey->GetPriKey(), pubKey->GetPubKey(), errCode); + } + + // dh_key_util + HcfDhCommParamsSpec *FFiOHOSDHKeyUtilGenDHCommonParamsSpec(int32_t pLen, int32_t skLen, int32_t *errCode) + { + return DHKeyUtilImpl::GenDHCommonParamsSpec(pLen, skLen, errCode); + } + + // sm2_crypto_util + HcfBlob FFiOHOSSm2CryptoUtilGenCipherTextBySpec(Sm2CipherTextSpec spec, char *mode, int32_t *errCode) + { + return Sm2CryptoUtilImpl::GenCipherTextBySpec(spec, mode, errCode); + } + + Sm2CipherTextSpec *FFiOHOSSm2CryptoUtilGetCipherTextSpec(HcfBlob input, char *mode, int32_t *errCode) + { + return Sm2CryptoUtilImpl::GetCipherTextSpec(input, mode, errCode); + } + } + } // namespace CryptoFramework } // namespace OHOS \ No newline at end of file diff --git a/frameworks/cj/src/crypto_mock.cpp b/frameworks/cj/src/crypto_mock.cpp index 65f9a07ae3d036f9cf48b9ad3dd05a7e190a9cdf..37233e16bae2427570c47870c5306dd083a1a7b5 100644 --- a/frameworks/cj/src/crypto_mock.cpp +++ b/frameworks/cj/src/crypto_mock.cpp @@ -1,53 +1,53 @@ -/* - * 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 "cj_common_ffi.h" - -extern "C" { -FFI_EXPORT int FfiOHOSCreateRandom = 0; -FFI_EXPORT int FfiOHOSRandomGetAlgName = 0; -FFI_EXPORT int FfiOHOSGenerateRandom = 0; -FFI_EXPORT int FfiOHOSSetSeed = 0; -FFI_EXPORT int FfiOHOSCreateMd = 0; -FFI_EXPORT int FfiOHOSMdUpdate = 0; -FFI_EXPORT int FfiOHOSDigest = 0; -FFI_EXPORT int FfiOHOSGetMdLength = 0; -FFI_EXPORT int FfiOHOSCreateSymKeyGenerator = 0; -FFI_EXPORT int FfiOHOSSymKeyGeneratorGetAlgName = 0; -FFI_EXPORT int FfiOHOSGenerateSymKey = 0; -FFI_EXPORT int FfiOHOSConvertKey = 0; -FFI_EXPORT int FfiOHOSSymKeyGetAlgName = 0; -FFI_EXPORT int FfiOHOSSymKeyGetFormat = 0; -FFI_EXPORT int FfiOHOSSymKeyGetEncoded = 0; -FFI_EXPORT int FfiOHOSClearMem = 0; -FFI_EXPORT int FfiOHOSSymKeyGetHcfKey = 0; -FFI_EXPORT int FfiOHOSCreateCipher = 0; -FFI_EXPORT int FfiOHOSCipherInitByIv = 0; -FFI_EXPORT int FfiOHOSCipherInitByGcm = 0; -FFI_EXPORT int FfiOHOSCipherInitByCcm = 0; -FFI_EXPORT int FfiOHOSCipherInitWithOutParams = 0; -FFI_EXPORT int FfiOHOSCipherUpdate = 0; -FFI_EXPORT int FfiOHOSCipherDoFinal = 0; -FFI_EXPORT int FfiOHOSSetCipherSpec = 0; -FFI_EXPORT int FfiOHOSGetCipherSpecString = 0; -FFI_EXPORT int FfiOHOSGetCipherSpecUint8Array = 0; -FFI_EXPORT int FfiOHOSCipherGetAlgName = 0; -FFI_EXPORT int FFiOHOSCryptoMacConstructor = 0; -FFI_EXPORT int FfiOHOSCryptoMacInit = 0; -FFI_EXPORT int FfiOHOSCryptoMacUpdate = 0; -FFI_EXPORT int FfiOHOSCryptoMacDoFinal = 0; -FFI_EXPORT int FfiOHOSGCryptoGetMacLength = 0; -FFI_EXPORT int FFiOHOSCryptoSignConstructor = 0; +/* + * 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 "cj_common_ffi.h" + +extern "C" { +FFI_EXPORT int FfiOHOSCreateRandom = 0; +FFI_EXPORT int FfiOHOSRandomGetAlgName = 0; +FFI_EXPORT int FfiOHOSGenerateRandom = 0; +FFI_EXPORT int FfiOHOSSetSeed = 0; +FFI_EXPORT int FfiOHOSCreateMd = 0; +FFI_EXPORT int FfiOHOSMdUpdate = 0; +FFI_EXPORT int FfiOHOSDigest = 0; +FFI_EXPORT int FfiOHOSGetMdLength = 0; +FFI_EXPORT int FfiOHOSCreateSymKeyGenerator = 0; +FFI_EXPORT int FfiOHOSSymKeyGeneratorGetAlgName = 0; +FFI_EXPORT int FfiOHOSGenerateSymKey = 0; +FFI_EXPORT int FfiOHOSConvertKey = 0; +FFI_EXPORT int FfiOHOSSymKeyGetAlgName = 0; +FFI_EXPORT int FfiOHOSSymKeyGetFormat = 0; +FFI_EXPORT int FfiOHOSSymKeyGetEncoded = 0; +FFI_EXPORT int FfiOHOSClearMem = 0; +FFI_EXPORT int FfiOHOSSymKeyGetHcfKey = 0; +FFI_EXPORT int FfiOHOSCreateCipher = 0; +FFI_EXPORT int FfiOHOSCipherInitByIv = 0; +FFI_EXPORT int FfiOHOSCipherInitByGcm = 0; +FFI_EXPORT int FfiOHOSCipherInitByCcm = 0; +FFI_EXPORT int FfiOHOSCipherInitWithOutParams = 0; +FFI_EXPORT int FfiOHOSCipherUpdate = 0; +FFI_EXPORT int FfiOHOSCipherDoFinal = 0; +FFI_EXPORT int FfiOHOSSetCipherSpec = 0; +FFI_EXPORT int FfiOHOSGetCipherSpecString = 0; +FFI_EXPORT int FfiOHOSGetCipherSpecUint8Array = 0; +FFI_EXPORT int FfiOHOSCipherGetAlgName = 0; +FFI_EXPORT int FFiOHOSCryptoMacConstructor = 0; +FFI_EXPORT int FfiOHOSCryptoMacInit = 0; +FFI_EXPORT int FfiOHOSCryptoMacUpdate = 0; +FFI_EXPORT int FfiOHOSCryptoMacDoFinal = 0; +FFI_EXPORT int FfiOHOSGCryptoGetMacLength = 0; +FFI_EXPORT int FFiOHOSCryptoSignConstructor = 0; } \ No newline at end of file diff --git a/frameworks/cj/src/dh_key_util_impl.cpp b/frameworks/cj/src/dh_key_util_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f4f5f1c23947751eabdfe1cec7e24c4a6be5a256 --- /dev/null +++ b/frameworks/cj/src/dh_key_util_impl.cpp @@ -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 "dh_key_util_impl.h" + +namespace OHOS { +namespace CryptoFramework { +DHKeyUtilImpl::DHKeyUtilImpl() {} + +DHKeyUtilImpl::~DHKeyUtilImpl() {} + +HcfDhCommParamsSpec *DHKeyUtilImpl::GenDHCommonParamsSpec(int32_t pLen, int32_t skLen, int32_t *errCode) +{ + HcfDhCommParamsSpec *dhCommParamsSpec = nullptr; + *errCode = HcfDhKeyUtilCreate(pLen, skLen, &dhCommParamsSpec); + return dhCommParamsSpec; +} +} +} \ No newline at end of file diff --git a/frameworks/cj/src/ecc_key_util_impl.cpp b/frameworks/cj/src/ecc_key_util_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9e8a51d952d5727b4efbb8cf9c092d97af815e53 --- /dev/null +++ b/frameworks/cj/src/ecc_key_util_impl.cpp @@ -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. + */ + +#include "ecc_key_util_impl.h" + +namespace OHOS { +namespace CryptoFramework { +ECCKeyUtilImpl::ECCKeyUtilImpl() {} + +ECCKeyUtilImpl::~ECCKeyUtilImpl() {} + +HcfEccCommParamsSpec *ECCKeyUtilImpl::GenECCCommonParamsSpec(char *algName, int32_t *errCode) +{ + HcfEccCommParamsSpec *eccCommParamsSpec = nullptr; + *errCode = HcfEccKeyUtilCreate(algName, &eccCommParamsSpec); + return eccCommParamsSpec; +} + +HcfPoint ECCKeyUtilImpl::ConvertPoint(char *curveName, HcfBlob encodedPoint, int32_t *errCode) +{ + HcfPoint point; + *errCode = HcfConvertPoint(curveName, &encodedPoint, &point); + return point; +} + +HcfBlob ECCKeyUtilImpl::GetEncodedPoint(char *curveName, HcfPoint point, char *format, int32_t *errCode) +{ + HcfBlob returnBlob; + *errCode = HcfGetEncodedPoint(curveName, &point, format, &returnBlob); + return returnBlob; +} +} +} \ No newline at end of file diff --git a/frameworks/cj/src/kdf_impl.cpp b/frameworks/cj/src/kdf_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5fffde9d0016529ce56f79dd81ebdfae13b8e001 --- /dev/null +++ b/frameworks/cj/src/kdf_impl.cpp @@ -0,0 +1,44 @@ +/* + * 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 "kdf_impl.h" + +namespace OHOS { +namespace CryptoFramework { +KdfImpl::KdfImpl(HcfKdf *kdfObj) +{ + this->kdf = kdfObj; +} + +KdfImpl::~KdfImpl() +{ + HcfObjDestroy(this->kdf); + this->kdf = nullptr; +} + +HcfKdf *KdfImpl::GetKdf() const +{ + return this->kdf; +} + +int32_t KdfImpl::GenerateSecret(HcfKdfParamsSpec *paramsSpec) +{ + if (this->kdf == nullptr) { + return HCF_INVALID_PARAMS; + } + return this->kdf->generateSecret(kdf, paramsSpec); +} +} +} \ No newline at end of file diff --git a/frameworks/cj/src/key_agreement_impl.cpp b/frameworks/cj/src/key_agreement_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e92bf40828ce2a948902ef0012f14d9f953b9349 --- /dev/null +++ b/frameworks/cj/src/key_agreement_impl.cpp @@ -0,0 +1,47 @@ +/* + * 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 "key_agreement_impl.h" + +namespace OHOS { +namespace CryptoFramework { +KeyAgreementImpl::KeyAgreementImpl(HcfKeyAgreement *keyAgreement) +{ + this->keyAgreement_ = keyAgreement; +} + +KeyAgreementImpl::~KeyAgreementImpl() +{ + HcfObjDestroy(this->keyAgreement_); + this->keyAgreement_ = nullptr; +} + +HcfKeyAgreement *KeyAgreementImpl::GetKeyAgreement() +{ + return this->keyAgreement_; +} + +HcfBlob KeyAgreementImpl::GenerateSecret(HcfPriKey *priKey, HcfPubKey *pubKey, int32_t *errCode) +{ + HcfBlob returnSecret = { .data = nullptr, .len = 0 }; + if (this->keyAgreement_ == nullptr || priKey == nullptr || pubKey == nullptr) { + *errCode = HCF_INVALID_PARAMS; + return returnSecret; + } + *errCode = this->keyAgreement_->generateSecret(keyAgreement_, priKey, pubKey, &returnSecret); + return returnSecret; +} +} +} \ No newline at end of file diff --git a/frameworks/cj/src/key_impl.cpp b/frameworks/cj/src/key_impl.cpp index 98a191a0b514f68ececb8a8b86bd55b2ae9c6a63..7a1f36262fe418ba7524da4313e92c9a5d88ccdf 100644 --- a/frameworks/cj/src/key_impl.cpp +++ b/frameworks/cj/src/key_impl.cpp @@ -1,66 +1,65 @@ -/* - * 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 "key_impl.h" -#include "result.h" -#include "log.h" - -namespace OHOS { - namespace CryptoFramework { - KeyImpl::KeyImpl(HcfKey *hcfKey) - { - hcfKey_ = hcfKey; - } - - KeyImpl::~KeyImpl() {} - - HcfKey *KeyImpl::GetHcfKey() const - { - return hcfKey_; - } - - const char *KeyImpl::GetFormat(int32_t* errCode) - { - if (hcfKey_ == nullptr) { - LOGE("fail to get key obj!"); - *errCode = HCF_ERR_MALLOC; - return nullptr; - } - const char *format = hcfKey_->getFormat(hcfKey_); - *errCode = HCF_SUCCESS; - return format; - } - - const char *KeyImpl::GetAlgorithm(int32_t* errCode) - { - if (hcfKey_ == nullptr) { - LOGE("fail to get key obj!"); - *errCode = HCF_ERR_MALLOC; - return nullptr; - } - const char *algo = hcfKey_->getAlgorithm(hcfKey_); - *errCode = HCF_SUCCESS; - return algo; - } - - HcfResult KeyImpl::GetEncoded(HcfBlob *returnBlob) - { - if (hcfKey_ == nullptr) { - LOGE("fail to get key obj!"); - return HCF_ERR_MALLOC; - } - return hcfKey_->getEncoded(hcfKey_, returnBlob); - } - } +/* + * 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 "key_impl.h" +#include "log.h" + +namespace OHOS { + namespace CryptoFramework { + KeyImpl::KeyImpl(HcfKey *hcfKey) + { + hcfKey_ = hcfKey; + } + + KeyImpl::~KeyImpl() {} + + HcfKey *KeyImpl::GetHcfKey() const + { + return hcfKey_; + } + + const char *KeyImpl::GetFormat(int32_t* errCode) + { + if (hcfKey_ == nullptr) { + LOGE("fail to get key obj!"); + *errCode = HCF_ERR_MALLOC; + return nullptr; + } + const char *format = hcfKey_->getFormat(hcfKey_); + *errCode = HCF_SUCCESS; + return format; + } + + const char *KeyImpl::GetAlgorithm(int32_t* errCode) + { + if (hcfKey_ == nullptr) { + LOGE("fail to get key obj!"); + *errCode = HCF_ERR_MALLOC; + return nullptr; + } + const char *algo = hcfKey_->getAlgorithm(hcfKey_); + *errCode = HCF_SUCCESS; + return algo; + } + + HcfResult KeyImpl::GetEncoded(HcfBlob *returnBlob) + { + if (hcfKey_ == nullptr) { + LOGE("fail to get key obj!"); + return HCF_ERR_MALLOC; + } + return hcfKey_->getEncoded(hcfKey_, returnBlob); + } + } } \ No newline at end of file diff --git a/frameworks/cj/src/key_pair_impl.cpp b/frameworks/cj/src/key_pair_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f06c2a1090cfa34362a003180139568a2b01412b --- /dev/null +++ b/frameworks/cj/src/key_pair_impl.cpp @@ -0,0 +1,36 @@ +/* + * 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 "key_pair_impl.h" + +namespace OHOS { +namespace CryptoFramework { +KeyPairImpl::KeyPairImpl(HcfKeyPair *keyPair) +{ + this->keyPair_ = keyPair; +} + +KeyPairImpl::~KeyPairImpl() +{ + HcfObjDestroy(this->keyPair_); + this->keyPair_ = nullptr; +} + +HcfKeyPair *KeyPairImpl::GetHcfKeyPair() +{ + return this->keyPair_; +} +} +} \ No newline at end of file diff --git a/frameworks/cj/src/mac_impl.cpp b/frameworks/cj/src/mac_impl.cpp index 03e08b362a0fe44645844d480a2bbaf1f9291a30..eb27e3aea052df4ce84d70d76ee2490132c77bd2 100644 --- a/frameworks/cj/src/mac_impl.cpp +++ b/frameworks/cj/src/mac_impl.cpp @@ -1,73 +1,71 @@ -/* - * 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 "mac_impl.h" -#include "log.h" -#include "result.h" - -namespace OHOS { - namespace CryptoFramework { - MacImpl::MacImpl(HcfMac *macObj) - { - macObj_ = macObj; - } - - MacImpl::~MacImpl() - { - HcfObjDestroy(this->macObj_); - } - - HcfResult MacImpl::MacInit(HcfSymKey *symKey) - { - if (macObj_ == nullptr) { - LOGE("fail to get mac obj!"); - return HCF_ERR_MALLOC; - } - HcfResult res = macObj_->init(macObj_, symKey); - return res; - } - - HcfResult MacImpl::MacUpdate(HcfBlob *input) - { - if (macObj_ == nullptr) { - LOGE("fail to get mac obj!"); - return HCF_ERR_MALLOC; - } - HcfResult res = macObj_->update(macObj_, input); - return res; - } - - HcfResult MacImpl::MacDoFinal(HcfBlob *output) - { - if (macObj_ == nullptr) { - LOGE("fail to get mac obj!"); - return HCF_ERR_MALLOC; - } - HcfResult res = macObj_->doFinal(macObj_, output); - return res; - } - - uint32_t MacImpl::GetMacLength() - { - if (macObj_ == nullptr) { - LOGE("fail to get mac obj!"); - return HCF_ERR_MALLOC; - } - uint32_t retLen = macObj_->getMacLength(macObj_); - return retLen; - } - - } +/* + * 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 "mac_impl.h" + +namespace OHOS { + namespace CryptoFramework { + MacImpl::MacImpl(HcfMac *macObj) + { + macObj_ = macObj; + } + + MacImpl::~MacImpl() + { + HcfObjDestroy(this->macObj_); + } + + HcfResult MacImpl::MacInit(HcfSymKey *symKey) + { + if (macObj_ == nullptr) { + LOGE("fail to get mac obj!"); + return HCF_ERR_MALLOC; + } + HcfResult res = macObj_->init(macObj_, symKey); + return res; + } + + HcfResult MacImpl::MacUpdate(HcfBlob *input) + { + if (macObj_ == nullptr) { + LOGE("fail to get mac obj!"); + return HCF_ERR_MALLOC; + } + HcfResult res = macObj_->update(macObj_, input); + return res; + } + + HcfResult MacImpl::MacDoFinal(HcfBlob *output) + { + if (macObj_ == nullptr) { + LOGE("fail to get mac obj!"); + return HCF_ERR_MALLOC; + } + HcfResult res = macObj_->doFinal(macObj_, output); + return res; + } + + uint32_t MacImpl::GetMacLength() + { + if (macObj_ == nullptr) { + LOGE("fail to get mac obj!"); + return HCF_ERR_MALLOC; + } + uint32_t retLen = macObj_->getMacLength(macObj_); + return retLen; + } + + } } \ No newline at end of file diff --git a/frameworks/cj/src/md_impl.cpp b/frameworks/cj/src/md_impl.cpp index 3a78325e01131fec2861cc68855702208d4f1641..543a3b07435e5b55b0a25db7ba812ca0274eb88f 100644 --- a/frameworks/cj/src/md_impl.cpp +++ b/frameworks/cj/src/md_impl.cpp @@ -1,63 +1,61 @@ -/* - * 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 "md_impl.h" -#include "log.h" -#include "result.h" - -namespace OHOS { - namespace CryptoFramework { - MdImpl::MdImpl(HcfMd *mdObj) - { - mdObj_ = mdObj; - } - - HcfResult MdImpl::MdUpdate(HcfBlob *input) - { - if (mdObj_ == nullptr) { - LOGE("fail to get md obj!"); - return HCF_ERR_MALLOC; - } - HcfResult res = mdObj_->update(mdObj_, input); - return res; - } - - MdImpl::~MdImpl() - { - HcfObjDestroy(this->mdObj_); - } - - HcfResult MdImpl::MdDoFinal(HcfBlob *output) - { - if (mdObj_ == nullptr) { - LOGE("fail to get md obj!"); - return HCF_ERR_MALLOC; - } - HcfResult res = mdObj_->doFinal(mdObj_, output); - return res; - } - - uint32_t MdImpl::GetMdLength(int32_t* errCode) - { - if (mdObj_ == nullptr) { - LOGE("fail to get md obj!"); - *errCode = HCF_ERR_MALLOC; - return 0; - } - uint32_t retLen = mdObj_->getMdLength(mdObj_); - *errCode = HCF_SUCCESS; - return retLen; - } - } +/* + * 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 "md_impl.h" + +namespace OHOS { + namespace CryptoFramework { + MdImpl::MdImpl(HcfMd *mdObj) + { + mdObj_ = mdObj; + } + + HcfResult MdImpl::MdUpdate(HcfBlob *input) + { + if (mdObj_ == nullptr) { + LOGE("fail to get md obj!"); + return HCF_ERR_MALLOC; + } + HcfResult res = mdObj_->update(mdObj_, input); + return res; + } + + MdImpl::~MdImpl() + { + HcfObjDestroy(this->mdObj_); + } + + HcfResult MdImpl::MdDoFinal(HcfBlob *output) + { + if (mdObj_ == nullptr) { + LOGE("fail to get md obj!"); + return HCF_ERR_MALLOC; + } + HcfResult res = mdObj_->doFinal(mdObj_, output); + return res; + } + + uint32_t MdImpl::GetMdLength(int32_t* errCode) + { + if (mdObj_ == nullptr) { + LOGE("fail to get md obj!"); + *errCode = HCF_ERR_MALLOC; + return 0; + } + uint32_t retLen = mdObj_->getMdLength(mdObj_); + *errCode = HCF_SUCCESS; + return retLen; + } + } } \ No newline at end of file diff --git a/frameworks/cj/src/crypto_utils.h b/frameworks/cj/src/pri_key_impl.cpp similarity index 67% rename from frameworks/cj/src/crypto_utils.h rename to frameworks/cj/src/pri_key_impl.cpp index ac677b1e4da23ddc2a907bb05a1670cc3469318d..7dda028050b6d0b60306ab0532751a00b8bd3f0e 100644 --- a/frameworks/cj/src/crypto_utils.h +++ b/frameworks/cj/src/pri_key_impl.cpp @@ -12,18 +12,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include "pri_key_impl.h" -#ifndef OHOS_CRYPTO_UTILS_H -#define OHOS_CRYPTO_UTILS_H +namespace OHOS { +namespace CryptoFramework { +PriKeyImpl::PriKeyImpl(HcfPriKey *priKey) : KeyImpl(reinterpret_cast(priKey)) {} -#include -#include -#include +PriKeyImpl::~PriKeyImpl() {} -#define FFI_EXPORT __attribute__((visibility("default"))) - -class FFI_EXPORT Utils { -public: - static char* MallocCString(const std::string& origin); -}; -#endif +HcfPriKey *PriKeyImpl::GetPriKey() +{ + return reinterpret_cast(KeyImpl::GetHcfKey()); +} +} +} \ No newline at end of file diff --git a/frameworks/cj/src/pub_key_impl.cpp b/frameworks/cj/src/pub_key_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5c8e2a15dfee4928abe26cbb22dba610145a8c3b --- /dev/null +++ b/frameworks/cj/src/pub_key_impl.cpp @@ -0,0 +1,28 @@ +/* + * 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 "pub_key_impl.h" + +namespace OHOS { +namespace CryptoFramework { +PubKeyImpl::PubKeyImpl(HcfPubKey *pubKey) : KeyImpl(reinterpret_cast(pubKey)) {} + +PubKeyImpl::~PubKeyImpl() {} + +HcfPubKey *PubKeyImpl::GetPubKey() +{ + return reinterpret_cast(KeyImpl::GetHcfKey()); +} +} +} \ No newline at end of file diff --git a/frameworks/cj/src/random_impl.cpp b/frameworks/cj/src/random_impl.cpp index 9ed0e414fe4b410e57fb1c6ba0b8434b4ffeac8b..c97b2ab4bdb220dae75e62d177747cc15b9b1554 100644 --- a/frameworks/cj/src/random_impl.cpp +++ b/frameworks/cj/src/random_impl.cpp @@ -1,73 +1,71 @@ -/* - * 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 "random_impl.h" -#include "result.h" -#include "log.h" - -namespace OHOS { - namespace CryptoFramework { - RandomImpl::RandomImpl(HcfRand *randObj) - { - randObj_ = randObj; - } - - RandomImpl::~RandomImpl() - { - HcfObjDestroy(this->randObj_); - } - - const char* RandomImpl::GetAlgName(int32_t* errCode) - { - if (randObj_ == nullptr) { - LOGE("fail to get rand obj!"); - *errCode = HCF_ERR_MALLOC; - return nullptr; - } - const char *algoName = randObj_->getAlgoName(randObj_); - *errCode = HCF_SUCCESS; - return algoName; - } - - HcfBlob RandomImpl::GenerateRandom(int32_t numBytes, int32_t* errCode) - { - HcfBlob randBlob = { .data = nullptr, .len = 0}; - if (randObj_ == nullptr) { - *errCode = HCF_ERR_MALLOC; - LOGE("fail to get rand obj!"); - return randBlob; - } - HcfResult res = randObj_->generateRandom(randObj_, numBytes, &randBlob); - if (res != HCF_SUCCESS) { - LOGE("generateRandom failed!"); - } - *errCode = static_cast(res); - return randBlob; - } - - void RandomImpl::SetSeed(HcfBlob *seed, int32_t* errCode) - { - if (randObj_ == nullptr) { - *errCode = HCF_ERR_MALLOC; - LOGE("fail to get rand obj!"); - return; - } - HcfResult res = randObj_->setSeed(randObj_, seed); - if (res != HCF_SUCCESS) { - LOGE("set seed failed."); - } - *errCode = static_cast(res); - } - } +/* + * 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 "random_impl.h" + +namespace OHOS { + namespace CryptoFramework { + RandomImpl::RandomImpl(HcfRand *randObj) + { + randObj_ = randObj; + } + + RandomImpl::~RandomImpl() + { + HcfObjDestroy(this->randObj_); + } + + const char* RandomImpl::GetAlgName(int32_t* errCode) + { + if (randObj_ == nullptr) { + LOGE("fail to get rand obj!"); + *errCode = HCF_ERR_MALLOC; + return nullptr; + } + const char *algoName = randObj_->getAlgoName(randObj_); + *errCode = HCF_SUCCESS; + return algoName; + } + + HcfBlob RandomImpl::GenerateRandom(int32_t numBytes, int32_t* errCode) + { + HcfBlob randBlob = { .data = nullptr, .len = 0}; + if (randObj_ == nullptr) { + *errCode = HCF_ERR_MALLOC; + LOGE("fail to get rand obj!"); + return randBlob; + } + HcfResult res = randObj_->generateRandom(randObj_, numBytes, &randBlob); + if (res != HCF_SUCCESS) { + LOGE("generateRandom failed!"); + } + *errCode = static_cast(res); + return randBlob; + } + + void RandomImpl::SetSeed(HcfBlob *seed, int32_t* errCode) + { + if (randObj_ == nullptr) { + *errCode = HCF_ERR_MALLOC; + LOGE("fail to get rand obj!"); + return; + } + HcfResult res = randObj_->setSeed(randObj_, seed); + if (res != HCF_SUCCESS) { + LOGE("set seed failed."); + } + *errCode = static_cast(res); + } + } } \ No newline at end of file diff --git a/frameworks/cj/src/sign_impl.cpp b/frameworks/cj/src/sign_impl.cpp index 3d417d8a1edc3cbdd85338d7fb15b066f0371bd4..b2785028b6b398391dc1ed81ef861225aa6ab67d 100644 --- a/frameworks/cj/src/sign_impl.cpp +++ b/frameworks/cj/src/sign_impl.cpp @@ -1,32 +1,86 @@ -/* - * 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 "sign_impl.h" -#include "log.h" -#include "result.h" - -namespace OHOS { - namespace CryptoFramework { - SignImpl::SignImpl(HcfSign *signObj) - { - signObj_ = signObj; - } - - SignImpl::~SignImpl() - { - HcfObjDestroy(this->signObj_); - } - } +/* + * 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 "sign_impl.h" + +namespace OHOS { +namespace CryptoFramework { +SignImpl::SignImpl(HcfSign *signObj) +{ + signObj_ = signObj; +} + +SignImpl::~SignImpl() +{ + HcfObjDestroy(this->signObj_); +} + +HcfResult SignImpl::Init(HcfPriKey *priKey) +{ + if (this->signObj_ == nullptr) { + return HCF_INVALID_PARAMS; + } + return this->signObj_->init(signObj_, nullptr, priKey); +} + +HcfResult SignImpl::Update(HcfBlob *input) +{ + if (this->signObj_ == nullptr) { + return HCF_INVALID_PARAMS; + } + return this->signObj_->update(signObj_, input); +} + +HcfResult SignImpl::Sign(HcfBlob *input, HcfBlob *output) +{ + if (this->signObj_ == nullptr) { + return HCF_INVALID_PARAMS; + } + return this->signObj_->sign(signObj_, input, output); +} + +HcfResult SignImpl::SetSignSpecByNum(int32_t itemValue) +{ + if (this->signObj_ == nullptr) { + return HCF_INVALID_PARAMS; + } + return this->signObj_->setSignSpecInt(signObj_, PSS_SALT_LEN_INT, itemValue); +} + +HcfResult SignImpl::SetSignSpecByArr(HcfBlob itemValue) +{ + if (this->signObj_ == nullptr) { + return HCF_INVALID_PARAMS; + } + return this->signObj_->setSignSpecUint8Array(signObj_, SM2_USER_ID_UINT8ARR, itemValue); +} + +HcfResult SignImpl::GetSignSpecString(SignSpecItem item, char *itemValue) +{ + if (this->signObj_ == nullptr) { + return HCF_INVALID_PARAMS; + } + return this->signObj_->getSignSpecString(signObj_, item, &itemValue); +} + +HcfResult SignImpl::GetSignSpecNum(SignSpecItem item, int32_t *itemValue) +{ + if (this->signObj_ == nullptr) { + return HCF_INVALID_PARAMS; + } + return this->signObj_->getSignSpecInt(signObj_, item, itemValue); +} +} } \ No newline at end of file diff --git a/frameworks/cj/src/sm2_crypto_util_impl.cpp b/frameworks/cj/src/sm2_crypto_util_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cabf2179b5c92ad803b8386e1443c2abbdce15dd --- /dev/null +++ b/frameworks/cj/src/sm2_crypto_util_impl.cpp @@ -0,0 +1,38 @@ +/* + * 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 "sm2_crypto_util_impl.h" + +namespace OHOS { +namespace CryptoFramework { +Sm2CryptoUtilImpl::Sm2CryptoUtilImpl() {} + +Sm2CryptoUtilImpl::~Sm2CryptoUtilImpl() {} + +HcfBlob Sm2CryptoUtilImpl::GenCipherTextBySpec(Sm2CipherTextSpec spec, char *mode, int32_t *errCode) +{ + HcfBlob output = { 0 }; + *errCode = HcfGenCipherTextBySpec(&spec, mode, &output); + return output; +} + +Sm2CipherTextSpec *Sm2CryptoUtilImpl::GetCipherTextSpec(HcfBlob input, char *mode, int32_t *errCode) +{ + Sm2CipherTextSpec *returnSpec = nullptr; + *errCode = HcfGetCipherTextSpec(&input, mode, &returnSpec); + return returnSpec; +} +} +} \ No newline at end of file diff --git a/frameworks/cj/src/symkey_generator_impl.cpp b/frameworks/cj/src/sym_key_generator_impl.cpp similarity index 94% rename from frameworks/cj/src/symkey_generator_impl.cpp rename to frameworks/cj/src/sym_key_generator_impl.cpp index c5dd9cee68aa710505507f9094ac1cd9fb4f9dab..9d13539480ec00c26aaa3b5f639ff474f9603d52 100644 --- a/frameworks/cj/src/symkey_generator_impl.cpp +++ b/frameworks/cj/src/sym_key_generator_impl.cpp @@ -12,8 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "symkey_generator_impl.h" -#include "log.h" +#include "sym_key_generator_impl.h" namespace OHOS { namespace CryptoFramework { @@ -39,7 +38,6 @@ namespace OHOS { return algo; } - HcfResult SymKeyGeneratorImpl::GenerateSymKey(HcfSymKey **symKey) { if (generator_ == nullptr) { diff --git a/frameworks/cj/src/symkey_impl.cpp b/frameworks/cj/src/sym_key_impl.cpp similarity index 92% rename from frameworks/cj/src/symkey_impl.cpp rename to frameworks/cj/src/sym_key_impl.cpp index 13836a03c103767238957d188b101eda74924df1..d1233091536074f482c067e6b6788a168b7159ab 100644 --- a/frameworks/cj/src/symkey_impl.cpp +++ b/frameworks/cj/src/sym_key_impl.cpp @@ -1,42 +1,40 @@ -/* - * 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 "symkey_impl.h" -#include "result.h" -#include "log.h" - -namespace OHOS { - namespace CryptoFramework { - SymKeyImpl::SymKeyImpl(HcfSymKey *symKey) : KeyImpl(reinterpret_cast(symKey)) {} - - SymKeyImpl::~SymKeyImpl() - { - HcfObjDestroy(this->hcfKey_); - this->hcfKey_ = nullptr; - } - - HcfSymKey *SymKeyImpl::GetSymKey() const - { - return reinterpret_cast(KeyImpl::GetHcfKey()); - } - - void SymKeyImpl::ClearMem() - { - HcfSymKey *key = GetSymKey(); - if (key != nullptr) { - key->clearMem(key); - } - } - } +/* + * 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 "sym_key_impl.h" + +namespace OHOS { + namespace CryptoFramework { + SymKeyImpl::SymKeyImpl(HcfSymKey *symKey) : KeyImpl(reinterpret_cast(symKey)) {} + + SymKeyImpl::~SymKeyImpl() + { + HcfObjDestroy(this->hcfKey_); + this->hcfKey_ = nullptr; + } + + HcfSymKey *SymKeyImpl::GetSymKey() const + { + return reinterpret_cast(KeyImpl::GetHcfKey()); + } + + void SymKeyImpl::ClearMem() + { + HcfSymKey *key = GetSymKey(); + if (key != nullptr) { + key->clearMem(key); + } + } + } } \ No newline at end of file diff --git a/frameworks/cj/src/verify_impl.cpp b/frameworks/cj/src/verify_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1ddfba8d952f94973eae20d3460054bf1a3c2c8a --- /dev/null +++ b/frameworks/cj/src/verify_impl.cpp @@ -0,0 +1,96 @@ +/* + * 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 "verify_impl.h" + +namespace OHOS { +namespace CryptoFramework { +VerifyImpl::VerifyImpl(HcfVerify *verify) +{ + this->verify_ = verify; +} + +VerifyImpl::~VerifyImpl() +{ + HcfObjDestroy(this->verify_); +} + +HcfResult VerifyImpl::Init(HcfPubKey *pubKey) +{ + if (this->verify_ == nullptr) { + return HCF_INVALID_PARAMS; + } + return this->verify_->init(verify_, nullptr, pubKey); +} + +HcfResult VerifyImpl::Update(HcfBlob *input) +{ + if (this->verify_ == nullptr) { + return HCF_INVALID_PARAMS; + } + return this->verify_->update(verify_, input); +} + +bool VerifyImpl::Verify(HcfBlob *data, HcfBlob signatureData, int32_t *errCode) +{ + if (this->verify_ == nullptr) { + *errCode = HCF_INVALID_PARAMS; + return false; + } + *errCode = HCF_SUCCESS; + return this->verify_->verify(verify_, data, &signatureData); +} + +HcfResult VerifyImpl::Recover(HcfBlob input, HcfBlob *output) +{ + if (this->verify_ == nullptr) { + return HCF_INVALID_PARAMS; + } + return this->verify_->recover(verify_, &input, output); +} + +HcfResult VerifyImpl::SetVerifySpecByNum(int32_t itemValue) +{ + if (this->verify_ == nullptr) { + return HCF_INVALID_PARAMS; + } + return this->verify_->setVerifySpecInt(verify_, PSS_SALT_LEN_INT, itemValue); +} + +HcfResult VerifyImpl::SetVerifySpecByArr(HcfBlob itemValue) +{ + if (this->verify_ == nullptr) { + return HCF_INVALID_PARAMS; + } + return this->verify_->setVerifySpecUint8Array(verify_, SM2_USER_ID_UINT8ARR, itemValue); +} + +HcfResult VerifyImpl::GetVerifySpecString(SignSpecItem item, char *itemValue) +{ + if (this->verify_ == nullptr) { + return HCF_INVALID_PARAMS; + } + return this->verify_->getVerifySpecString(verify_, item, &itemValue); +} + +HcfResult VerifyImpl::GetVerifySpecNum(SignSpecItem item, int32_t *itemValue) +{ + if (this->verify_ == nullptr) { + return HCF_INVALID_PARAMS; + } + return this->verify_->getVerifySpecInt(verify_, item, itemValue); +} +} +} \ No newline at end of file diff --git a/frameworks/crypto_operation/cipher.c b/frameworks/crypto_operation/cipher.c index add67e4887ba09af144bd420661244a6591cf58d..aab445a791b7be7be4b682692e59543343f30b2c 100644 --- a/frameworks/crypto_operation/cipher.c +++ b/frameworks/crypto_operation/cipher.c @@ -214,7 +214,7 @@ static HcfResult SetCipherSpecUint8Array(HcfCipher *self, CipherSpecItem item, H { // only implemented for OAEP_MGF1_PSRC_UINT8ARR // if pSource == NULL or len == 0, it means cleaning the pSource - if (self == NULL || pSource.len < 0) { + if (self == NULL) { LOGE("Invalid input parameter."); return HCF_INVALID_PARAMS; } diff --git a/frameworks/crypto_operation/kdf.c b/frameworks/crypto_operation/kdf.c index 1b4ce47817eeb7c39512a1c821d3945d3923582d..1d45072a8998f8ff642a5d9cb26f21eb11c59abc 100644 --- a/frameworks/crypto_operation/kdf.c +++ b/frameworks/crypto_operation/kdf.c @@ -152,15 +152,15 @@ static void DestroyKdf(HcfObjectBase *self) HcfFree(impl); } -HcfResult HcfKdfCreate(const char *algoName, HcfKdf **returnObj) +HcfResult HcfKdfCreate(const char *transformation, HcfKdf **returnObj) { - if ((!HcfIsStrValid(algoName, HCF_MAX_ALGO_NAME_LEN)) || (returnObj == NULL)) { + if ((!HcfIsStrValid(transformation, HCF_MAX_ALGO_NAME_LEN)) || (returnObj == NULL)) { LOGE("Invalid input params while creating kdf!"); return HCF_INVALID_PARAMS; } HcfKdfDeriveParams params = { 0 }; - if (ParseAndSetParameter(algoName, ¶ms, ParseKdfParams) != HCF_SUCCESS) { + if (ParseAndSetParameter(transformation, ¶ms, ParseKdfParams) != HCF_SUCCESS) { LOGE("Failed to parse params!"); return HCF_INVALID_PARAMS; } @@ -175,7 +175,7 @@ HcfResult HcfKdfCreate(const char *algoName, HcfKdf **returnObj) LOGE("Failed to allocate returnGenerator memory!"); return HCF_ERR_MALLOC; } - if (strcpy_s(returnGenerator->algoName, HCF_MAX_ALGO_NAME_LEN, algoName) != EOK) { + if (strcpy_s(returnGenerator->algoName, HCF_MAX_ALGO_NAME_LEN, transformation) != EOK) { LOGE("Failed to copy algoName!"); HcfFree(returnGenerator); return HCF_INVALID_PARAMS; diff --git a/frameworks/crypto_operation/md.c b/frameworks/crypto_operation/md.c index 0a921fd8395acd803c1352e3a6212850b074542e..888f3bebaf0eef31ab88b9de75068b8eb21c790f 100644 --- a/frameworks/crypto_operation/md.c +++ b/frameworks/crypto_operation/md.c @@ -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) diff --git a/frameworks/crypto_operation/rand.c b/frameworks/crypto_operation/rand.c index 99018add125280c94ea72148656f3d801a3e2811..0f4227d8fa857204ce3396263d2d8a6ec4dec8c2 100644 --- a/frameworks/crypto_operation/rand.c +++ b/frameworks/crypto_operation/rand.c @@ -18,7 +18,11 @@ #include #include #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; diff --git a/frameworks/frameworks.gni b/frameworks/frameworks.gni index 623a379253235fdbd20ddcdcd699a8cd4b2e789b..957383a1ad10b002edc1b20ed1e668daa7490ea7 100644 --- a/frameworks/frameworks.gni +++ b/frameworks/frameworks.gni @@ -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 diff --git a/frameworks/js/jsi/BUILD.gn b/frameworks/js/jsi/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..6ac9a4ce9bf84ed4fa63482e2e6e0b8a94028aa2 --- /dev/null +++ b/frameworks/js/jsi/BUILD.gn @@ -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" ] +} diff --git a/frameworks/js/jsi/inc/jsi_api.h b/frameworks/js/jsi/inc/jsi_api.h new file mode 100644 index 0000000000000000000000000000000000000000..723492524fde0ddf9bcb7828bc034479f64ad000 --- /dev/null +++ b/frameworks/js/jsi/inc/jsi_api.h @@ -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 diff --git a/frameworks/js/jsi/inc/jsi_api_common.h b/frameworks/js/jsi/inc/jsi_api_common.h new file mode 100644 index 0000000000000000000000000000000000000000..e80dffb5e1845d371c33c539a45969be50a52379 --- /dev/null +++ b/frameworks/js/jsi/inc/jsi_api_common.h @@ -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 diff --git a/frameworks/js/jsi/inc/jsi_api_errcode.h b/frameworks/js/jsi/inc/jsi_api_errcode.h new file mode 100644 index 0000000000000000000000000000000000000000..6563a42968b6f1c429899e4850e209b3635d2e4a --- /dev/null +++ b/frameworks/js/jsi/inc/jsi_api_errcode.h @@ -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 diff --git a/frameworks/js/jsi/inc/jsi_list.h b/frameworks/js/jsi/inc/jsi_list.h new file mode 100644 index 0000000000000000000000000000000000000000..06d25374fafbd9042c09d4c1d46aded76c514228 --- /dev/null +++ b/frameworks/js/jsi/inc/jsi_list.h @@ -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 diff --git a/frameworks/js/jsi/inc/jsi_utils.h b/frameworks/js/jsi/inc/jsi_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..e3ee876b6a115cd896b72a9985261e0b415f5ef0 --- /dev/null +++ b/frameworks/js/jsi/inc/jsi_utils.h @@ -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 + +#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 diff --git a/frameworks/js/jsi/src/jsi_api.cpp b/frameworks/js/jsi/src/jsi_api.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3312a0b3e603f2a279282bd269c2f304c37d24f5 --- /dev/null +++ b/frameworks/js/jsi/src/jsi_api.cpp @@ -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 diff --git a/frameworks/js/jsi/src/jsi_api_common.cpp b/frameworks/js/jsi/src/jsi_api_common.cpp new file mode 100644 index 0000000000000000000000000000000000000000..36db62386968ed51f5c3e67b7880eb9757772d5e --- /dev/null +++ b/frameworks/js/jsi/src/jsi_api_common.cpp @@ -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 diff --git a/frameworks/js/jsi/src/jsi_api_errcode.cpp b/frameworks/js/jsi/src/jsi_api_errcode.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f9707bbc8fcc5a12841f6f753001349d45e2ac59 --- /dev/null +++ b/frameworks/js/jsi/src/jsi_api_errcode.cpp @@ -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 diff --git a/frameworks/js/jsi/src/jsi_list.cpp b/frameworks/js/jsi/src/jsi_list.cpp new file mode 100644 index 0000000000000000000000000000000000000000..35cc91ededb22f03484381368918945571906a7f --- /dev/null +++ b/frameworks/js/jsi/src/jsi_list.cpp @@ -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 = static_cast(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(reinterpret_cast(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(reinterpret_cast(obj->objAddr)); + HcfFree(obj); + obj = nullptr; + } +} + +} // ACELite +} // OHOS diff --git a/frameworks/js/jsi/src/jsi_md.cpp b/frameworks/js/jsi/src/jsi_md.cpp new file mode 100644 index 0000000000000000000000000000000000000000..08bf0109bf08833c3d3570fd44319d78a457c510 --- /dev/null +++ b/frameworks/js/jsi/src/jsi_md.cpp @@ -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 "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(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(static_cast(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!"); + return JSI::CreateUndefined(); + } + HcfMd *mdObj = reinterpret_cast((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 = reinterpret_cast((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!"); + return ThrowErrorCodeResult(errCode); + } + + 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!"); + return JSI::CreateUndefined(); + } + HcfMd *mdObj = reinterpret_cast((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 = reinterpret_cast((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 = reinterpret_cast((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 diff --git a/frameworks/js/jsi/src/jsi_rand.cpp b/frameworks/js/jsi/src/jsi_rand.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9cb57bb5ce0e7b36baa54a835e6d4943271974ec --- /dev/null +++ b/frameworks/js/jsi/src/jsi_rand.cpp @@ -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(static_cast(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) +{ + if ((args == nullptr) || (argsNum != ARRAY_MAX_SIZE) || (args[ARRAY_INDEX_ONE] == nullptr)) { + LOGE("GenerateRandom params is err!"); + return JSI::CreateUndefined(); + } + + HcfRand *randObj = reinterpret_cast((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(); + } + + 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) +{ + if ((args == nullptr) || (argsNum != ARRAY_INDEX_ONE)) { + LOGE("GenerateRandomSync params is err"); + return ThrowErrorCodeResult(HCF_INVALID_PARAMS); + } + + HcfRand *randObj = reinterpret_cast((uint32_t)JSI::GetNumberProperty(thisVal, "randObj")); + if (randObj == nullptr) { + LOGE("GenerateRandom randObj is null!!"); + 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 = reinterpret_cast((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 diff --git a/frameworks/js/jsi/src/jsi_utils.cpp b/frameworks/js/jsi/src/jsi_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3320f1d296d54e466a77a76676b830e3c7d91c72 --- /dev/null +++ b/frameworks/js/jsi/src/jsi_utils.cpp @@ -0,0 +1,90 @@ +/* + * 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; + HcfResult ret = HCF_SUCCESS; + do { + uint8_t *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 = reinterpret_cast(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 diff --git a/frameworks/js/napi/crypto/BUILD.gn b/frameworks/js/napi/crypto/BUILD.gn index 4adb38c4f90bfb92ac1ce0819413579a37ffcd6c..5cd065542e1526e78f365cbca40e74340713f7ab 100644 --- a/frameworks/js/napi/crypto/BUILD.gn +++ b/frameworks/js/napi/crypto/BUILD.gn @@ -16,6 +16,7 @@ import("//base/security/crypto_framework/frameworks/frameworks.gni") import("//build/ohos.gni") ohos_shared_library("cryptoframework_napi") { + branch_protector_ret = "pac_ret" subsystem_name = "security" part_name = "crypto_framework" relative_install_dir = "module/security" diff --git a/frameworks/js/napi/crypto/src/napi_asy_key_generator.cpp b/frameworks/js/napi/crypto/src/napi_asy_key_generator.cpp index b301fdeb58024cedd646473bee966a9dcadd9c97..86945889aa63b703dd977e5aa8d2e46d07c01974 100644 --- a/frameworks/js/napi/crypto/src/napi_asy_key_generator.cpp +++ b/frameworks/js/napi/crypto/src/napi_asy_key_generator.cpp @@ -132,7 +132,7 @@ static void FreeConvertKeyCtx(napi_env env, ConvertKeyCtx *ctx) HcfBlobDataFree(ctx->pubKey); HcfFree(ctx->pubKey); - HcfBlobDataFree(ctx->priKey); + HcfBlobDataClearAndFree(ctx->priKey); HcfFree(ctx->priKey); HcfFree(ctx); } @@ -156,7 +156,6 @@ static void FreeConvertPemKeyCtx(napi_env env, ConvertPemKeyCtx *ctx) ctx->pubKey = ""; ctx->priKey = ""; HcfFree(ctx); - ctx = nullptr; } static bool BuildGenKeyPairCtx(napi_env env, napi_callback_info info, GenKeyPairCtx *ctx) @@ -172,7 +171,7 @@ static bool BuildGenKeyPairCtx(napi_env env, napi_callback_info info, GenKeyPair } ctx->asyncType = isCallback(env, argv[0], argc, expectedArgc) ? ASYNC_CALLBACK : ASYNC_PROMISE; - NapiAsyKeyGenerator *napiGenerator; + NapiAsyKeyGenerator *napiGenerator = nullptr; napi_status status = napi_unwrap(env, thisVar, reinterpret_cast(&napiGenerator)); if (status != napi_ok || napiGenerator == nullptr) { LOGE("failed to unwrap napi asyKeyGenerator obj."); @@ -287,7 +286,7 @@ static bool BuildConvertKeyCtx(napi_env env, napi_callback_info info, ConvertKey } ctx->asyncType = isCallback(env, argv[expectedArgc - 1], argc, expectedArgc) ? ASYNC_CALLBACK : ASYNC_PROMISE; - NapiAsyKeyGenerator *napiGenerator; + NapiAsyKeyGenerator *napiGenerator = nullptr; napi_status status = napi_unwrap(env, thisVar, reinterpret_cast(&napiGenerator)); if (status != napi_ok || napiGenerator == nullptr) { LOGE("failed to unwrap napi asyKeyGenerator obj."); @@ -329,7 +328,7 @@ static bool BuildConvertPemKeyCtx(napi_env env, napi_callback_info info, Convert LOGE("wrong argument num. require %zu arguments. [Argc]: %zu!", expectedArgc, argc); return false; } - NapiAsyKeyGenerator *napiGenerator; + NapiAsyKeyGenerator *napiGenerator = nullptr; napi_status status = napi_unwrap(env, thisVar, reinterpret_cast(&napiGenerator)); if (status != napi_ok || napiGenerator == nullptr) { LOGE("failed to unwrap napi asyKeyGenerator obj."); @@ -761,7 +760,7 @@ static void HcfFreePubKeyAndPriKey(HcfBlob *pubKey, HcfBlob *priKey) { HcfBlobDataFree(pubKey); HcfFree(pubKey); - HcfBlobDataFree(priKey); + HcfBlobDataClearAndFree(priKey); HcfFree(priKey); } @@ -863,7 +862,7 @@ napi_value NapiAsyKeyGenerator::JsConvertPemKeySync(napi_env env, napi_callback_ return nullptr; } - NapiAsyKeyGenerator *napiGenerator; + NapiAsyKeyGenerator *napiGenerator = nullptr; napi_status status = napi_unwrap(env, thisVar, reinterpret_cast(&napiGenerator)); if (status != napi_ok || napiGenerator == nullptr) { LOGE("failed to unwrap napi asyKeyGenerator obj."); @@ -903,8 +902,7 @@ napi_value NapiAsyKeyGenerator::JsConvertPemKeySync(napi_env env, napi_callback_ return nullptr; } - napi_value instance = nullptr; - instance = napiKeyPair->ConvertToJsKeyPair(env); + napi_value instance = napiKeyPair->ConvertToJsKeyPair(env); return instance; } @@ -936,7 +934,6 @@ static napi_value NapiWrapAsyKeyGen(napi_env env, napi_value instance, NapiAsyKe napi_value NapiAsyKeyGenerator::CreateJsAsyKeyGenerator(napi_env env, napi_callback_info info) { - LOGD("Enter CreateJsAsyKeyGenerator..."); size_t expectedArgc = PARAMS_NUM_ONE; size_t argc = expectedArgc; napi_value argv[PARAMS_NUM_ONE] = { nullptr }; diff --git a/frameworks/js/napi/crypto/src/napi_asy_key_spec_generator.cpp b/frameworks/js/napi/crypto/src/napi_asy_key_spec_generator.cpp index d0b470f7665a0cad0dd1244cf482c4f8a9918000..442c3289aa599540d51705f2564cc361bd44e284 100644 --- a/frameworks/js/napi/crypto/src/napi_asy_key_spec_generator.cpp +++ b/frameworks/js/napi/crypto/src/napi_asy_key_spec_generator.cpp @@ -85,7 +85,7 @@ static bool BuildAsyKeyCtx(napi_env env, napi_callback_info info, AsyKeyCtx *ctx } ctx->asyncType = isCallback(env, argv[0], argc, expectedArgc) ? ASYNC_CALLBACK : ASYNC_PROMISE; - NapiAsyKeyGeneratorBySpec *napiGenerator; + NapiAsyKeyGeneratorBySpec *napiGenerator = nullptr; napi_status status = napi_unwrap(env, thisVar, reinterpret_cast(&napiGenerator)); if (status != napi_ok || napiGenerator == nullptr) { LOGE("failed to unwrap napi asyKeyGenerator obj."); @@ -111,7 +111,7 @@ static bool GetAsyKeyGenerator(napi_env env, napi_callback_info info, HcfAsyKeyG napi_value thisVar = nullptr; napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); - NapiAsyKeyGeneratorBySpec *napiGenerator; + NapiAsyKeyGeneratorBySpec *napiGenerator = nullptr; napi_status status = napi_unwrap(env, thisVar, reinterpret_cast(&napiGenerator)); if (status != napi_ok || napiGenerator == nullptr) { LOGE("failed to unwrap napi asyKeyGenerator obj."); diff --git a/frameworks/js/napi/crypto/src/napi_cipher.cpp b/frameworks/js/napi/crypto/src/napi_cipher.cpp index 0e404dcb7964e21f9b20259e65f7187bcd5747a5..ac947b7dbefcd20d457f41b739f4da1e66c40d79 100644 --- a/frameworks/js/napi/crypto/src/napi_cipher.cpp +++ b/frameworks/js/napi/crypto/src/napi_cipher.cpp @@ -648,7 +648,7 @@ napi_value NapiCipher::JsCipherUpdateSync(napi_env env, napi_callback_info info) } HcfBlob output = { .data = nullptr, .len = 0 }; errCode = cipher->update(cipher, &input, &output); - HcfFree(input.data); + HcfBlobDataClearAndFree(&input); if (errCode != HCF_SUCCESS) { LOGE("failed to update!"); napi_throw(env, GenerateBusinessError(env, errCode, "update fail!")); @@ -657,7 +657,7 @@ napi_value NapiCipher::JsCipherUpdateSync(napi_env env, napi_callback_info info) napi_value instance = nullptr; errCode = ConvertDataBlobToNapiValue(env, &output, &instance); - HcfFree(output.data); + HcfBlobDataClearAndFree(&output); if (errCode != HCF_SUCCESS) { LOGE("cipher update convert dataBlob to napi_value failed!"); napi_throw(env, GenerateBusinessError(env, errCode, "cipher update convert dataBlob to napi_value failed!")); @@ -721,7 +721,7 @@ napi_value NapiCipher::JsCipherDoFinalSync(napi_env env, napi_callback_info info } HcfBlob output = { .data = nullptr, .len = 0 }; HcfResult res = cipher->doFinal(cipher, input, &output); - HcfBlobDataFree(input); + HcfBlobDataClearAndFree(input); if (res != HCF_SUCCESS) { LOGE("failed to do final!"); napi_throw(env, GenerateBusinessError(env, res, "do final fail!")); @@ -730,7 +730,7 @@ napi_value NapiCipher::JsCipherDoFinalSync(napi_env env, napi_callback_info info napi_value instance = nullptr; res = ConvertDataBlobToNapiValue(env, &output, &instance); - HcfFree(output.data); + HcfBlobDataClearAndFree(&output); if (res != HCF_SUCCESS) { LOGE("cipher convert dataBlob to napi_value failed!"); napi_throw(env, GenerateBusinessError(env, res, "cipher convert dataBlob to napi_value failed!")); @@ -851,12 +851,10 @@ napi_value NapiCipher::JsSetCipherSpec(napi_env env, napi_callback_info info) LOGE("get JsGetCipherSpecUint8Array failed!"); return nullptr; } - HcfBlob *pSource = nullptr; - pSource = GetBlobFromNapiUint8Arr(env, argv[1]); + HcfBlob *pSource = GetBlobFromNapiUint8Arr(env, argv[1]); if (pSource == nullptr || pSource->len == 0) { LOGE("failed to get pSource."); - napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, - "[pSource]: must be of the DataBlob type.")); + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "[pSource]: must be of the DataBlob type.")); return nullptr; } napi_status status = napi_unwrap(env, thisVar, reinterpret_cast(&napiCipher)); diff --git a/frameworks/js/napi/crypto/src/napi_ecc_key_util.cpp b/frameworks/js/napi/crypto/src/napi_ecc_key_util.cpp index 00edecbcbbc3af480a0136649e02ca584cc788ab..0cd9ceed90d52c09e6b4f0c5607b6e1e924e50f8 100644 --- a/frameworks/js/napi/crypto/src/napi_ecc_key_util.cpp +++ b/frameworks/js/napi/crypto/src/napi_ecc_key_util.cpp @@ -59,6 +59,7 @@ napi_value NapiECCKeyUtil::JsGenECCCommonParamsSpec(napi_env env, napi_callback_ } napi_value instance = ConvertEccCommParamsSpecToNapiValue(env, eccCommParamsSpec); FreeEccCommParamsSpec(eccCommParamsSpec); + HcfFree(eccCommParamsSpec); return instance; } diff --git a/frameworks/js/napi/crypto/src/napi_kdf.cpp b/frameworks/js/napi/crypto/src/napi_kdf.cpp index d7d8318ab7860a3174847a17b7099fa220456d5b..9a99858a5b710178b486a767abd4789d49758226 100644 --- a/frameworks/js/napi/crypto/src/napi_kdf.cpp +++ b/frameworks/js/napi/crypto/src/napi_kdf.cpp @@ -595,7 +595,6 @@ napi_value NapiKdf::JsKdfGenerateSecretSync(napi_env env, napi_callback_info inf LOGE("KDF generateSecret failed!"); napi_throw(env, GenerateBusinessError(env, errCode, "KDF generateSecret failed!")); FreeKdfParamsSpec(paramsSpec); - paramsSpec = nullptr; return nullptr; } napi_value returnBlob = NewKdfJsGenSecretSyncWork(env, paramsSpec); @@ -635,7 +634,6 @@ napi_value NapiKdf::KdfConstructor(napi_env env, napi_callback_info info) napi_value NapiKdf::CreateJsKdf(napi_env env, napi_callback_info info) { - LOGD("Enter CreateKdf..."); size_t expectedArgc = ARGS_SIZE_ONE; size_t argc = expectedArgc; napi_value argv[ARGS_SIZE_ONE] = { nullptr }; diff --git a/frameworks/js/napi/crypto/src/napi_key.cpp b/frameworks/js/napi/crypto/src/napi_key.cpp index deb23b3459974328c81cc59aa06fe105f1234a1b..f6a816d7df28d704e8322aa3a40d8000fbe16f7f 100644 --- a/frameworks/js/napi/crypto/src/napi_key.cpp +++ b/frameworks/js/napi/crypto/src/napi_key.cpp @@ -113,7 +113,7 @@ napi_value NapiKey::JsGetEncoded(napi_env env, napi_callback_info info) return nullptr; } napi_value instance = ConvertBlobToNapiValue(env, &blob); - HcfBlobDataFree(&blob); + HcfBlobDataClearAndFree(&blob); return instance; } diff --git a/frameworks/js/napi/crypto/src/napi_key_agreement.cpp b/frameworks/js/napi/crypto/src/napi_key_agreement.cpp index 12aa7129cdcbb36e4cbed72ad9de6f7d76a2bd49..0e6ff2dd6d844310a84d1a0d19717ae092084f1f 100644 --- a/frameworks/js/napi/crypto/src/napi_key_agreement.cpp +++ b/frameworks/js/napi/crypto/src/napi_key_agreement.cpp @@ -348,7 +348,7 @@ napi_value NapiKeyAgreement::JsGenerateSecretSync(napi_env env, napi_callback_in napi_value instance = nullptr; ret = ConvertDataBlobToNapiValue(env, &returnSecret, &instance); - HcfBlobDataFree(&returnSecret); + HcfBlobDataClearAndFree(&returnSecret); if (ret != HCF_SUCCESS) { LOGE("key agreement convert dataBlob to napi_value failed!"); napi_throw(env, GenerateBusinessError(env, ret, "key agreement convert dataBlob to napi_value failed!")); diff --git a/frameworks/js/napi/crypto/src/napi_mac.cpp b/frameworks/js/napi/crypto/src/napi_mac.cpp index beecde6e4cc59e24f6a234ffe63635a85ab82675..1d91c44e30defb7e41f16ffeab053f5981fb6b9b 100644 --- a/frameworks/js/napi/crypto/src/napi_mac.cpp +++ b/frameworks/js/napi/crypto/src/napi_mac.cpp @@ -87,7 +87,6 @@ static void FreeCryptoFwkCtx(napi_env env, MacCtx *context) context->errMsg = nullptr; context->mac = nullptr; HcfFree(context); - context = nullptr; } static void ReturnCallbackResult(napi_env env, MacCtx *context, napi_value result) @@ -642,7 +641,6 @@ static napi_value NapiWrapMac(napi_env env, napi_value instance, NapiMac *macNap if (status != napi_ok) { napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "failed to wrap NapiMac obj!")); delete macNapiObj; - macNapiObj = nullptr; LOGE("failed to wrap NapiMac obj!"); return nullptr; } @@ -651,7 +649,6 @@ static napi_value NapiWrapMac(napi_env env, napi_value instance, NapiMac *macNap napi_value NapiMac::CreateMac(napi_env env, napi_callback_info info) { - LOGD("Enter CreateMac..."); size_t expectedArgc = ARGS_SIZE_ONE; size_t argc = expectedArgc; napi_value argv[ARGS_SIZE_ONE] = { nullptr }; diff --git a/frameworks/js/napi/crypto/src/napi_md.cpp b/frameworks/js/napi/crypto/src/napi_md.cpp index c2751c4761a1dcfae2823aacd48eb66afdd7c1fc..7ebe265d4e74a114fe4e937c92e843059f8b34cc 100644 --- a/frameworks/js/napi/crypto/src/napi_md.cpp +++ b/frameworks/js/napi/crypto/src/napi_md.cpp @@ -80,7 +80,6 @@ static void FreeCryptoFwkCtx(napi_env env, MdCtx *context) context->errMsg = nullptr; context->md = nullptr; HcfFree(context); - context = nullptr; } static void ReturnCallbackResult(napi_env env, MdCtx *context, napi_value result) @@ -481,7 +480,6 @@ static napi_value NapiWrapMd(napi_env env, napi_value instance, NapiMd *mdNapiOb if (status != napi_ok) { napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "failed to wrap NapiMd obj!")); delete mdNapiObj; - mdNapiObj = nullptr; LOGE("failed to wrap NapiMd obj!"); return nullptr; } @@ -490,7 +488,6 @@ static napi_value NapiWrapMd(napi_env env, napi_value instance, NapiMd *mdNapiOb napi_value NapiMd::CreateMd(napi_env env, napi_callback_info info) { - LOGD("Enter CreateMd..."); size_t expectedArgc = ARGS_SIZE_ONE; size_t argc = expectedArgc; napi_value argv[ARGS_SIZE_ONE] = { nullptr }; diff --git a/frameworks/js/napi/crypto/src/napi_pri_key.cpp b/frameworks/js/napi/crypto/src/napi_pri_key.cpp index ffc93b4a8a1f71b06e669a1e605a5b4513a7323c..25ae8f2c2310b7439bd7d7b824a5c8071b6b407c 100644 --- a/frameworks/js/napi/crypto/src/napi_pri_key.cpp +++ b/frameworks/js/napi/crypto/src/napi_pri_key.cpp @@ -90,7 +90,13 @@ napi_value NapiPriKey::JsGetEncoded(napi_env env, napi_callback_info info) } napi_value instance = ConvertBlobToNapiValue(env, &returnBlob); - HcfBlobDataFree(&returnBlob); + if (instance == nullptr) { + HcfBlobDataFree(&returnBlob); + napi_throw(env, GenerateBusinessError(env, res, "covert blob to napi value failed.")); + LOGE("covert blob to napi value failed."); + return nullptr; + } + HcfBlobDataClearAndFree(&returnBlob); return instance; } @@ -176,7 +182,13 @@ static napi_value GetAsyKeySpecBigInt(napi_env env, AsyKeySpecItem item, HcfPriK } napi_value instance = ConvertBigIntToNapiValue(env, &returnBigInteger); + (void)memset_s(returnBigInteger.data, returnBigInteger.len, 0, returnBigInteger.len); HcfFree(returnBigInteger.data); + if (instance == nullptr) { + napi_throw(env, GenerateBusinessError(env, res, "covert bigInt to napi value failed.")); + LOGE("covert bigInt to napi value failed."); + return nullptr; + } return instance; } @@ -296,8 +308,9 @@ napi_value NapiPriKey::JsGetEncodedDer(napi_env env, napi_callback_info info) LOGE("get private key encodeDer fail."); return nullptr; } + napi_value instance = ConvertBlobToNapiValue(env, &returnBlob); - HcfBlobDataFree(&returnBlob); + HcfBlobDataClearAndFree(&returnBlob); return instance; } diff --git a/frameworks/js/napi/crypto/src/napi_pub_key.cpp b/frameworks/js/napi/crypto/src/napi_pub_key.cpp index 38109e73a9c376b9f7c9ee78a3aeaddbb5b963a0..675cba125f05d87f7a01185bdbbee7977c6542a1 100644 --- a/frameworks/js/napi/crypto/src/napi_pub_key.cpp +++ b/frameworks/js/napi/crypto/src/napi_pub_key.cpp @@ -90,6 +90,12 @@ napi_value NapiPubKey::JsGetEncoded(napi_env env, napi_callback_info info) } napi_value instance = ConvertBlobToNapiValue(env, &returnBlob); + if (instance == nullptr) { + HcfBlobDataFree(&returnBlob); + napi_throw(env, GenerateBusinessError(env, res, "covert blob to napi value failed.")); + LOGE("covert blob to napi value failed."); + return nullptr; + } HcfBlobDataFree(&returnBlob); return instance; } @@ -136,6 +142,12 @@ napi_value NapiPubKey::JsGetEncodedDer(napi_env env, napi_callback_info info) } napi_value instance = ConvertBlobToNapiValue(env, &returnBlob); + if (instance == nullptr) { + HcfBlobDataFree(&returnBlob); + napi_throw(env, GenerateBusinessError(env, res, "covert blob to napi value failed.")); + LOGE("covert blob to napi value failed."); + return nullptr; + } HcfBlobDataFree(&returnBlob); return instance; } @@ -199,6 +211,12 @@ static napi_value GetAsyKeySpecBigInt(napi_env env, AsyKeySpecItem item, HcfPubK } napi_value instance = ConvertBigIntToNapiValue(env, &returnBigInteger); + if (instance == nullptr) { + HcfFree(returnBigInteger.data); + napi_throw(env, GenerateBusinessError(env, res, "covert bigInt to napi value failed.")); + LOGE("covert bigInt to napi value failed."); + return nullptr; + } HcfFree(returnBigInteger.data); return instance; } diff --git a/frameworks/js/napi/crypto/src/napi_rand.cpp b/frameworks/js/napi/crypto/src/napi_rand.cpp index 212a7c511434cbe6d6389be8c050e551035bb3ef..4b3c9bfd47c74e542e60237929de7bb3345234c9 100644 --- a/frameworks/js/napi/crypto/src/napi_rand.cpp +++ b/frameworks/js/napi/crypto/src/napi_rand.cpp @@ -80,7 +80,6 @@ static void FreeCryptoFwkCtx(napi_env env, RandCtx *context) context->errMsg = nullptr; context->rand = nullptr; HcfFree(context); - context = nullptr; } static void ReturnCallbackResult(napi_env env, RandCtx *context, napi_value result) @@ -315,7 +314,7 @@ napi_value NapiRand::JsSetSeed(napi_env env, napi_callback_info info) } napi_status status = napi_unwrap(env, thisVar, reinterpret_cast(&napiRand)); if (status != napi_ok || napiRand == nullptr) { - HcfBlobDataFree(seedBlob); + HcfBlobDataClearAndFree(seedBlob); HcfFree(seedBlob); napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "failed to unwrap NapiRand obj!")); LOGE("failed to unwrap NapiRand obj!"); @@ -323,7 +322,7 @@ napi_value NapiRand::JsSetSeed(napi_env env, napi_callback_info info) } HcfRand *rand = napiRand->GetRand(); if (rand == nullptr) { - HcfBlobDataFree(seedBlob); + HcfBlobDataClearAndFree(seedBlob); HcfFree(seedBlob); napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "fail to get rand obj!")); LOGE("fail to get rand obj!"); @@ -331,13 +330,13 @@ napi_value NapiRand::JsSetSeed(napi_env env, napi_callback_info info) } HcfResult res = rand->setSeed(rand, seedBlob); if (res != HCF_SUCCESS) { - HcfBlobDataFree(seedBlob); + HcfBlobDataClearAndFree(seedBlob); HcfFree(seedBlob); napi_throw(env, GenerateBusinessError(env, res, "set seed failed.")); LOGD("[error] set seed failed."); return nullptr; } - HcfBlobDataFree(seedBlob); + HcfBlobDataClearAndFree(seedBlob); HcfFree(seedBlob); return thisVar; } diff --git a/frameworks/js/napi/crypto/src/napi_sign.cpp b/frameworks/js/napi/crypto/src/napi_sign.cpp index cf7fc77a896a90c8a782143907ae0534ea7fe050..213550c43166a9743b6794d72c130d808c84d887 100644 --- a/frameworks/js/napi/crypto/src/napi_sign.cpp +++ b/frameworks/js/napi/crypto/src/napi_sign.cpp @@ -170,7 +170,7 @@ static bool BuildSignJsInitCtx(napi_env env, napi_callback_info info, SignInitCt napi_value thisVar = nullptr; size_t expectedArgc = PARAMS_NUM_TWO; size_t argc = expectedArgc; - napi_value argv[PARAMS_NUM_TWO] = { nullptr, nullptr }; + napi_value argv[PARAMS_NUM_TWO] = { nullptr }; napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); if (argc != expectedArgc && argc != expectedArgc - 1) { LOGE("wrong argument num. require %zu or %zu arguments. [Argc]: %zu!", expectedArgc - 1, expectedArgc, argc); @@ -220,7 +220,7 @@ static bool BuildSignJsUpdateCtx(napi_env env, napi_callback_info info, SignUpda napi_value thisVar = nullptr; size_t expectedArgc = PARAMS_NUM_TWO; size_t argc = expectedArgc; - napi_value argv[PARAMS_NUM_TWO] = { nullptr, nullptr }; + napi_value argv[PARAMS_NUM_TWO] = { nullptr }; napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); if ((argc != expectedArgc) && (argc != expectedArgc - 1)) { LOGE("wrong argument num. require %zu or %zu arguments. [Argc]: %zu!", expectedArgc - 1, expectedArgc, argc); @@ -263,7 +263,7 @@ static bool BuildSignJsDoFinalCtx(napi_env env, napi_callback_info info, SignDoF napi_value thisVar = nullptr; size_t expectedArgc = PARAMS_NUM_TWO; size_t argc = expectedArgc; - napi_value argv[PARAMS_NUM_TWO] = { nullptr, nullptr }; + napi_value argv[PARAMS_NUM_TWO] = { nullptr }; napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); if ((argc != expectedArgc) && (argc != expectedArgc - 1)) { LOGE("wrong argument num. require %zu or %zu arguments. [Argc]: %zu!", expectedArgc - 1, expectedArgc, argc); @@ -767,7 +767,6 @@ static napi_value NapiWrapSign(napi_env env, napi_value instance, NapiSign *napi if (status != napi_ok) { LOGE("failed to wrap napiSign obj!"); delete napiSign; - napiSign = nullptr; return nullptr; } return instance; @@ -775,7 +774,6 @@ static napi_value NapiWrapSign(napi_env env, napi_value instance, NapiSign *napi napi_value NapiSign::CreateJsSign(napi_env env, napi_callback_info info) { - LOGD("Enter CreateJsSign..."); size_t expectedArgc = PARAMS_NUM_ONE; size_t argc = expectedArgc; napi_value argv[PARAMS_NUM_ONE] = { nullptr }; diff --git a/frameworks/js/napi/crypto/src/napi_sym_key_generator.cpp b/frameworks/js/napi/crypto/src/napi_sym_key_generator.cpp index 1b51cd26e3ec1b44f32a2035905352e66afa047a..321d1d0ff7fd5d43750ef1ed9870f69618f7e06e 100644 --- a/frameworks/js/napi/crypto/src/napi_sym_key_generator.cpp +++ b/frameworks/js/napi/crypto/src/napi_sym_key_generator.cpp @@ -90,7 +90,7 @@ static bool BuildContextForGenerateKey(napi_env env, napi_callback_info info, Sy return false; } context->asyncType = isCallback(env, argv[expectedArgc - 1], argc, expectedArgc) ? ASYNC_CALLBACK : ASYNC_PROMISE; - NapiSymKeyGenerator *napiGenerator; + NapiSymKeyGenerator *napiGenerator = nullptr; napi_status status = napi_unwrap(env, thisVar, reinterpret_cast(&napiGenerator)); if (status != napi_ok || napiGenerator == nullptr) { LOGE("failed to unwrap NapiSymKeyGenerator obj!"); @@ -129,7 +129,7 @@ static bool BuildContextForConvertKey(napi_env env, napi_callback_info info, Sym } context->asyncType = isCallback(env, argv[expectedArgc - 1], argc, expectedArgc) ? ASYNC_CALLBACK : ASYNC_PROMISE; - NapiSymKeyGenerator *napiGenerator; + NapiSymKeyGenerator *napiGenerator = nullptr; napi_status status = napi_unwrap(env, thisVar, reinterpret_cast(&napiGenerator)); if (status != napi_ok || napiGenerator == nullptr) { LOGE("failed to unwrap NapiSymKeyGenerator obj!"); @@ -477,7 +477,7 @@ napi_value NapiSymKeyGenerator::JsConvertKeySync(napi_env env, napi_callback_inf HcfSymKey *key = nullptr; HcfResult ret = generator->convertSymKey(generator, keyMaterial, &key); - HcfBlobDataFree(keyMaterial); + HcfBlobDataClearAndFree(keyMaterial); HcfFree(keyMaterial); if (ret != HCF_SUCCESS) { napi_throw(env, GenerateBusinessError(env, ret, "convertSymKey key failed!")); diff --git a/frameworks/js/napi/crypto/src/napi_utils.cpp b/frameworks/js/napi/crypto/src/napi_utils.cpp index cb55d6c7e9aecc704d889b6a154234a76f5e82c7..b95168b4423df91fa8154c8823f17be39d35aee1 100644 --- a/frameworks/js/napi/crypto/src/napi_utils.cpp +++ b/frameworks/js/napi/crypto/src/napi_utils.cpp @@ -245,9 +245,6 @@ static HcfBlob *GetAadFromParamsSpec(napi_env env, napi_value arg) LOGE("Failed to allocate newBlob memory!"); return nullptr; } - blob->data = nullptr; - blob->len = 0; - LOGD("Input GCM Aad is Null"); return blob; } blob = GetBlobFromNapiDataBlob(env, data); @@ -1529,6 +1526,7 @@ napi_value ConvertBlobToNapiValue(napi_env env, HcfBlob *blob) env, buffer, blob->len, [](napi_env env, void *data, void *hint) { HcfFree(data); }, nullptr, &outBuffer); if (status != napi_ok) { LOGE("create uint8 array buffer failed!"); + (void)memset_s(buffer, blob->len, 0, blob->len); HcfFree(buffer); return NapiGetNull(env); } @@ -1642,6 +1640,7 @@ napi_value ConvertBigIntToNapiValue(napi_env env, HcfBigInteger *blob) if (status != napi_ok) { napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "create bigint failed!")); LOGE("create bigint failed!"); + (void)memset_s(words, wordsCount * sizeof(uint64_t), 0, wordsCount * sizeof(uint64_t)); HcfFree(words); return NapiGetNull(env); } @@ -1649,6 +1648,7 @@ napi_value ConvertBigIntToNapiValue(napi_env env, HcfBigInteger *blob) napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "bigInt is null!")); LOGE("bigInt is null!"); } + (void)memset_s(words, wordsCount * sizeof(uint64_t), 0, wordsCount * sizeof(uint64_t)); HcfFree(words); words = nullptr; return bigInt; diff --git a/frameworks/js/napi/crypto/src/napi_verify.cpp b/frameworks/js/napi/crypto/src/napi_verify.cpp index 47319d9466f149cf5284268cae4e42051cee37cd..a03a02ca1a618ce4bc8248ab6f957118f2dc5709 100644 --- a/frameworks/js/napi/crypto/src/napi_verify.cpp +++ b/frameworks/js/napi/crypto/src/napi_verify.cpp @@ -214,7 +214,7 @@ static bool BuildVerifyJsInitCtx(napi_env env, napi_callback_info info, VerifyIn napi_value thisVar = nullptr; size_t expectedArgc = PARAMS_NUM_TWO; size_t argc = expectedArgc; - napi_value argv[PARAMS_NUM_TWO] = { nullptr, nullptr }; + napi_value argv[PARAMS_NUM_TWO] = { nullptr }; napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); if ((argc != expectedArgc) && (argc != expectedArgc - 1)) { LOGE("wrong argument num. require %zu or %zu arguments. [Argc]: %zu!", expectedArgc - 1, expectedArgc, argc); @@ -264,7 +264,7 @@ static bool BuildVerifyJsUpdateCtx(napi_env env, napi_callback_info info, Verify napi_value thisVar = nullptr; size_t expectedArgc = PARAMS_NUM_TWO; size_t argc = expectedArgc; - napi_value argv[PARAMS_NUM_TWO] = { nullptr, nullptr }; + napi_value argv[PARAMS_NUM_TWO] = { nullptr }; napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); if ((argc != expectedArgc) && (argc != expectedArgc - 1)) { LOGE("wrong argument num. require %zu or %zu arguments. [Argc]: %zu!", expectedArgc - 1, expectedArgc, argc); @@ -362,7 +362,7 @@ static bool BuildVerifyJsDoFinalCtx(napi_env env, napi_callback_info info, Verif napi_value thisVar = nullptr; size_t expectedArgc = PARAMS_NUM_THREE; size_t argc = expectedArgc; - napi_value argv[PARAMS_NUM_THREE] = { nullptr, nullptr, nullptr }; + napi_value argv[PARAMS_NUM_THREE] = { nullptr }; napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); if ((argc != expectedArgc) && (argc != expectedArgc - 1)) { LOGE("wrong argument num. require %zu or %zu arguments. [Argc]: %zu!", expectedArgc - 1, expectedArgc, argc); @@ -816,6 +816,11 @@ napi_value NapiVerify::JsUpdateSync(napi_env env, napi_callback_info info) } HcfVerify *verify = napiVerify->GetVerify(); + if (verify == nullptr) { + LOGE("failed to get verify obj."); + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "fail to get verify obj.")); + return nullptr; + } ret = verify->update(verify, &blob); HcfBlobDataFree(&blob); if (ret != HCF_SUCCESS) { @@ -849,7 +854,7 @@ napi_value NapiVerify::JsVerifySync(napi_env env, napi_callback_info info) { napi_value thisVar = nullptr; size_t argc = PARAMS_NUM_TWO; - napi_value argv[PARAMS_NUM_TWO] = { nullptr, nullptr }; + napi_value argv[PARAMS_NUM_TWO] = { nullptr }; napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); if (argc != PARAMS_NUM_TWO) { LOGE("wrong argument num. require %d arguments. [Argc]: %zu!", PARAMS_NUM_TWO, argc); @@ -1026,7 +1031,6 @@ static napi_value NapiWrapVerify(napi_env env, napi_value instance, NapiVerify * if (status != napi_ok) { LOGE("failed to wrap napiVerify obj!"); delete napiVerify; - napiVerify = nullptr; return nullptr; } return instance; @@ -1034,7 +1038,6 @@ static napi_value NapiWrapVerify(napi_env env, napi_value instance, NapiVerify * napi_value NapiVerify::CreateJsVerify(napi_env env, napi_callback_info info) { - LOGD("Enter CreateJsVerify..."); size_t expectedArgc = PARAMS_NUM_ONE; size_t argc = expectedArgc; napi_value argv[PARAMS_NUM_ONE] = { nullptr }; diff --git a/frameworks/key/asy_key_generator.c b/frameworks/key/asy_key_generator.c index c3ff4bf8520e640b07346236a9d659a0bd530c9a..479af45800fcf0823c44289e2ea21d719326dbb0 100644 --- a/frameworks/key/asy_key_generator.c +++ b/frameworks/key/asy_key_generator.c @@ -723,7 +723,6 @@ static HcfResult CreateDhPubKeySpecImpl(const HcfDhPubKeyParamsSpec *srcSpec, Hc spec->pk.data = (unsigned char *)HcfMalloc(srcSpec->pk.len, 0); if (spec->pk.data == NULL) { LOGE("Failed to allocate public key memory"); - FreeDhCommParamsSpec(&(spec->base)); DestroyDhPubKeySpec(spec); return HCF_ERR_MALLOC; } @@ -1234,6 +1233,10 @@ static HcfResult ConvertKey(HcfAsyKeyGenerator *self, HcfParamsSpec *params, Hcf return HCF_INVALID_PARAMS; } HcfAsyKeyGeneratorImpl *impl = (HcfAsyKeyGeneratorImpl *)self; + if (impl->spiObj == NULL || impl->spiObj->engineConvertKey == NULL) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } return impl->spiObj->engineConvertKey(impl->spiObj, params, pubKeyBlob, priKeyBlob, returnKeyPair); } @@ -1248,6 +1251,10 @@ static HcfResult ConvertPemKey(HcfAsyKeyGenerator *self, HcfParamsSpec *params, return HCF_INVALID_PARAMS; } HcfAsyKeyGeneratorImpl *impl = (HcfAsyKeyGeneratorImpl *)self; + if (impl->spiObj == NULL || impl->spiObj->engineConvertPemKey == NULL) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } return impl->spiObj->engineConvertPemKey(impl->spiObj, params, pubKeyStr, priKeyStr, returnKeyPair); } @@ -1263,6 +1270,10 @@ static HcfResult GenerateKeyPair(HcfAsyKeyGenerator *self, HcfParamsSpec *params return HCF_INVALID_PARAMS; } HcfAsyKeyGeneratorImpl *impl = (HcfAsyKeyGeneratorImpl *)self; + if (impl->spiObj == NULL || impl->spiObj->engineGenerateKeyPair == NULL) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } return impl->spiObj->engineGenerateKeyPair(impl->spiObj, returnKeyPair); } @@ -1276,6 +1287,10 @@ static HcfResult GenerateKeyPairBySpec(const HcfAsyKeyGeneratorBySpec *self, Hcf return HCF_INVALID_PARAMS; } HcfAsyKeyGeneratorBySpecImpl *impl = (HcfAsyKeyGeneratorBySpecImpl *)self; + if (impl->spiObj == NULL || impl->spiObj->engineGenerateKeyPairBySpec == NULL) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } return impl->spiObj->engineGenerateKeyPairBySpec(impl->spiObj, impl->paramsSpec, returnKeyPair); } @@ -1289,6 +1304,10 @@ static HcfResult GeneratePubKeyBySpec(const HcfAsyKeyGeneratorBySpec *self, HcfP return HCF_INVALID_PARAMS; } HcfAsyKeyGeneratorBySpecImpl *impl = (HcfAsyKeyGeneratorBySpecImpl *)self; + if (impl->spiObj == NULL || impl->spiObj->engineGeneratePubKeyBySpec == NULL) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } return impl->spiObj->engineGeneratePubKeyBySpec(impl->spiObj, impl->paramsSpec, returnPubKey); } @@ -1302,6 +1321,10 @@ static HcfResult GeneratePriKeyBySpec(const HcfAsyKeyGeneratorBySpec *self, HcfP return HCF_INVALID_PARAMS; } HcfAsyKeyGeneratorBySpecImpl *impl = (HcfAsyKeyGeneratorBySpecImpl *)self; + if (impl->spiObj == NULL || impl->spiObj->engineGeneratePriKeyBySpec == NULL) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } return impl->spiObj->engineGeneratePriKeyBySpec(impl->spiObj, impl->paramsSpec, returnPriKey); } diff --git a/frameworks/key/dh_key_util.c b/frameworks/key/dh_key_util.c index d04952f74cac5663856f5df401b593ecabc5cf50..af6c831536fd68606a968bd45bef190b16d094a1 100644 --- a/frameworks/key/dh_key_util.c +++ b/frameworks/key/dh_key_util.c @@ -44,7 +44,7 @@ HcfResult HcfDhKeyUtilCreate(int32_t pLen, int32_t skLen, HcfDhCommParamsSpec ** } ret = CreateDhCommonSpecImpl(&(spiInstance->paramsSpec), returnCommonParamSpec); if (ret != HCF_SUCCESS) { - LOGE("Failed to create spi object!"); + LOGE("Failed to create spi impl object!"); } FreeDhCommParamsSpec(&(spiInstance->paramsSpec)); HcfFree(spiInstance); diff --git a/frameworks/key/ecc_key_util.c b/frameworks/key/ecc_key_util.c index 8e81d140a11ee21ccb39601458a0ea6808de3e6e..31565684ece1120926df30ab7779aad270c5ff98 100644 --- a/frameworks/key/ecc_key_util.c +++ b/frameworks/key/ecc_key_util.c @@ -185,13 +185,11 @@ HcfResult HcfEccKeyUtilCreate(const char *algName, HcfEccCommParamsSpec **return LOGE("Failed to create spi object!"); return ret; } - if (CreateEccCommonSpecImpl(&(spiInstance->paramsSpec), returnCommonParamSpec) != HCF_SUCCESS) { + ret = CreateEccCommonSpecImpl(&(spiInstance->paramsSpec), returnCommonParamSpec); + if (ret != HCF_SUCCESS) { LOGE("Failed to create spi object!"); - FreeEccCommParamsSpec(&(spiInstance->paramsSpec)); - HcfFree(spiInstance); - return ret; } FreeEccCommParamsSpec(&(spiInstance->paramsSpec)); HcfFree(spiInstance); - return HCF_SUCCESS; + return ret; } diff --git a/frameworks/key/sym_key_generator.c b/frameworks/key/sym_key_generator.c index 9295cf39303004058a844c079e54e5221b0739ce..0b9f646d1f7f40d0bc53927ed0a96aa019d0444a 100644 --- a/frameworks/key/sym_key_generator.c +++ b/frameworks/key/sym_key_generator.c @@ -216,6 +216,10 @@ static HcfResult GenerateSymmKey(HcfSymKeyGenerator *self, HcfSymKey **symmKey) return HCF_INVALID_PARAMS; } HcfSymmKeyGeneratorImpl *impl = (HcfSymmKeyGeneratorImpl *)self; + if (impl->spiObj == NULL || impl->spiObj->engineGenerateSymmKey == NULL) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } return impl->spiObj->engineGenerateSymmKey(impl->spiObj, symmKey); } @@ -231,7 +235,10 @@ static HcfResult ConvertSymmKey(HcfSymKeyGenerator *self, const HcfBlob *key, Hc return HCF_INVALID_PARAMS; } HcfSymmKeyGeneratorImpl *impl = (HcfSymmKeyGeneratorImpl *)self; - + if (impl->spiObj == NULL || impl->spiObj->engineConvertSymmKey == NULL) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } return impl->spiObj->engineConvertSymmKey(impl->spiObj, key, symmKey); } diff --git a/frameworks/native/BUILD.gn b/frameworks/native/BUILD.gn index 32819374b2eafd629d55d09f01f353150e837318..3bf85f5517b226c1b89eeaf301943d5e2e2be34a 100644 --- a/frameworks/native/BUILD.gn +++ b/frameworks/native/BUILD.gn @@ -16,6 +16,7 @@ import("//base/security/crypto_framework/frameworks/frameworks.gni") import("//build/ohos.gni") ohos_shared_library("ohcrypto") { + branch_protector_ret = "pac_ret" if (os_level == "standard") { sanitize = { cfi = true diff --git a/frameworks/native/src/asym_key.c b/frameworks/native/src/asym_key.c index 2295e0e5177e26365d01179d95c5963fe65fe0a0..5007aa7400aa794cdbfb5510b23a896316320874 100644 --- a/frameworks/native/src/asym_key.c +++ b/frameworks/native/src/asym_key.c @@ -74,7 +74,7 @@ OH_Crypto_ErrCode OH_CryptoAsymKeyGenerator_Create(const char *algoName, OH_Cryp OH_Crypto_ErrCode OH_CryptoAsymKeyGenerator_Generate(OH_CryptoAsymKeyGenerator *ctx, OH_CryptoKeyPair **keyCtx) { - if ((ctx == NULL) || (keyCtx == NULL)) { + if ((ctx == NULL) || (ctx->generateKeyPair == NULL) || (keyCtx == NULL)) { return CRYPTO_INVALID_PARAMS; } HcfResult ret = ctx->generateKeyPair((HcfAsyKeyGenerator *)ctx, NULL, (HcfKeyPair **)keyCtx); @@ -92,11 +92,13 @@ OH_Crypto_ErrCode OH_CryptoAsymKeyGenerator_Convert(OH_CryptoAsymKeyGenerator *c const char *pubKeyStr = (pubKeyData == NULL)? NULL : (const char *)pubKeyData->data; switch (type) { case CRYPTO_PEM: - ret = ctx->convertPemKey((HcfAsyKeyGenerator *)ctx, NULL, pubKeyStr, priKeyStr, (HcfKeyPair **)keyCtx); + ret = ctx->convertPemKey == NULL ? HCF_INVALID_PARAMS : + ctx->convertPemKey((HcfAsyKeyGenerator *)ctx, NULL, pubKeyStr, priKeyStr, (HcfKeyPair **)keyCtx); break; case CRYPTO_DER: - ret = ctx->convertKey((HcfAsyKeyGenerator *)ctx, NULL, - (HcfBlob *)pubKeyData, (HcfBlob *)priKeyData, (HcfKeyPair **)keyCtx); + ret = ctx->convertKey == NULL ? HCF_INVALID_PARAMS : + ctx->convertKey((HcfAsyKeyGenerator *)ctx, NULL, (HcfBlob *)pubKeyData, + (HcfBlob *)priKeyData, (HcfKeyPair **)keyCtx); break; default: return CRYPTO_INVALID_PARAMS; @@ -106,7 +108,7 @@ OH_Crypto_ErrCode OH_CryptoAsymKeyGenerator_Convert(OH_CryptoAsymKeyGenerator *c const char *OH_CryptoAsymKeyGenerator_GetAlgoName(OH_CryptoAsymKeyGenerator *ctx) { - if (ctx == NULL) { + if ((ctx == NULL) || (ctx->getAlgoName == NULL)) { return NULL; } return ctx->getAlgoName((HcfAsyKeyGenerator *)ctx); @@ -114,7 +116,7 @@ const char *OH_CryptoAsymKeyGenerator_GetAlgoName(OH_CryptoAsymKeyGenerator *ctx void OH_CryptoAsymKeyGenerator_Destroy(OH_CryptoAsymKeyGenerator *ctx) { - if (ctx == NULL) { + if ((ctx == NULL) || (ctx->base.destroy == NULL)) { return; } ctx->base.destroy((HcfObjectBase *)ctx); @@ -122,7 +124,7 @@ void OH_CryptoAsymKeyGenerator_Destroy(OH_CryptoAsymKeyGenerator *ctx) void OH_CryptoKeyPair_Destroy(OH_CryptoKeyPair *keyCtx) { - if (keyCtx == NULL) { + if ((keyCtx == NULL) || (keyCtx->base.destroy == NULL)) { return; } keyCtx->base.destroy((HcfObjectBase *)keyCtx); @@ -146,6 +148,9 @@ OH_Crypto_ErrCode OH_CryptoPubKey_Encode(OH_CryptoPubKey *key, Crypto_EncodingTy char *pemStr = NULL; switch (type) { case CRYPTO_PEM: + if (key->base.getEncodedPem == NULL) { + return CRYPTO_INVALID_PARAMS; + } ret = key->base.getEncodedPem((HcfKey *)key, encodingStandard, &pemStr); if (ret != HCF_SUCCESS) { break; @@ -155,10 +160,12 @@ OH_Crypto_ErrCode OH_CryptoPubKey_Encode(OH_CryptoPubKey *key, Crypto_EncodingTy break; case CRYPTO_DER: if (encodingStandard != NULL) { - ret = key->getEncodedDer((HcfPubKey *)key, encodingStandard, (HcfBlob *)out); + ret = key->getEncodedDer == NULL ? HCF_INVALID_PARAMS : + key->getEncodedDer((HcfPubKey *)key, encodingStandard, (HcfBlob *)out); break; } else { - ret = key->base.getEncoded((HcfKey *)key, (HcfBlob *)out); + ret = key->base.getEncoded == NULL ? HCF_INVALID_PARAMS + : key->base.getEncoded((HcfKey *)key, (HcfBlob *)out); break; } default: @@ -186,7 +193,8 @@ OH_Crypto_ErrCode OH_CryptoPubKey_GetParam(OH_CryptoPubKey *key, CryptoAsymKey_P ret = HCF_ERR_MALLOC; break; } - ret = key->getAsyKeySpecInt((HcfPubKey *)key, (AsyKeySpecItem)item, returnInt); + ret = key->getAsyKeySpecInt == NULL ? HCF_INVALID_PARAMS : + key->getAsyKeySpecInt((HcfPubKey *)key, (AsyKeySpecItem)item, returnInt); if (ret != HCF_SUCCESS) { HcfFree(returnInt); break; @@ -196,7 +204,8 @@ OH_Crypto_ErrCode OH_CryptoPubKey_GetParam(OH_CryptoPubKey *key, CryptoAsymKey_P break; case CRYPTO_ECC_FIELD_TYPE_STR: case CRYPTO_ECC_CURVE_NAME_STR: - ret = key->getAsyKeySpecString((HcfPubKey *)key, (AsyKeySpecItem)item, &returnStr); + ret = key->getAsyKeySpecString == NULL ? HCF_INVALID_PARAMS : + key->getAsyKeySpecString((HcfPubKey *)key, (AsyKeySpecItem)item, &returnStr); if (ret != HCF_SUCCESS) { break; } @@ -204,8 +213,8 @@ OH_Crypto_ErrCode OH_CryptoPubKey_GetParam(OH_CryptoPubKey *key, CryptoAsymKey_P value->len = strlen(returnStr); break; default: - ret = key->getAsyKeySpecBigInteger((HcfPubKey *)key, - (AsyKeySpecItem)item, &bigIntValue); + ret = key->getAsyKeySpecBigInteger == NULL ? HCF_INVALID_PARAMS : + key->getAsyKeySpecBigInteger((HcfPubKey *)key, (AsyKeySpecItem)item, &bigIntValue); if (ret != HCF_SUCCESS) { break; } diff --git a/frameworks/native/src/crypto_common.c b/frameworks/native/src/crypto_common.c index b3d00a2811a1ff3bc8f548334530edff5cb2f3be..f9a17dde2e73c5af2c9e8eebab637b7e82db9266 100644 --- a/frameworks/native/src/crypto_common.c +++ b/frameworks/native/src/crypto_common.c @@ -22,5 +22,5 @@ void OH_Crypto_FreeDataBlob(Crypto_DataBlob *dataBlob) if (dataBlob == NULL) { return; } - return HcfBlobDataFree((HcfBlob *)dataBlob); + HcfBlobDataFree((HcfBlob *)dataBlob); } \ No newline at end of file diff --git a/frameworks/native/src/digest.c b/frameworks/native/src/digest.c index b8d9ab2ff5e3a38d3ef96e5d96490b9057cbb2c0..8d0a6c6d86be01545e0adad98643ab45f842b1d2 100644 --- a/frameworks/native/src/digest.c +++ b/frameworks/native/src/digest.c @@ -44,7 +44,7 @@ OH_Crypto_ErrCode OH_CryptoDigest_Create(const char *algoName, OH_CryptoDigest * OH_Crypto_ErrCode OH_CryptoDigest_Update(OH_CryptoDigest *ctx, Crypto_DataBlob *in) { - if ((ctx == NULL) || (in == NULL)) { + if ((ctx == NULL) || (ctx->update == NULL) || (in == NULL)) { return CRYPTO_INVALID_PARAMS; } HcfResult ret = ctx->update((HcfMd *)ctx, (HcfBlob *)in); @@ -53,7 +53,7 @@ OH_Crypto_ErrCode OH_CryptoDigest_Update(OH_CryptoDigest *ctx, Crypto_DataBlob * OH_Crypto_ErrCode OH_CryptoDigest_Final(OH_CryptoDigest *ctx, Crypto_DataBlob *out) { - if ((ctx == NULL) || (out == NULL)) { + if ((ctx == NULL) || (ctx->doFinal == NULL) || (out == NULL)) { return CRYPTO_INVALID_PARAMS; } HcfResult ret = ctx->doFinal((HcfMd *)ctx, (HcfBlob *)out); @@ -62,7 +62,7 @@ OH_Crypto_ErrCode OH_CryptoDigest_Final(OH_CryptoDigest *ctx, Crypto_DataBlob *o uint32_t OH_CryptoDigest_GetLength(OH_CryptoDigest *ctx) { - if (ctx == NULL) { + if ((ctx == NULL) || (ctx->getMdLength == NULL)) { return CRYPTO_INVALID_PARAMS; } return ctx->getMdLength((HcfMd *)ctx); @@ -70,7 +70,7 @@ uint32_t OH_CryptoDigest_GetLength(OH_CryptoDigest *ctx) const char *OH_CryptoDigest_GetAlgoName(OH_CryptoDigest *ctx) { - if (ctx == NULL) { + if ((ctx == NULL) || (ctx->getAlgoName == NULL)) { return NULL; } return ctx->getAlgoName((HcfMd *)ctx); @@ -78,7 +78,7 @@ const char *OH_CryptoDigest_GetAlgoName(OH_CryptoDigest *ctx) void OH_DigestCrypto_Destroy(OH_CryptoDigest *ctx) { - if (ctx == NULL) { + if ((ctx == NULL) || (ctx->base.destroy == NULL)) { return; } ctx->base.destroy((HcfObjectBase *)ctx); diff --git a/frameworks/native/src/signature.c b/frameworks/native/src/signature.c index 060e78aa83c88493b39485fb4acd37c6a4237eda..c619321f860e74be2b2a2a6ee871b88e8dd460fc 100644 --- a/frameworks/native/src/signature.c +++ b/frameworks/native/src/signature.c @@ -46,18 +46,18 @@ struct OH_CryptoVerify { HcfResult (*setVerifySpecUint8Array)(HcfVerify *self, SignSpecItem item, HcfBlob blob); }; -OH_Crypto_ErrCode OH_CryptoVerify_Create(const char *algoName, OH_CryptoVerify **ctx) +OH_Crypto_ErrCode OH_CryptoVerify_Create(const char *algoName, OH_CryptoVerify **verify) { - if (ctx == NULL) { + if (verify == NULL) { return CRYPTO_INVALID_PARAMS; } - HcfResult ret = HcfVerifyCreate(algoName, (HcfVerify **)ctx); + HcfResult ret = HcfVerifyCreate(algoName, (HcfVerify **)verify); return GetOhCryptoErrCode(ret); } OH_Crypto_ErrCode OH_CryptoVerify_Init(OH_CryptoVerify *ctx, OH_CryptoPubKey *pubKey) { - if ((ctx == NULL) || (pubKey == NULL)) { + if ((ctx == NULL) || (ctx->init == NULL) || (pubKey == NULL)) { return CRYPTO_INVALID_PARAMS; } HcfResult ret = ctx->init((HcfVerify *)ctx, NULL, (HcfPubKey *)pubKey); @@ -66,7 +66,7 @@ OH_Crypto_ErrCode OH_CryptoVerify_Init(OH_CryptoVerify *ctx, OH_CryptoPubKey *pu OH_Crypto_ErrCode OH_CryptoVerify_Update(OH_CryptoVerify *ctx, Crypto_DataBlob *in) { - if ((ctx == NULL) || (in == NULL)) { + if ((ctx == NULL) || (ctx->update == NULL) || (in == NULL)) { return CRYPTO_INVALID_PARAMS; } HcfResult ret = ctx->update((HcfVerify *)ctx, (HcfBlob *)in); @@ -75,7 +75,7 @@ OH_Crypto_ErrCode OH_CryptoVerify_Update(OH_CryptoVerify *ctx, Crypto_DataBlob * bool OH_CryptoVerify_Final(OH_CryptoVerify *ctx, Crypto_DataBlob *in, Crypto_DataBlob *signData) { - if ((ctx == NULL) || (signData == NULL)) { + if ((ctx == NULL) || (ctx->verify == NULL) || (signData == NULL)) { return false; } bool ret = ctx->verify((HcfVerify *)ctx, (HcfBlob *)in, (HcfBlob *)signData); @@ -89,7 +89,7 @@ bool OH_CryptoVerify_Final(OH_CryptoVerify *ctx, Crypto_DataBlob *in, Crypto_Dat OH_Crypto_ErrCode OH_CryptoVerify_Recover(OH_CryptoVerify *ctx, Crypto_DataBlob *signData, Crypto_DataBlob *rawSignData) { - if ((ctx == NULL) || (signData == NULL) || (rawSignData == NULL)) { + if ((ctx == NULL) || (ctx->recover == NULL) || (signData == NULL) || (rawSignData == NULL)) { return CRYPTO_INVALID_PARAMS; } HcfResult ret = ctx->recover((HcfVerify *)ctx, (HcfBlob *)signData, (HcfBlob *)rawSignData); @@ -98,7 +98,7 @@ OH_Crypto_ErrCode OH_CryptoVerify_Recover(OH_CryptoVerify *ctx, Crypto_DataBlob const char *OH_CryptoVerify_GetAlgoName(OH_CryptoVerify *ctx) { - if (ctx == NULL) { + if ((ctx == NULL) || (ctx->getAlgoName == NULL)) { return NULL; } return ctx->getAlgoName((HcfVerify *)ctx); @@ -114,7 +114,7 @@ OH_Crypto_ErrCode OH_CryptoVerify_SetParam(OH_CryptoVerify *ctx, CryptoSignature switch (type) { case CRYPTO_PSS_SALT_LEN_INT: case CRYPTO_PSS_TRAILER_FIELD_INT: - if (value->len != sizeof(int32_t)) { + if ((value->data == NULL) || (value->len != sizeof(int32_t)) || (ctx->setVerifySpecInt == NULL)) { ret = HCF_INVALID_PARAMS; break; } @@ -124,6 +124,10 @@ OH_Crypto_ErrCode OH_CryptoVerify_SetParam(OH_CryptoVerify *ctx, CryptoSignature case CRYPTO_PSS_MGF1_NAME_STR: case CRYPTO_PSS_MGF_NAME_STR: case CRYPTO_PSS_MD_NAME_STR: + if (ctx->setVerifySpecUint8Array == NULL) { + ret = HCF_INVALID_PARAMS; + break; + } ret = ctx->setVerifySpecUint8Array((HcfVerify *)ctx, (SignSpecItem)type, *((HcfBlob *)value)); break; default: @@ -145,6 +149,10 @@ OH_Crypto_ErrCode OH_CryptoVerify_GetParam(OH_CryptoVerify *ctx, CryptoSignature case CRYPTO_PSS_SALT_LEN_INT: case CRYPTO_PSS_TRAILER_FIELD_INT: case CRYPTO_SM2_USER_ID_DATABLOB: + if (ctx->getVerifySpecInt == NULL) { + ret = HCF_INVALID_PARAMS; + break; + } returnInt = (int32_t *)HcfMalloc(sizeof(int32_t), 0); if (returnInt == NULL) { return CRYPTO_MEMORY_ERROR; @@ -160,6 +168,10 @@ OH_Crypto_ErrCode OH_CryptoVerify_GetParam(OH_CryptoVerify *ctx, CryptoSignature case CRYPTO_PSS_MD_NAME_STR: case CRYPTO_PSS_MGF_NAME_STR: case CRYPTO_PSS_MGF1_NAME_STR: + if (ctx->getVerifySpecString == NULL) { + ret = HCF_INVALID_PARAMS; + break; + } ret = ctx->getVerifySpecString((HcfVerify *)ctx, (SignSpecItem)type, &returnStr); if (ret != HCF_SUCCESS) { break; @@ -176,7 +188,7 @@ OH_Crypto_ErrCode OH_CryptoVerify_GetParam(OH_CryptoVerify *ctx, CryptoSignature void OH_CryptoVerify_Destroy(OH_CryptoVerify *ctx) { - if (ctx == NULL) { + if (ctx == NULL || ctx->base.destroy == NULL) { return; } ctx->base.destroy((HcfObjectBase *)ctx); diff --git a/frameworks/native/src/sym_cipher.c b/frameworks/native/src/sym_cipher.c index 615d554207733974fe2d76e03661c413f4f3641d..ac7f75f547000ae40547720bbeb9d6137c80241f 100644 --- a/frameworks/native/src/sym_cipher.c +++ b/frameworks/native/src/sym_cipher.c @@ -113,7 +113,7 @@ OH_Crypto_ErrCode OH_CryptoSymCipher_Create(const char *algoName, OH_CryptoSymCi OH_Crypto_ErrCode OH_CryptoSymCipher_Init(OH_CryptoSymCipher *ctx, Crypto_CipherMode mod, OH_CryptoSymKey *key, OH_CryptoSymCipherParams *params) { - if ((ctx == NULL) || (key == NULL)) { + if ((ctx == NULL) || (ctx->init == NULL) || (key == NULL)) { return CRYPTO_INVALID_PARAMS; } HcfResult ret = ctx->init((HcfCipher *)ctx, (enum HcfCryptoMode)mod, (HcfKey *)key, (HcfParamsSpec *)params); @@ -122,7 +122,7 @@ OH_Crypto_ErrCode OH_CryptoSymCipher_Init(OH_CryptoSymCipher *ctx, Crypto_Cipher OH_Crypto_ErrCode OH_CryptoSymCipher_Update(OH_CryptoSymCipher *ctx, Crypto_DataBlob *in, Crypto_DataBlob *out) { - if ((ctx == NULL) || (in == NULL) || (out == NULL)) { + if ((ctx == NULL) || (ctx->update == NULL) || (in == NULL) || (out == NULL)) { return CRYPTO_INVALID_PARAMS; } HcfResult ret = ctx->update((HcfCipher *)ctx, (HcfBlob *)in, (HcfBlob *)out); @@ -131,7 +131,7 @@ OH_Crypto_ErrCode OH_CryptoSymCipher_Update(OH_CryptoSymCipher *ctx, Crypto_Data OH_Crypto_ErrCode OH_CryptoSymCipher_Final(OH_CryptoSymCipher *ctx, Crypto_DataBlob *in, Crypto_DataBlob *out) { - if ((ctx == NULL) || (out == NULL)) { + if ((ctx == NULL) || (ctx->doFinal == NULL) || (out == NULL)) { return CRYPTO_INVALID_PARAMS; } HcfResult ret = ctx->doFinal((HcfCipher *)ctx, (HcfBlob *)in, (HcfBlob *)out); @@ -140,7 +140,7 @@ OH_Crypto_ErrCode OH_CryptoSymCipher_Final(OH_CryptoSymCipher *ctx, Crypto_DataB const char *OH_CryptoSymCipher_GetAlgoName(OH_CryptoSymCipher *ctx) { - if (ctx == NULL) { + if ((ctx == NULL) || (ctx->getAlgorithm == NULL)) { return NULL; } return ctx->getAlgorithm((HcfCipher *)ctx); @@ -148,7 +148,7 @@ const char *OH_CryptoSymCipher_GetAlgoName(OH_CryptoSymCipher *ctx) void OH_CryptoSymCipher_Destroy(OH_CryptoSymCipher *ctx) { - if (ctx == NULL) { + if ((ctx == NULL) || (ctx->base.destroy == NULL)) { return; } ctx->base.destroy((HcfObjectBase *)ctx); diff --git a/frameworks/native/src/sym_key.c b/frameworks/native/src/sym_key.c index df250d8658ceb3fae34ac1bf6b268ec9f50a7f01..4d9626767b84a24066e340cee362ea2aca72e91d 100644 --- a/frameworks/native/src/sym_key.c +++ b/frameworks/native/src/sym_key.c @@ -53,7 +53,7 @@ OH_Crypto_ErrCode OH_CryptoSymKeyGenerator_Create(const char *algoName, OH_Crypt OH_Crypto_ErrCode OH_CryptoSymKeyGenerator_Generate(OH_CryptoSymKeyGenerator *ctx, OH_CryptoSymKey **keyCtx) { - if ((ctx == NULL) || (keyCtx == NULL)) { + if ((ctx == NULL) || (ctx->generateSymKey == NULL) || (keyCtx == NULL)) { return CRYPTO_INVALID_PARAMS; } HcfResult ret = ctx->generateSymKey((HcfSymKeyGenerator *)ctx, (HcfSymKey **)keyCtx); @@ -63,7 +63,7 @@ OH_Crypto_ErrCode OH_CryptoSymKeyGenerator_Generate(OH_CryptoSymKeyGenerator *ct OH_Crypto_ErrCode OH_CryptoSymKeyGenerator_Convert(OH_CryptoSymKeyGenerator *ctx, const Crypto_DataBlob *keyData, OH_CryptoSymKey **keyCtx) { - if ((ctx == NULL) || (keyData == NULL) || (keyCtx == NULL)) { + if ((ctx == NULL) || (ctx->convertSymKey == NULL) || (keyData == NULL) || (keyCtx == NULL)) { return CRYPTO_INVALID_PARAMS; } HcfResult ret = ctx->convertSymKey((HcfSymKeyGenerator *)ctx, (HcfBlob *)keyData, (HcfSymKey **)keyCtx); @@ -72,7 +72,7 @@ OH_Crypto_ErrCode OH_CryptoSymKeyGenerator_Convert(OH_CryptoSymKeyGenerator *ctx const char *OH_CryptoSymKeyGenerator_GetAlgoName(OH_CryptoSymKeyGenerator *ctx) { - if (ctx == NULL) { + if (ctx == NULL || (ctx->getAlgoName == NULL)) { return NULL; } return ctx->getAlgoName((HcfSymKeyGenerator *)ctx); @@ -80,7 +80,7 @@ const char *OH_CryptoSymKeyGenerator_GetAlgoName(OH_CryptoSymKeyGenerator *ctx) void OH_CryptoSymKeyGenerator_Destroy(OH_CryptoSymKeyGenerator *ctx) { - if (ctx == NULL) { + if (ctx == NULL || (ctx->base.destroy == NULL)) { return; } ctx->base.destroy((HcfObjectBase *)ctx); @@ -88,7 +88,7 @@ void OH_CryptoSymKeyGenerator_Destroy(OH_CryptoSymKeyGenerator *ctx) const char *OH_CryptoSymKey_GetAlgoName(OH_CryptoSymKey *keyCtx) { - if (keyCtx == NULL) { + if (keyCtx == NULL || (keyCtx->key.getAlgorithm == NULL)) { return NULL; } return keyCtx->key.getAlgorithm((HcfKey *)keyCtx); @@ -96,7 +96,7 @@ const char *OH_CryptoSymKey_GetAlgoName(OH_CryptoSymKey *keyCtx) OH_Crypto_ErrCode OH_CryptoSymKey_GetKeyData(OH_CryptoSymKey *keyCtx, Crypto_DataBlob *out) { - if ((keyCtx == NULL) || (out == NULL)) { + if ((keyCtx == NULL) || (keyCtx->key.getEncoded == NULL) || (out == NULL)) { return CRYPTO_INVALID_PARAMS; } HcfResult ret = keyCtx->key.getEncoded((HcfKey *)keyCtx, (HcfBlob *)out); @@ -105,7 +105,7 @@ OH_Crypto_ErrCode OH_CryptoSymKey_GetKeyData(OH_CryptoSymKey *keyCtx, Crypto_Dat void OH_CryptoSymKey_Destroy(OH_CryptoSymKey *keyCtx) { - if (keyCtx == NULL) { + if ((keyCtx == NULL) || (keyCtx->key.base.destroy == NULL)) { return; } keyCtx->key.base.destroy((HcfObjectBase *)keyCtx); diff --git a/frameworks/spi/rand_spi.h b/frameworks/spi/rand_spi.h index 8b554c672eecbb6eb2e5338dc18c53e4917cb7ff..166950f6b876dc85ecc864567f38f9a26513b94e 100644 --- a/frameworks/spi/rand_spi.h +++ b/frameworks/spi/rand_spi.h @@ -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; diff --git a/plugin/BUILD.gn b/plugin/BUILD.gn index fd6d724ee016948f2edb575bbeb836c49dff2f2c..08b689cbf7b6c9ec1bbd7686abca993ed8fde260 100644 --- a/plugin/BUILD.gn +++ b/plugin/BUILD.gn @@ -25,35 +25,55 @@ config("plugin_config") { ] } -ohos_shared_library("crypto_openssl_plugin_lib") { - 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 - - if (os_level == "standard") { - sanitize = { - cfi = true - cfi_cross_dso = true - debug = false +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 + + 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" ] + } } diff --git a/plugin/mbedtls_plugin/common/mbedtls_common.h b/plugin/mbedtls_plugin/common/mbedtls_common.h new file mode 100644 index 0000000000000000000000000000000000000000..702a39e58af488ee296f9fd9715f8f22e462789e --- /dev/null +++ b/plugin/mbedtls_plugin/common/mbedtls_common.h @@ -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 +#include + +#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 diff --git a/plugin/mbedtls_plugin/md/inc/mbedtls_md.h b/plugin/mbedtls_plugin/md/inc/mbedtls_md.h new file mode 100644 index 0000000000000000000000000000000000000000..cbd66dac9a2b86858045dbfab383d48dd4cc7dd1 --- /dev/null +++ b/plugin/mbedtls_plugin/md/inc/mbedtls_md.h @@ -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 diff --git a/plugin/mbedtls_plugin/md/src/mbedtls_md.c b/plugin/mbedtls_plugin/md/src/mbedtls_md.c new file mode 100644 index 0000000000000000000000000000000000000000..73a5fd680191873de98caade4e9317713fa67bae --- /dev/null +++ b/plugin/mbedtls_plugin/md/src/mbedtls_md.c @@ -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; +} diff --git a/plugin/mbedtls_plugin/rand/inc/mbedtls_rand.h b/plugin/mbedtls_plugin/rand/inc/mbedtls_rand.h new file mode 100644 index 0000000000000000000000000000000000000000..3ce39205dacecaeedfee446e193cf70ed3bedbd7 --- /dev/null +++ b/plugin/mbedtls_plugin/rand/inc/mbedtls_rand.h @@ -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 diff --git a/plugin/mbedtls_plugin/rand/src/mbedtls_rand.c b/plugin/mbedtls_plugin/rand/src/mbedtls_rand.c new file mode 100644 index 0000000000000000000000000000000000000000..247eb691e6207982f92aa4b20a013de07497b1ef --- /dev/null +++ b/plugin/mbedtls_plugin/rand/src/mbedtls_rand.c @@ -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; +} diff --git a/plugin/openssl_plugin/common/inc/openssl_adapter.h b/plugin/openssl_plugin/common/inc/openssl_adapter.h index 5ad1a6981ec8fcc1432dba05187035b3e51471d9..ab212bca0326ba2af75f6b742f371e131d16db8f 100644 --- a/plugin/openssl_plugin/common/inc/openssl_adapter.h +++ b/plugin/openssl_plugin/common/inc/openssl_adapter.h @@ -28,6 +28,8 @@ #include #include #include +#include +#include #include #include @@ -217,9 +219,12 @@ int OpensslEvpPkeySet1Rsa(EVP_PKEY *pkey, struct rsa_st *key); int OpensslEvpPkeyAssignRsa(EVP_PKEY *pkey, struct rsa_st *key); int OpensslPemWriteBioRsaPublicKey(BIO *bp, RSA *x); int OpensslPemWriteBioRsaPubKey(BIO *bp, RSA *x); +EVP_PKEY *OpensslPemReadBioPrivateKey(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, void *u); + // BIO BIO *OpensslBioNew(const BIO_METHOD *type); const BIO_METHOD *OpensslBioSMem(void); +int OpensslBioWrite(BIO *b, const void *data, int dlen); int OpensslBioRead(BIO *b, void *data, int dlen); void OpensslBioFreeAll(BIO *a); @@ -325,6 +330,7 @@ const BIGNUM *OpensslDhGet0PrivKey(const DH *dh); int OpensslEvpPkeySet1Dh(EVP_PKEY *pkey, DH *key); int OpensslEvpPkeyAssignDh(EVP_PKEY *pkey, DH *key); struct dh_st *OpensslEvpPkeyGet1Dh(EVP_PKEY *pkey); +int OpensslEvpPkeyIsA(const EVP_PKEY *pkey, const char *name); int OpensslEvpPkeyCtxSetDhParamgenPrimeLen(EVP_PKEY_CTX *ctx, int pbits); int OpensslEvpPkeyCtxSetSignatureMd(EVP_PKEY_CTX *ctx, const EVP_MD *md); int OpensslDhUpRef(DH *r); @@ -383,6 +389,12 @@ OSSL_DECODER_CTX *OpensslOsslDecoderCtxNewForPkey(EVP_PKEY **pkey, const char *i int OpensslOsslDecoderFromData(OSSL_DECODER_CTX *ctx, const unsigned char **pdata, size_t *len); void OpensslOsslDecoderCtxFree(OSSL_DECODER_CTX *ctx); +EC_KEY *OpensslEcKeyNewbyCurveNameEx(OSSL_LIB_CTX *ctx, const char *propq, int nid); +int OpensslEvpPkeyGetOctetStringParam(const EVP_PKEY *pkey, const char *keyName, unsigned char *buf, size_t maxBufSz, + size_t *outLen); +void OpensslEcKeySetFlags(EC_KEY *key, int flags); +int OpensslEvpPkeyGetBnParam(const EVP_PKEY *pkey, const char *keyName, BIGNUM **bn); + #ifdef __cplusplus } #endif diff --git a/plugin/openssl_plugin/common/inc/openssl_common.h b/plugin/openssl_plugin/common/inc/openssl_common.h index b1f3ab3373f2b7e513766cb030cf420e91ecac96..a1360842def449b17a4defc3541e0ce0258feaae 100644 --- a/plugin/openssl_plugin/common/inc/openssl_common.h +++ b/plugin/openssl_plugin/common/inc/openssl_common.h @@ -52,8 +52,6 @@ void HcfPrintOpensslError(void); HcfResult GetOpensslPadding(int32_t padding, int32_t *opensslPadding); -int32_t GetRealPrimes(int32_t primesFlag); - bool IsBigEndian(void); HcfResult BigIntegerToBigNum(const HcfBigInteger *src, BIGNUM **dest); @@ -70,6 +68,10 @@ HcfResult KeyDerive(EVP_PKEY *priKey, EVP_PKEY *pubKey, HcfBlob *returnSecret); HcfResult GetKeyEncodedPem(EVP_PKEY *pkey, const char *outPutStruct, int selection, char **returnString); +HcfResult ConvertPubPemStrToKey(EVP_PKEY **pkey, const char *keyType, int selection, const char *keyStr); + +HcfResult ConvertPriPemStrToKey(const char *keyStr, EVP_PKEY **pkey, const char *keyType); + #ifdef __cplusplus } #endif diff --git a/plugin/openssl_plugin/common/src/ecc_openssl_common.c b/plugin/openssl_plugin/common/src/ecc_openssl_common.c index a667155e87886546af6d35a1f19576cd9f2f7251..4afd54afbfa01989d40a3ddd7c1296abf85fcef2 100644 --- a/plugin/openssl_plugin/common/src/ecc_openssl_common.c +++ b/plugin/openssl_plugin/common/src/ecc_openssl_common.c @@ -218,10 +218,10 @@ static HcfResult InitEcKeyByPriKey(const HcfBigInteger *priKey, EC_KEY *ecKey) int32_t ret = (int32_t)OpensslEcKeySetPrivateKey(ecKey, sk); if (ret != HCF_OPENSSL_SUCCESS) { LOGD("[error] OpensslEcKeySetPrivateKey failed."); - OpensslBnFree(sk); + OpensslBnClearFree(sk); return HCF_ERR_CRYPTO_OPERATION; } - OpensslBnFree(sk); + OpensslBnClearFree(sk); return HCF_SUCCESS; } @@ -256,7 +256,7 @@ static HcfResult SetEcPubKeyFromPriKey(const HcfBigInteger *priKey, EC_KEY *ecKe } } while (0); OpensslEcPointFree(point); - OpensslBnFree(sk); + OpensslBnClearFree(sk); return ret; } diff --git a/plugin/openssl_plugin/common/src/openssl_adapter.c b/plugin/openssl_plugin/common/src/openssl_adapter.c index 8760c91381369c07cd0dbc1637e45478884ac696..f38dd44a94823421e4e63da068d9b240a8a97795 100644 --- a/plugin/openssl_plugin/common/src/openssl_adapter.c +++ b/plugin/openssl_plugin/common/src/openssl_adapter.c @@ -819,6 +819,11 @@ int OpensslPemWriteBioRsaPubKey(BIO *bp, RSA *x) return PEM_write_bio_RSA_PUBKEY(bp, x); } +EVP_PKEY *OpensslPemReadBioPrivateKey(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, void *u) +{ + return PEM_read_bio_PrivateKey(bp, x, cb, u); +} + BIO *OpensslBioNew(const BIO_METHOD *type) { return BIO_new(type); @@ -834,9 +839,14 @@ int OpensslBioRead(BIO *b, void *data, int dlen) return BIO_read(b, data, dlen); } +int OpensslBioWrite(BIO *b, const void *data, int dlen) +{ + return BIO_write(b, data, dlen); +} + void OpensslBioFreeAll(BIO *a) { - return BIO_free_all(a); + BIO_free_all(a); } int OpensslRandPrivBytes(unsigned char *buf, int num) @@ -1116,7 +1126,7 @@ EVP_CIPHER *OpensslEvpCipherFetch(OSSL_LIB_CTX *ctx, const char *algorithm, cons void OpensslEvpCipherFree(EVP_CIPHER *cipher) { - return EVP_CIPHER_free(cipher); + EVP_CIPHER_free(cipher); } EVP_CIPHER_CTX *OpensslEvpCipherCtxNew(void) @@ -1225,7 +1235,7 @@ int OpensslDhComputeKeyPadded(unsigned char *key, const BIGNUM *pubKey, DH *dh) void OpensslDhFree(DH *dh) { - return DH_free(dh); + DH_free(dh); } int OpensslDhGenerateKey(DH *dh) @@ -1278,6 +1288,11 @@ DH *OpensslEvpPkeyGet1Dh(EVP_PKEY *pkey) return EVP_PKEY_get1_DH(pkey); } +int OpensslEvpPkeyIsA(const EVP_PKEY *pkey, const char *name) +{ + return EVP_PKEY_is_a(pkey, name); +} + int OpensslEvpPkeyAssignDh(EVP_PKEY *pkey, DH *key) { return EVP_PKEY_assign_DH(pkey, key); @@ -1308,9 +1323,9 @@ int OpensslDhSet0Key(DH *dh, BIGNUM *pubKey, BIGNUM *privKey) return DH_set0_key(dh, pubKey, privKey); } -struct Sm2CipherTextSt *OpensslD2iSm2CipherText(const uint8_t *ciphertext, size_t ciphertext_len) +struct Sm2CipherTextSt *OpensslD2iSm2CipherText(const uint8_t *ciphertext, size_t ciphertextLen) { - return d2i_Sm2CipherText(NULL, &ciphertext, ciphertext_len); + return d2i_Sm2CipherText(NULL, &ciphertext, ciphertextLen); } void OpensslSm2CipherTextFree(struct Sm2CipherTextSt *sm2Text) @@ -1433,12 +1448,12 @@ EVP_KDF_CTX *OpensslEvpKdfCtxNew(EVP_KDF *kdf) void OpensslEvpKdfFree(EVP_KDF *kdf) { - return EVP_KDF_free(kdf); + EVP_KDF_free(kdf); } void OpensslEvpKdfCtxFree(EVP_KDF_CTX *ctx) { - return EVP_KDF_CTX_free(ctx); + EVP_KDF_CTX_free(ctx); } int OpensslEvpKdfDerive(EVP_KDF_CTX *ctx, unsigned char *key, size_t keylen, @@ -1479,3 +1494,24 @@ void OpensslOsslDecoderCtxFree(OSSL_DECODER_CTX *ctx) { OSSL_DECODER_CTX_free(ctx); } + +EC_KEY *OpensslEcKeyNewbyCurveNameEx(OSSL_LIB_CTX *ctx, const char *propq, int nid) +{ + return EC_KEY_new_by_curve_name_ex(ctx, propq, nid); +} + +int OpensslEvpPkeyGetOctetStringParam(const EVP_PKEY *pkey, const char *keyName, unsigned char *buf, size_t maxBufSz, + size_t *outLen) +{ + return EVP_PKEY_get_octet_string_param(pkey, keyName, buf, maxBufSz, outLen); +} + +void OpensslEcKeySetFlags(EC_KEY *key, int flags) +{ + EC_KEY_set_flags(key, flags); +} + +int OpensslEvpPkeyGetBnParam(const EVP_PKEY *pkey, const char *keyName, BIGNUM **bn) +{ + return EVP_PKEY_get_bn_param(pkey, keyName, bn); +} diff --git a/plugin/openssl_plugin/common/src/openssl_common.c b/plugin/openssl_plugin/common/src/openssl_common.c index 6924f3415a8b85f9a13f01cbdfdfce4d486274d1..3669142bfebdc7e7f83e7e10ac1ca5a1793e0fc5 100644 --- a/plugin/openssl_plugin/common/src/openssl_common.c +++ b/plugin/openssl_plugin/common/src/openssl_common.c @@ -27,11 +27,6 @@ #include "params_parser.h" #include "utils.h" -#define PRIMES_2 2 -#define PRIMES_3 3 -#define PRIMES_4 4 -#define PRIMES_5 5 - #define HCF_OPENSSL_DIGEST_NONE_STR "NONE" #define HCF_OPENSSL_DIGEST_MD5_STR "MD5" #define HCF_OPENSSL_DIGEST_SM3_STR "SM3" @@ -418,23 +413,6 @@ HcfResult GetOpensslPadding(int32_t padding, int32_t *opensslPadding) } } -int32_t GetRealPrimes(int32_t primesFlag) -{ - switch (primesFlag) { - case HCF_OPENSSL_PRIMES_2: - return PRIMES_2; - case HCF_OPENSSL_PRIMES_3: - return PRIMES_3; - case HCF_OPENSSL_PRIMES_4: - return PRIMES_4; - case HCF_OPENSSL_PRIMES_5: - return PRIMES_5; - default: - LOGD("set default primes 2"); - return PRIMES_2; - } -} - bool IsBigEndian(void) { uint32_t *pointer = (uint32_t *)&ASCII_CODE_ZERO; @@ -454,9 +432,9 @@ HcfResult BigIntegerToBigNum(const HcfBigInteger *src, BIGNUM **dest) } if (IsBigEndian()) { - *dest = OpensslBin2Bn((src->data), (src->len), NULL); + *dest = OpensslBin2Bn((src->data), (src->len), *dest); } else { - *dest = OpensslLeBin2Bn((src->data), (src->len), NULL); + *dest = OpensslLeBin2Bn((src->data), (src->len), *dest); } if (*dest == NULL) { @@ -537,20 +515,16 @@ HcfResult KeyDerive(EVP_PKEY *priKey, EVP_PKEY *pubKey, HcfBlob *returnSecret) ret = HCF_ERR_MALLOC; break; } - size_t actualLen = maxLen; - if (OpensslEvpPkeyDerive(ctx, secretData, &actualLen) != HCF_OPENSSL_SUCCESS) { + + if (OpensslEvpPkeyDerive(ctx, secretData, &maxLen) != HCF_OPENSSL_SUCCESS) { LOGD("[error] Evp key derive failed!"); HcfPrintOpensslError(); HcfFree(secretData); break; } - if (actualLen > maxLen) { - LOGD("[error] signature data too long."); - HcfFree(secretData); - break; - } + returnSecret->data = secretData; - returnSecret->len = actualLen; + returnSecret->len = maxLen; ret = HCF_SUCCESS; } while (0); OpensslEvpPkeyCtxFree(ctx); @@ -577,3 +551,62 @@ HcfResult GetKeyEncodedPem(EVP_PKEY *pkey, const char *outPutStruct, int selecti OpensslOsslEncoderCtxFree(ctx); return HCF_SUCCESS; } + +HcfResult ConvertPubPemStrToKey(EVP_PKEY **pkey, const char *keyType, int selection, const char *keyStr) +{ + OSSL_DECODER_CTX *ctx = OpensslOsslDecoderCtxNewForPkey(pkey, "PEM", NULL, keyType, selection, NULL, NULL); + if (ctx == NULL) { + LOGE("Failed to init pem public key decoder ctx."); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + size_t pdataLen = strlen(keyStr); + const unsigned char *pdata = (const unsigned char *)keyStr; + int ret = OpensslOsslDecoderFromData(ctx, &pdata, &pdataLen); + OpensslOsslDecoderCtxFree(ctx); + if (ret != HCF_OPENSSL_SUCCESS) { + LOGE("Failed to decode public key from pem data."); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + return HCF_SUCCESS; +} + +int PrivateKeyReadNullCb(char *buf, int size, int rwflag, void *userdata) +{ + LOGE("Failed to read private key from bio."); + return -1; +} + +HcfResult ConvertPriPemStrToKey(const char *keyStr, EVP_PKEY **pkey, const char *keyType) +{ + BIO *bio = OpensslBioNew(OpensslBioSMem()); + if (bio == NULL) { + LOGE("Failed to init bio."); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + + if (OpensslBioWrite(bio, keyStr, strlen(keyStr)) <= 0) { + OpensslBioFreeAll(bio); + LOGE("Failed to write pem private key to bio"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + + EVP_PKEY *pkeyRet = OpensslPemReadBioPrivateKey(bio, pkey, PrivateKeyReadNullCb, NULL); + OpensslBioFreeAll(bio); + if (pkeyRet == NULL) { + LOGE("Failed to read private key from bio"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + + if (OpensslEvpPkeyIsA(*pkey, keyType) != HCF_OPENSSL_SUCCESS) { + LOGE("Private key type does not match current alg [%s].", keyType); + OpensslEvpPkeyFree(*pkey); + return HCF_INVALID_PARAMS; + } + + return HCF_SUCCESS; +} diff --git a/plugin/openssl_plugin/crypto_operation/cipher/src/cipher_3des_openssl.c b/plugin/openssl_plugin/crypto_operation/cipher/src/cipher_3des_openssl.c index 01bf8f29a65da2e3fcd525df79ea85bb83b551f7..b8c1c458979c72c5946af99b96dcf698eb59776a 100644 --- a/plugin/openssl_plugin/crypto_operation/cipher/src/cipher_3des_openssl.c +++ b/plugin/openssl_plugin/crypto_operation/cipher/src/cipher_3des_openssl.c @@ -192,7 +192,7 @@ static HcfResult EngineUpdate(HcfCipherGeneratorSpi *self, HcfBlob *input, HcfBl res = HCF_SUCCESS; clearup: if (res != HCF_SUCCESS) { - HcfBlobDataFree(output); + HcfBlobDataClearAndFree(output); FreeCipherData(&(cipherImpl->cipherData)); } else { FreeRedundantOutput(output); @@ -253,7 +253,7 @@ static HcfResult EngineDoFinal(HcfCipherGeneratorSpi *self, HcfBlob *input, HcfB } clearup: if (res != HCF_SUCCESS) { - HcfBlobDataFree(output); + HcfBlobDataClearAndFree(output); } else { FreeRedundantOutput(output); } diff --git a/plugin/openssl_plugin/crypto_operation/cipher/src/cipher_aes_openssl.c b/plugin/openssl_plugin/crypto_operation/cipher/src/cipher_aes_openssl.c index 8720c590daef4cf1da5f07d50b8a3267d475394d..d3df53b248469e9e36572236136e5395b3baee44 100644 --- a/plugin/openssl_plugin/crypto_operation/cipher/src/cipher_aes_openssl.c +++ b/plugin/openssl_plugin/crypto_operation/cipher/src/cipher_aes_openssl.c @@ -532,7 +532,7 @@ static HcfResult EngineUpdate(HcfCipherGeneratorSpi *self, HcfBlob *input, HcfBl ret = AeadUpdate(data, cipherImpl->attr.mode, input, output); } if (ret != HCF_SUCCESS) { - HcfBlobDataFree(output); + HcfBlobDataClearAndFree(output); FreeCipherData(&(cipherImpl->cipherData)); } data->aead = false; @@ -575,7 +575,7 @@ static HcfResult AllocateCcmOutput(CipherData *data, HcfBlob *input, HcfBlob *ou outLen += input->len; *isUpdateInput = true; } - uint32_t authTagLen = data->enc == ENCRYPT_MODE ? CCM_TAG_SIZE : 0; + uint32_t authTagLen = (data->enc == ENCRYPT_MODE) ? CCM_TAG_SIZE : 0; outLen += authTagLen + AES_BLOCK_SIZE; if (outLen == 0) { LOGE("output size is invaild!"); @@ -596,7 +596,7 @@ static HcfResult CcmDecryptDoFinal(HcfBlob *output, bool isUpdateInput) return HCF_SUCCESS; } if (output->data != NULL) { - HcfBlobDataFree(output); + HcfBlobDataClearAndFree(output); } return HCF_SUCCESS; } @@ -688,7 +688,7 @@ static HcfResult AllocateGcmOutput(CipherData *data, HcfBlob *input, HcfBlob *ou outLen += input->len; *isUpdateInput = true; } - uint32_t authTagLen = data->enc == ENCRYPT_MODE ? GCM_TAG_SIZE : 0; + uint32_t authTagLen = (data->enc == ENCRYPT_MODE) ? GCM_TAG_SIZE : 0; outLen += data->updateLen + authTagLen + AES_BLOCK_SIZE; if (outLen == 0) { LOGE("output size is invaild!"); @@ -767,7 +767,7 @@ static HcfResult EngineDoFinal(HcfCipherGeneratorSpi *self, HcfBlob *input, HcfB FreeCipherData(&(cipherImpl->cipherData)); if (ret != HCF_SUCCESS) { - HcfBlobDataFree(output); + HcfBlobDataClearAndFree(output); } FreeRedundantOutput(output); return ret; diff --git a/plugin/openssl_plugin/crypto_operation/cipher/src/cipher_rsa_openssl.c b/plugin/openssl_plugin/crypto_operation/cipher/src/cipher_rsa_openssl.c index 3c796810086e1df7315c12a8c5713e7960f5f352..d567d0bc1c303c90dd2e4809e3b6c5dbe7baa22c 100644 --- a/plugin/openssl_plugin/crypto_operation/cipher/src/cipher_rsa_openssl.c +++ b/plugin/openssl_plugin/crypto_operation/cipher/src/cipher_rsa_openssl.c @@ -72,7 +72,6 @@ static HcfResult DuplicateRsaFromKey(HcfKey *key, enum HcfCryptoMode opMode, RSA LOGD("[error] dup pub RSA fail."); return ret; } - LOGD("dup pub RSA success."); } else if (opMode == DECRYPT_MODE) { // dup will check if rsa is NULL ret = DuplicateRsa(((HcfOpensslRsaPriKey *)key)->sk, true, dupRsa); @@ -80,7 +79,6 @@ static HcfResult DuplicateRsaFromKey(HcfKey *key, enum HcfCryptoMode opMode, RSA LOGD("[error] dup pri RSA fail."); return ret; } - LOGD("dup pri RSA success."); } else { LOGD("[error] OpMode not match."); return HCF_INVALID_PARAMS; @@ -122,6 +120,7 @@ static HcfResult InitEvpPkeyCtx(HcfCipherRsaGeneratorSpiImpl *impl, HcfKey *key, HcfPrintOpensslError(); OpensslEvpPkeyFree(pkey); OpensslEvpPkeyCtxFree(impl->ctx); + impl->ctx = NULL; return HCF_ERR_CRYPTO_OPERATION; } OpensslEvpPkeyFree(pkey); @@ -175,8 +174,8 @@ static HcfResult SetDetailParams(HcfCipherRsaGeneratorSpiImpl *impl) (void)GetOpensslDigestAlg(attr.md, &md); (void)GetOpensslDigestAlg(attr.mgf1md, &mgf1md); // set md and mgf1md - if (OpensslEvpPkeyCtxSetRsaOaepMd(impl->ctx, md) != HCF_OPENSSL_SUCCESS - || OpensslEvpPkeyCtxSetRsaMgf1Md(impl->ctx, mgf1md) != HCF_OPENSSL_SUCCESS) { + if (OpensslEvpPkeyCtxSetRsaOaepMd(impl->ctx, md) != HCF_OPENSSL_SUCCESS || + OpensslEvpPkeyCtxSetRsaMgf1Md(impl->ctx, mgf1md) != HCF_OPENSSL_SUCCESS) { LOGD("[error] Set md or mgf1md fail"); HcfPrintOpensslError(); return HCF_ERR_CRYPTO_OPERATION; @@ -413,7 +412,6 @@ static HcfResult EngineDoFinal(HcfCipherGeneratorSpi *self, HcfBlob *input, HcfB LOGD("[error] GetOutLen fail."); return HCF_ERR_CRYPTO_OPERATION; } - LOGD("ouput data len is %zu.", output->len); output->data = (uint8_t *)HcfMalloc(sizeof(uint8_t) * output->len, 0); if (output->data == NULL) { @@ -516,6 +514,5 @@ HcfResult HcfCipherRsaCipherSpiCreate(CipherAttr *params, HcfCipherGeneratorSpi returnImpl->super.base.getClass = EngineGetClass; returnImpl->initFlag = UNINITIALIZED; *generator = (HcfCipherGeneratorSpi *)returnImpl; - LOGD("Rsa Cipher create success."); return HCF_SUCCESS; } diff --git a/plugin/openssl_plugin/crypto_operation/cipher/src/cipher_sm2_crypto_util_openssl.c b/plugin/openssl_plugin/crypto_operation/cipher/src/cipher_sm2_crypto_util_openssl.c index c3405fde5864fb1c6c9b40bf6cfa387abea165e3..94d70a89d2c663c2fa38094c5f15604aa2ea1a66 100644 --- a/plugin/openssl_plugin/crypto_operation/cipher/src/cipher_sm2_crypto_util_openssl.c +++ b/plugin/openssl_plugin/crypto_operation/cipher/src/cipher_sm2_crypto_util_openssl.c @@ -33,8 +33,6 @@ static HcfResult BuildSm2Ciphertext(const Sm2CipherTextSpec *spec, struct Sm2Cip LOGE("Build y failed."); return HCF_ERR_CRYPTO_OPERATION; } - sm2Text->c3 = OpensslAsn1OctetStringNew(); - sm2Text->c2 = OpensslAsn1OctetStringNew(); if (sm2Text->c3 == NULL || sm2Text->c2 == NULL) { LOGE("SM2 openssl [ASN1_OCTET_STRING_new] c3 c2 fail"); HcfPrintOpensslError(); diff --git a/plugin/openssl_plugin/crypto_operation/cipher/src/cipher_sm4_openssl.c b/plugin/openssl_plugin/crypto_operation/cipher/src/cipher_sm4_openssl.c index 750f2ac515256552c5426486e8372209c13e45c3..0d3fafd5f0935f99e7f0822a44355f6dd5728700 100644 --- a/plugin/openssl_plugin/crypto_operation/cipher/src/cipher_sm4_openssl.c +++ b/plugin/openssl_plugin/crypto_operation/cipher/src/cipher_sm4_openssl.c @@ -302,8 +302,8 @@ static HcfResult CheckParam(HcfCipherGeneratorSpi* self, enum HcfCryptoMode opMo cipherImpl->attr.paddingMode = HCF_ALG_NOPADDING; LOGD("Default paddingMode is %u", HCF_ALG_NOPADDING); } - if (cipherImpl->attr.paddingMode != HCF_ALG_NOPADDING && cipherImpl->attr.paddingMode != HCF_ALG_PADDING_PKCS5 - && cipherImpl->attr.paddingMode != HCF_ALG_PADDING_PKCS7) { + if (cipherImpl->attr.paddingMode != HCF_ALG_NOPADDING && cipherImpl->attr.paddingMode != HCF_ALG_PADDING_PKCS5 && + cipherImpl->attr.paddingMode != HCF_ALG_PADDING_PKCS7) { LOGE("Invalid padding mode %u", cipherImpl->attr.paddingMode); return HCF_INVALID_PARAMS; } @@ -459,7 +459,7 @@ static HcfResult EngineUpdate(HcfCipherGeneratorSpi *self, HcfBlob *input, HcfBl ret = AeadUpdate(data, cipherImpl->attr.mode, input, output); } if (ret != HCF_SUCCESS) { - HcfBlobDataFree(output); + HcfBlobDataClearAndFree(output); FreeCipherData(&(cipherImpl->cipherData)); } data->aead = false; @@ -474,7 +474,7 @@ static HcfResult AllocateGcmOutput(CipherData *data, HcfBlob *input, HcfBlob *ou outLen += input->len; *isUpdateInput = true; } - uint32_t authTagLen = data->enc == ENCRYPT_MODE ? GCM_TAG_SIZE : 0; + uint32_t authTagLen = (data->enc == ENCRYPT_MODE) ? GCM_TAG_SIZE : 0; outLen += data->updateLen + authTagLen + SM4_BLOCK_SIZE; if (outLen == 0) { LOGE("output size is invaild!"); @@ -624,7 +624,7 @@ static HcfResult EngineDoFinal(HcfCipherGeneratorSpi* self, HcfBlob* input, HcfB FreeCipherData(&(cipherImpl->cipherData)); if (ret != HCF_SUCCESS) { - HcfBlobDataFree(output); + HcfBlobDataClearAndFree(output); } FreeRedundantOutput(output); return ret; diff --git a/plugin/openssl_plugin/crypto_operation/md/src/md_openssl.c b/plugin/openssl_plugin/crypto_operation/md/src/md_openssl.c index 58f62f557bfbf4f576c56ee344c7f9dd512cbe83..ffcb32e8a085d1211c9c12c6c679a872652c9bda 100644 --- a/plugin/openssl_plugin/crypto_operation/md/src/md_openssl.c +++ b/plugin/openssl_plugin/crypto_operation/md/src/md_openssl.c @@ -67,6 +67,10 @@ static const EVP_MD *OpensslGetMdAlgoFromString(const char *mdName) static HcfResult OpensslEngineUpdateMd(HcfMdSpi *self, HcfBlob *input) { + if (input == NULL) { + LOGE("The input is NULL!"); + return HCF_INVALID_PARAMS; + } if (OpensslGetMdCtx(self) == NULL) { LOGD("[error] The CTX is NULL!"); return HCF_ERR_CRYPTO_OPERATION; @@ -81,6 +85,10 @@ static HcfResult OpensslEngineUpdateMd(HcfMdSpi *self, HcfBlob *input) static HcfResult OpensslEngineDoFinalMd(HcfMdSpi *self, HcfBlob *output) { + if (output == NULL) { + LOGE("The output is NULL!"); + return HCF_INVALID_PARAMS; + } EVP_MD_CTX *localCtx = OpensslGetMdCtx(self); if (localCtx == NULL) { LOGE("The CTX is NULL!"); @@ -136,13 +144,13 @@ static void OpensslDestroyMd(HcfObjectBase *self) HcfResult OpensslMdSpiCreate(const char *opensslAlgoName, HcfMdSpi **spiObj) { - if (spiObj == NULL) { + if (spiObj == NULL || opensslAlgoName == NULL) { LOGE("Invalid input parameter."); return HCF_INVALID_PARAMS; } OpensslMdSpiImpl *returnSpiImpl = (OpensslMdSpiImpl *)HcfMalloc(sizeof(OpensslMdSpiImpl), 0); if (returnSpiImpl == NULL) { - LOGE("Failed to allocate returnImpl memory!"); + LOGE("Failed to allocate MdSpiImpl memory!"); return HCF_ERR_MALLOC; } returnSpiImpl->ctx = OpensslEvpMdCtxNew(); @@ -152,6 +160,12 @@ HcfResult OpensslMdSpiCreate(const char *opensslAlgoName, HcfMdSpi **spiObj) return HCF_ERR_MALLOC; } const EVP_MD *mdfunc = OpensslGetMdAlgoFromString(opensslAlgoName); + if (mdfunc == NULL) { + LOGE("OpensslGetMdAlgoFromString failed!"); + OpensslEvpMdCtxFree(returnSpiImpl->ctx); + HcfFree(returnSpiImpl); + return HCF_ERR_CRYPTO_OPERATION; + } int32_t ret = OpensslEvpDigestInitEx(returnSpiImpl->ctx, mdfunc, NULL); if (ret != HCF_OPENSSL_SUCCESS) { LOGD("[error] Failed to init MD!"); diff --git a/plugin/openssl_plugin/crypto_operation/rand/src/rand_openssl.c b/plugin/openssl_plugin/crypto_operation/rand/src/rand_openssl.c index 8ba2e1719392ad27c6c63229e44b6a10010eb88e..78bb9691d9df582a6166a0fe03d9d4fa77112d35 100644 --- a/plugin/openssl_plugin/crypto_operation/rand/src/rand_openssl.c +++ b/plugin/openssl_plugin/crypto_operation/rand/src/rand_openssl.c @@ -75,6 +75,11 @@ static const char *GetRandAlgoName(HcfRandSpi *self) static void OpensslSetSeed(HcfRandSpi *self, HcfBlob *seed) { + (void)self; + if (seed == NULL) { + LOGE("The seed is NULL!"); + return; + } OpensslRandSeed(seed->data, seed->len); } diff --git a/plugin/openssl_plugin/crypto_operation/signature/src/dsa_openssl.c b/plugin/openssl_plugin/crypto_operation/signature/src/dsa_openssl.c index 2debcae3db6270c106618a2000279816ed4a7638..03fb3f146492ccf237ba42ca9652ad955df3c04c 100644 --- a/plugin/openssl_plugin/crypto_operation/signature/src/dsa_openssl.c +++ b/plugin/openssl_plugin/crypto_operation/signature/src/dsa_openssl.c @@ -378,20 +378,15 @@ static HcfResult EngineDsaSignDoFinal(HcfSignSpi *self, HcfBlob *data, HcfBlob * LOGE("Failed to allocate signatureData memory!"); return HCF_ERR_MALLOC; } - size_t actualLen = maxLen; - if (OpensslEvpDigestSignFinal(impl->mdCtx, signatureData, &actualLen) != HCF_OPENSSL_SUCCESS) { + + if (OpensslEvpDigestSignFinal(impl->mdCtx, signatureData, &maxLen) != HCF_OPENSSL_SUCCESS) { HcfPrintOpensslError(); HcfFree(signatureData); return HCF_ERR_CRYPTO_OPERATION; } - if (actualLen > maxLen) { - LOGD("[error] Signature data too long."); - HcfFree(signatureData); - return HCF_ERR_CRYPTO_OPERATION; - } returnSignatureData->data = signatureData; - returnSignatureData->len = (uint32_t)actualLen; + returnSignatureData->len = (uint32_t)maxLen; return HCF_SUCCESS; } diff --git a/plugin/openssl_plugin/crypto_operation/signature/src/ecdsa_openssl.c b/plugin/openssl_plugin/crypto_operation/signature/src/ecdsa_openssl.c index d369fb87d355f09be15875103c95feb6abb32755..3c8f67176ae76c1cb7bfc568085ec4419bbc49fd 100644 --- a/plugin/openssl_plugin/crypto_operation/signature/src/ecdsa_openssl.c +++ b/plugin/openssl_plugin/crypto_operation/signature/src/ecdsa_openssl.c @@ -225,21 +225,16 @@ static HcfResult EngineSignDoFinal(HcfSignSpi *self, HcfBlob *data, HcfBlob *ret LOGE("Failed to allocate outData memory!"); return HCF_ERR_MALLOC; } - size_t actualLen = maxLen; - if (OpensslEvpDigestSignFinal(impl->ctx, outData, &actualLen) != HCF_OPENSSL_SUCCESS) { + + if (OpensslEvpDigestSignFinal(impl->ctx, outData, &maxLen) != HCF_OPENSSL_SUCCESS) { HcfPrintOpensslError(); LOGD("[error] EVP_DigestSignFinal failed."); HcfFree(outData); return HCF_ERR_CRYPTO_OPERATION; } - if (actualLen > maxLen) { - LOGD("[error] signature data too long."); - HcfFree(outData); - return HCF_ERR_CRYPTO_OPERATION; - } returnSignatureData->data = outData; - returnSignatureData->len = (uint32_t)actualLen; + returnSignatureData->len = (uint32_t)maxLen; return HCF_SUCCESS; } diff --git a/plugin/openssl_plugin/crypto_operation/signature/src/ed25519_openssl.c b/plugin/openssl_plugin/crypto_operation/signature/src/ed25519_openssl.c index b0c6f3b7db2edc9a8df12808e0537e2f82e57ea9..4c391c64668c06914c776eea721fcdd9725e5553 100644 --- a/plugin/openssl_plugin/crypto_operation/signature/src/ed25519_openssl.c +++ b/plugin/openssl_plugin/crypto_operation/signature/src/ed25519_openssl.c @@ -111,19 +111,13 @@ static HcfResult EngineSignInit(HcfSignSpi *self, HcfParamsSpec *params, HcfPriK LOGE("Repeated initialization is not allowed."); return HCF_INVALID_PARAMS; } - EVP_PKEY *pKey = OpensslEvpPkeyDup(((HcfOpensslAlg25519PriKey *)privateKey)->pkey); - if (pKey == NULL) { - HcfPrintOpensslError(); - LOGD("[error] Dup pkey failed."); - return HCF_ERR_CRYPTO_OPERATION; - } - if (OpensslEvpDigestSignInit(impl->mdCtx, NULL, NULL, NULL, pKey) != HCF_OPENSSL_SUCCESS) { + + if (OpensslEvpDigestSignInit(impl->mdCtx, NULL, NULL, NULL, + ((HcfOpensslAlg25519PriKey *)privateKey)->pkey) != HCF_OPENSSL_SUCCESS) { HcfPrintOpensslError(); LOGD("[error] EVP_DigestSignInit failed."); - OpensslEvpPkeyFree(pKey); return HCF_ERR_CRYPTO_OPERATION; } - OpensslEvpPkeyFree(pKey); impl->status = INITIALIZED; return HCF_SUCCESS; } diff --git a/plugin/openssl_plugin/crypto_operation/signature/src/signature_rsa_openssl.c b/plugin/openssl_plugin/crypto_operation/signature/src/signature_rsa_openssl.c index fa11d7ba55dc9a14d18b785f18e86f70ecb30678..4ac193d4a344b497cb8408fca435fbc3f62ef760 100644 --- a/plugin/openssl_plugin/crypto_operation/signature/src/signature_rsa_openssl.c +++ b/plugin/openssl_plugin/crypto_operation/signature/src/signature_rsa_openssl.c @@ -104,8 +104,6 @@ static void DestroyRsaSign(HcfObjectBase *self) impl->ctx = NULL; } HcfFree(impl); - impl = NULL; - LOGD("DestroyRsaSign success."); } static void DestroyRsaVerify(HcfObjectBase *self) @@ -126,8 +124,6 @@ static void DestroyRsaVerify(HcfObjectBase *self) impl->ctx = NULL; } HcfFree(impl); - impl = NULL; - LOGD("DestroyRsaVerify success."); } static HcfResult CheckInitKeyType(HcfKey *key, bool signing) @@ -251,6 +247,7 @@ static HcfResult SetSignParams(HcfSignSpiRsaOpensslImpl *impl, HcfPriKey *privat EVP_MD *opensslAlg = NULL; (void)GetOpensslDigestAlg(impl->md, &opensslAlg); if (opensslAlg == NULL) { + OpensslEvpPkeyFree(dupKey); LOGE("Get openssl digest alg fail"); return HCF_INVALID_PARAMS; } @@ -318,6 +315,7 @@ static HcfResult SetVerifyParams(HcfVerifySpiRsaOpensslImpl *impl, HcfPubKey *pu EVP_MD *opensslAlg = NULL; (void)GetOpensslDigestAlg(impl->md, &opensslAlg); if (opensslAlg == NULL) { + OpensslEvpPkeyFree(dupKey); LOGE("Get openssl digest alg fail"); return HCF_INVALID_PARAMS; } @@ -529,20 +527,15 @@ static HcfResult EngineDigestSign(HcfSignSpiRsaOpensslImpl *impl, HcfBlob *data, LOGE("Failed to allocate outData memory!"); return HCF_ERR_MALLOC; } - size_t actualLen = maxLen; - if (OpensslEvpDigestSignFinal(impl->mdctx, outData, &actualLen) != HCF_OPENSSL_SUCCESS) { + + if (OpensslEvpDigestSignFinal(impl->mdctx, outData, &maxLen) != HCF_OPENSSL_SUCCESS) { LOGD("[error] OpensslEvpDigestSignFinal fail"); HcfFree(outData); HcfPrintOpensslError(); return HCF_ERR_CRYPTO_OPERATION; } - if (actualLen > maxLen) { - LOGD("[error] signature data too long."); - HcfFree(outData); - return HCF_ERR_CRYPTO_OPERATION; - } returnSignatureData->data = outData; - returnSignatureData->len = (uint32_t)actualLen; + returnSignatureData->len = (uint32_t)maxLen; return HCF_SUCCESS; } @@ -631,7 +624,7 @@ static HcfResult EngineRecover(HcfVerifySpi *self, HcfBlob *signatureData, HcfBl size_t bufLen = 0; if (OpensslEvpPkeyVerifyRecover(impl->ctx, NULL, &bufLen, signatureData->data, signatureData->len) - != HCF_OPENSSL_SUCCESS) { + != HCF_OPENSSL_SUCCESS) { LOGE("[error] OpensslEvpPkeyVerifyRecover get len fail."); HcfPrintOpensslError(); return HCF_ERR_CRYPTO_OPERATION; @@ -644,7 +637,7 @@ static HcfResult EngineRecover(HcfVerifySpi *self, HcfBlob *signatureData, HcfBl } if (OpensslEvpPkeyVerifyRecover(impl->ctx, buf, &bufLen, signatureData->data, signatureData->len) - != HCF_OPENSSL_SUCCESS) { + != HCF_OPENSSL_SUCCESS) { LOGE("[error] OpensslEvpPkeyVerifyRecover fail."); HcfPrintOpensslError(); HcfFree(buf); @@ -981,7 +974,7 @@ HcfResult HcfSignSpiRsaCreate(HcfSignatureParams *params, HcfSignSpi **returnObj } returnImpl->initFlag = UNINITIALIZED; returnImpl->saltLen = PSS_SALTLEN_INVALID_INIT; - returnImpl->operation = params->operation == HCF_ALG_ONLY_SIGN ? HCF_OPERATIOPN_ONLY_SIGN : HCF_OPERATION_SIGN; + returnImpl->operation = (params->operation == HCF_ALG_ONLY_SIGN) ? HCF_OPERATIOPN_ONLY_SIGN : HCF_OPERATION_SIGN; *returnObj = (HcfSignSpi *)returnImpl; return HCF_SUCCESS; } diff --git a/plugin/openssl_plugin/crypto_operation/signature/src/sm2_openssl.c b/plugin/openssl_plugin/crypto_operation/signature/src/sm2_openssl.c index 897bca35c3a339810cec079318232e422d9eb6c5..f2f57bcc9ac7b3aa6b36f6368a52b74173520c93 100644 --- a/plugin/openssl_plugin/crypto_operation/signature/src/sm2_openssl.c +++ b/plugin/openssl_plugin/crypto_operation/signature/src/sm2_openssl.c @@ -89,6 +89,7 @@ static void DestroySm2Sign(HcfObjectBase *self) HcfSignSpiSm2OpensslImpl *impl = (HcfSignSpiSm2OpensslImpl *)self; impl->digestAlg = NULL; if (impl->mdCtx != NULL) { + OpensslEvpPkeyCtxFree(OpensslEvpMdCtxGetPkeyCtx(impl->mdCtx)); OpensslEvpMdCtxFree(impl->mdCtx); impl->mdCtx = NULL; } @@ -110,6 +111,7 @@ static void DestroySm2Verify(HcfObjectBase *self) HcfVerifySpiSm2OpensslImpl *impl = (HcfVerifySpiSm2OpensslImpl *)self; impl->digestAlg = NULL; if (impl->mdCtx != NULL) { + OpensslEvpPkeyCtxFree(OpensslEvpMdCtxGetPkeyCtx(impl->mdCtx)); OpensslEvpMdCtxFree(impl->mdCtx); impl->mdCtx = NULL; } @@ -135,26 +137,13 @@ static HcfResult SetUserIdFromBlob(HcfBlob userId, EVP_MD_CTX *mdCtx) OpensslEvpMdCtxSetPkeyCtx(mdCtx, pKeyCtx); return HCF_SUCCESS; } - // deep copy from userId - uint8_t *opensslUserId = (uint8_t *)HcfMalloc(userId.len, 0); - if (opensslUserId == NULL) { - LOGE("Failed to allocate openssl userId data memory"); - return HCF_ERR_MALLOC; - } - if (memcpy_s(opensslUserId, userId.len, userId.data, userId.len) != EOK) { - LOGE("memcpy opensslUserId failed."); - HcfFree(opensslUserId); - return HCF_ERR_MALLOC; - } - if (OpensslEvpPkeyCtxSet1Id(pKeyCtx, (const void*)opensslUserId, + if (OpensslEvpPkeyCtxSet1Id(pKeyCtx, (const void*)userId.data, userId.len) != HCF_OPENSSL_SUCCESS) { LOGD("[error] Set sm2 user id fail."); - HcfFree(opensslUserId); HcfPrintOpensslError(); return HCF_ERR_CRYPTO_OPERATION; } OpensslEvpMdCtxSetPkeyCtx(mdCtx, pKeyCtx); - HcfFree(opensslUserId); return HCF_SUCCESS; } @@ -300,21 +289,16 @@ static HcfResult EngineSignDoFinal(HcfSignSpi *self, HcfBlob *data, HcfBlob *ret LOGE("Failed to allocate outData memory!"); return HCF_ERR_MALLOC; } - size_t actualLen = maxLen; - if (OpensslEvpDigestSignFinal(impl->mdCtx, outData, &actualLen) != HCF_OPENSSL_SUCCESS) { + + if (OpensslEvpDigestSignFinal(impl->mdCtx, outData, &maxLen) != HCF_OPENSSL_SUCCESS) { HcfPrintOpensslError(); LOGD("[error] EVP_DigestSignFinal failed."); HcfFree(outData); return HCF_ERR_CRYPTO_OPERATION; } - if (actualLen > maxLen) { - LOGD("[error] signature data too long."); - HcfFree(outData); - return HCF_ERR_CRYPTO_OPERATION; - } returnSignatureData->data = outData; - returnSignatureData->len = (uint32_t)actualLen; + returnSignatureData->len = (uint32_t)maxLen; return HCF_SUCCESS; } diff --git a/plugin/openssl_plugin/key/asy_key_generator/src/alg_25519_asy_key_generator_openssl.c b/plugin/openssl_plugin/key/asy_key_generator/src/alg_25519_asy_key_generator_openssl.c index 29d1236ab24860ac01ba20736958762c99962a6d..d29922be2082c2320ce5f35ca595865497124e2b 100644 --- a/plugin/openssl_plugin/key/asy_key_generator/src/alg_25519_asy_key_generator_openssl.c +++ b/plugin/openssl_plugin/key/asy_key_generator/src/alg_25519_asy_key_generator_openssl.c @@ -67,16 +67,21 @@ static const char *GetAlg25519PriKeyClass(void) static void DestroyAlg25519KeyGeneratorSpiImpl(HcfObjectBase *self) { - if (self == NULL) { + if ((self == NULL) || (self->getClass() == NULL)) { LOGE("Invalid input parameter."); return; } - if (!HcfIsClassMatch(self, GetEd25519KeyGeneratorSpiClass()) && - !HcfIsClassMatch(self, GetX25519KeyGeneratorSpiClass())) { - LOGE("Invalid class of self."); + + if (strcmp(self->getClass(), GetX25519KeyGeneratorSpiClass()) == 0) { + HcfFree(self); return; } - HcfFree(self); + + if (strcmp(self->getClass(), GetEd25519KeyGeneratorSpiClass()) == 0) { + HcfFree(self); + return; + } + LOGE("Invalid input parameter."); } static void DestroyAlg25519PubKey(HcfObjectBase *self) @@ -774,6 +779,153 @@ static HcfResult EngineConvertAlg25519Key(HcfAsyKeyGeneratorSpi *self, HcfParams return ret; } +static HcfResult ConvertAlg25519PemPubKey(int type, const char *pubKeyStr, HcfOpensslAlg25519PubKey **returnPubKey) +{ + EVP_PKEY *pkey = NULL; + const char *keyType = NULL; + if (type == EVP_PKEY_ED25519) { + keyType = "ED25519"; + } + if (type == EVP_PKEY_X25519) { + keyType = "X25519"; + } + + HcfResult ret = ConvertPubPemStrToKey(&pkey, keyType, EVP_PKEY_PUBLIC_KEY, pubKeyStr); + if (ret != HCF_SUCCESS) { + LOGE("Convert public key from pem to key failed."); + return ret; + } + + ret = CreateAlg25519PubKey(pkey, returnPubKey); + if (ret != HCF_SUCCESS) { + LOGE("Create alg25519 public key failed."); + OpensslEvpPkeyFree(pkey); + } + + return ret; +} + +static HcfResult ConvertAlg25519PemPriKey(int type, const char *priKeyStr, HcfOpensslAlg25519PriKey **returnPriKey) +{ + EVP_PKEY *pkey = NULL; + const char *keyType = NULL; + if (type == EVP_PKEY_ED25519) { + keyType = "ED25519"; + } + if (type == EVP_PKEY_X25519) { + keyType = "X25519"; + } + + HcfResult ret = ConvertPriPemStrToKey(priKeyStr, &pkey, keyType); + if (ret != HCF_SUCCESS) { + LOGE("Convert private key from pem to key failed."); + return ret; + } + + ret = CreateAlg25519PriKey(pkey, returnPriKey); + if (ret != HCF_SUCCESS) { + LOGE("Create alg25519 private key failed."); + OpensslEvpPkeyFree(pkey); + } + return ret; +} + +static HcfResult ConvertAlg25519PemPubAndPriKey(int type, const char *pubKeyStr, const char *priKeyStr, + HcfOpensslAlg25519PubKey **returnPubKey, HcfOpensslAlg25519PriKey **returnPriKey) +{ + if (pubKeyStr != NULL && strlen(pubKeyStr) != 0) { + if (ConvertAlg25519PemPubKey(type, pubKeyStr, returnPubKey) != HCF_SUCCESS) { + LOGE("Convert alg25519 pem public key failed."); + return HCF_ERR_CRYPTO_OPERATION; + } + } + if (priKeyStr != NULL && strlen(priKeyStr) != 0) { + if (ConvertAlg25519PemPriKey(type, priKeyStr, returnPriKey) != HCF_SUCCESS) { + LOGE("Convert alg25519 pem private key failed."); + HcfObjDestroy(*returnPubKey); + *returnPubKey = NULL; + return HCF_ERR_CRYPTO_OPERATION; + } + } + return HCF_SUCCESS; +} + +static HcfResult EngineConvertX25519PemKey(HcfAsyKeyGeneratorSpi *self, HcfParamsSpec *params, const char *pubKeyStr, + const char *priKeyStr, HcfKeyPair **returnKeyPair) +{ + (void)params; + if ((self == NULL) || (returnKeyPair == NULL) || ((pubKeyStr == NULL) && (priKeyStr == NULL))) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + + if (!HcfIsClassMatch((HcfObjectBase *)self, GetX25519KeyGeneratorSpiClass())) { + LOGE("Class not match."); + return HCF_INVALID_PARAMS; + } + + HcfOpensslAlg25519PubKey *pubKey = NULL; + HcfOpensslAlg25519PriKey *priKey = NULL; + int type = EVP_PKEY_X25519; + HcfResult ret = ConvertAlg25519PemPubAndPriKey(type, pubKeyStr, priKeyStr, &pubKey, &priKey); + if (ret != HCF_SUCCESS) { + LOGE("Convert alg25519 pem keyPair failed."); + return ret; + } + + if (pubKey != NULL) { + pubKey->type = type; + } + if (priKey != NULL) { + priKey->type = type; + } + ret = CreateAlg25519KeyPair(pubKey, priKey, returnKeyPair); + if (ret != HCF_SUCCESS) { + LOGE("Create alg25519 keyPair failed."); + HcfObjDestroy(pubKey); + HcfObjDestroy(priKey); + } + return ret; +} + +static HcfResult EngineConvertEd25519PemKey(HcfAsyKeyGeneratorSpi *self, HcfParamsSpec *params, const char *pubKeyStr, + const char *priKeyStr, HcfKeyPair **returnKeyPair) +{ + (void)params; + if ((self == NULL) || (returnKeyPair == NULL) || ((pubKeyStr == NULL) && (priKeyStr == NULL))) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + + if (!HcfIsClassMatch((HcfObjectBase *)self, GetEd25519KeyGeneratorSpiClass())) { + LOGE("Class not match."); + return HCF_INVALID_PARAMS; + } + + HcfOpensslAlg25519PubKey *pubKey = NULL; + HcfOpensslAlg25519PriKey *priKey = NULL; + int type = EVP_PKEY_ED25519; + HcfResult ret = ConvertAlg25519PemPubAndPriKey(type, pubKeyStr, priKeyStr, &pubKey, &priKey); + if (ret != HCF_SUCCESS) { + LOGE("Convert alg25519 pem keyPair failed."); + return ret; + } + + if (pubKey != NULL) { + pubKey->type = type; + } + if (priKey != NULL) { + priKey->type = type; + } + ret = CreateAlg25519KeyPair(pubKey, priKey, returnKeyPair); + if (ret != HCF_SUCCESS) { + LOGE("Create alg25519 keyPair failed."); + HcfObjDestroy(pubKey); + HcfObjDestroy(priKey); + } + return ret; +} + static HcfResult CreateOpensslAlg25519PubKey(const HcfBigInteger *pk, const char *algName, EVP_PKEY **returnAlg25519) { @@ -910,7 +1062,7 @@ static HcfResult CreateAlg25519PriKeyByPriKeySpec(const HcfAlg25519PriKeyParamsS static HcfResult EngineGenerateAlg25519PubKeyBySpec(const HcfAsyKeyGeneratorSpi *self, const HcfAsyKeyParamsSpec *paramsSpec, HcfPubKey **returnPubKey) { - if ((self == NULL) || (paramsSpec == NULL) || (returnPubKey == NULL)) { + if ((self == NULL) || (paramsSpec == NULL) || (paramsSpec->algName == NULL) || (returnPubKey == NULL)) { LOGE("Invalid input parameter."); return HCF_INVALID_PARAMS; } @@ -944,7 +1096,7 @@ static HcfResult EngineGenerateAlg25519PubKeyBySpec(const HcfAsyKeyGeneratorSpi static HcfResult EngineGenerateAlg25519PriKeyBySpec(const HcfAsyKeyGeneratorSpi *self, const HcfAsyKeyParamsSpec *paramsSpec, HcfPriKey **returnPriKey) { - if ((self == NULL) || (paramsSpec == NULL) || (returnPriKey == NULL)) { + if ((self == NULL) || (paramsSpec == NULL) || (paramsSpec->algName == NULL) || (returnPriKey == NULL)) { LOGE("Invalid input parameter."); return HCF_INVALID_PARAMS; } @@ -978,7 +1130,7 @@ static HcfResult EngineGenerateAlg25519PriKeyBySpec(const HcfAsyKeyGeneratorSpi static HcfResult EngineGenerateAlg25519KeyPairBySpec(const HcfAsyKeyGeneratorSpi *self, const HcfAsyKeyParamsSpec *paramsSpec, HcfKeyPair **returnKeyPair) { - if ((self == NULL) || (paramsSpec == NULL) || (returnKeyPair == NULL)) { + if ((self == NULL) || (paramsSpec == NULL) || (paramsSpec->algName == NULL) || (returnKeyPair == NULL)) { LOGE("Invalid input parameter."); return HCF_INVALID_PARAMS; } @@ -1010,10 +1162,10 @@ static HcfResult EngineGenerateAlg25519KeyPairBySpec(const HcfAsyKeyGeneratorSpi return ret; } -HcfResult HcfAsyKeyGeneratorSpiEd25519Create(HcfAsyKeyGenParams *params, HcfAsyKeyGeneratorSpi **returnSpi) +HcfResult HcfAsyKeyGeneratorSpiEd25519Create(HcfAsyKeyGenParams *params, HcfAsyKeyGeneratorSpi **returnObj) { (void)params; - if (params == NULL || returnSpi == NULL) { + if (params == NULL || returnObj == NULL) { LOGE("Invalid input parameter."); return HCF_INVALID_PARAMS; } @@ -1027,18 +1179,19 @@ HcfResult HcfAsyKeyGeneratorSpiEd25519Create(HcfAsyKeyGenParams *params, HcfAsyK impl->base.base.destroy = DestroyAlg25519KeyGeneratorSpiImpl; impl->base.engineGenerateKeyPair = EngineGenerateAlg25519KeyPair; impl->base.engineConvertKey = EngineConvertAlg25519Key; + impl->base.engineConvertPemKey = EngineConvertEd25519PemKey; impl->base.engineGenerateKeyPairBySpec = EngineGenerateAlg25519KeyPairBySpec; impl->base.engineGeneratePubKeyBySpec = EngineGenerateAlg25519PubKeyBySpec; impl->base.engineGeneratePriKeyBySpec = EngineGenerateAlg25519PriKeyBySpec; - *returnSpi = (HcfAsyKeyGeneratorSpi *)impl; + *returnObj = (HcfAsyKeyGeneratorSpi *)impl; return HCF_SUCCESS; } -HcfResult HcfAsyKeyGeneratorSpiX25519Create(HcfAsyKeyGenParams *params, HcfAsyKeyGeneratorSpi **returnSpi) +HcfResult HcfAsyKeyGeneratorSpiX25519Create(HcfAsyKeyGenParams *params, HcfAsyKeyGeneratorSpi **returnObj) { (void)params; - if (params == NULL || returnSpi == NULL) { + if (params == NULL || returnObj == NULL) { LOGE("Invalid input parameter."); return HCF_INVALID_PARAMS; } @@ -1052,11 +1205,12 @@ HcfResult HcfAsyKeyGeneratorSpiX25519Create(HcfAsyKeyGenParams *params, HcfAsyKe impl->base.base.destroy = DestroyAlg25519KeyGeneratorSpiImpl; impl->base.engineGenerateKeyPair = EngineGenerateAlg25519KeyPair; impl->base.engineConvertKey = EngineConvertAlg25519Key; + impl->base.engineConvertPemKey = EngineConvertX25519PemKey; impl->base.engineGenerateKeyPairBySpec = EngineGenerateAlg25519KeyPairBySpec; impl->base.engineGeneratePubKeyBySpec = EngineGenerateAlg25519PubKeyBySpec; impl->base.engineGeneratePriKeyBySpec = EngineGenerateAlg25519PriKeyBySpec; - *returnSpi = (HcfAsyKeyGeneratorSpi *)impl; + *returnObj = (HcfAsyKeyGeneratorSpi *)impl; return HCF_SUCCESS; } diff --git a/plugin/openssl_plugin/key/asy_key_generator/src/dh_asy_key_generator_openssl.c b/plugin/openssl_plugin/key/asy_key_generator/src/dh_asy_key_generator_openssl.c index bc4be871348f41487edee51f692be556927a63be..8be26487e542e18faa14299ffc7d44319e8a9d6e 100644 --- a/plugin/openssl_plugin/key/asy_key_generator/src/dh_asy_key_generator_openssl.c +++ b/plugin/openssl_plugin/key/asy_key_generator/src/dh_asy_key_generator_openssl.c @@ -346,8 +346,7 @@ static HcfResult GetBigIntegerSpecFromDhPriKey(const HcfPriKey *self, const AsyK LOGE("Invalid class of self."); return HCF_INVALID_PARAMS; } - HcfResult ret = HCF_SUCCESS; - ret = GetBigIntegerSpec(NULL, self, item, returnBigInteger); + HcfResult ret = GetBigIntegerSpec(NULL, self, item, returnBigInteger); if (ret != HCF_SUCCESS) { LOGE("Get big integer failed."); } @@ -1048,10 +1047,118 @@ static HcfResult EngineConvertDhKey(HcfAsyKeyGeneratorSpi *self, HcfParamsSpec * return ret; } +static HcfResult ConvertDhPemPubKey(const char *pubKeyStr, HcfOpensslDhPubKey **returnPubKey) +{ + EVP_PKEY *pkey = NULL; + const char *keyType = "DH"; + HcfResult ret = ConvertPubPemStrToKey(&pkey, keyType, EVP_PKEY_PUBLIC_KEY, pubKeyStr); + if (ret != HCF_SUCCESS) { + LOGE("Convert dh pem public key failed."); + return ret; + } + + DH *dh = OpensslEvpPkeyGet1Dh(pkey); + OpensslEvpPkeyFree(pkey); + if (dh == NULL) { + LOGE("Pkey to dh key failed."); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + + ret = CreateDhPubKey(dh, returnPubKey); + if (ret != HCF_SUCCESS) { + LOGE("Create dh public key failed."); + OpensslDhFree(dh); + } + + return ret; +} + +static HcfResult ConvertDhPemPriKey(const char *priKeyStr, HcfOpensslDhPriKey **returnPriKey) +{ + EVP_PKEY *pkey = NULL; + const char *keyType = "DH"; + HcfResult ret = ConvertPriPemStrToKey(priKeyStr, &pkey, keyType); + if (ret != HCF_SUCCESS) { + LOGE("Convert dh pem private key failed."); + return ret; + } + + DH *dh = OpensslEvpPkeyGet1Dh(pkey); + OpensslEvpPkeyFree(pkey); + if (dh == NULL) { + LOGE("Pkey to dh key failed."); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + + ret = CreateDhPriKey(dh, returnPriKey); + if (ret != HCF_SUCCESS) { + LOGE("Create DH private key failed."); + OpensslDhFree(dh); + } + + return ret; +} + +static HcfResult ConvertDhPemPubAndPriKey(const char *pubKeyStr, const char *priKeyStr, + HcfOpensslDhPubKey **returnPubKey, HcfOpensslDhPriKey **returnPriKey) +{ + if (pubKeyStr != NULL && strlen(pubKeyStr) != 0) { + if (ConvertDhPemPubKey(pubKeyStr, returnPubKey) != HCF_SUCCESS) { + LOGE("Convert dh pem public key failed."); + return HCF_ERR_CRYPTO_OPERATION; + } + } + + if (priKeyStr != NULL && strlen(priKeyStr) != 0) { + if (ConvertDhPemPriKey(priKeyStr, returnPriKey) != HCF_SUCCESS) { + LOGE("Convert dh pem private key failed."); + HcfObjDestroy(*returnPubKey); + *returnPubKey = NULL; + return HCF_ERR_CRYPTO_OPERATION; + } + } + + return HCF_SUCCESS; +} + +static HcfResult EngineConvertDhPemKey(HcfAsyKeyGeneratorSpi *self, HcfParamsSpec *params, const char *pubKeyStr, + const char *priKeyStr, HcfKeyPair **returnKeyPair) +{ + (void)params; + if ((self == NULL) || (returnKeyPair == NULL) || ((pubKeyStr == NULL) && (priKeyStr == NULL))) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!HcfIsClassMatch((HcfObjectBase *)self, GetDhKeyGeneratorSpiClass())) { + LOGE("Class not match."); + return HCF_INVALID_PARAMS; + } + + HcfOpensslDhPubKey *pubKey = NULL; + HcfOpensslDhPriKey *priKey = NULL; + + HcfResult ret = ConvertDhPemPubAndPriKey(pubKeyStr, priKeyStr, &pubKey, &priKey); + if (ret != HCF_SUCCESS) { + LOGE("Convert dh pem pubKey and priKey failed."); + return ret; + } + + ret = CreateDhKeyPair(pubKey, priKey, returnKeyPair); + if (ret != HCF_SUCCESS) { + LOGE("Create dh keyPair failed."); + HcfObjDestroy(pubKey); + HcfObjDestroy(priKey); + } + + return ret; +} + static HcfResult EngineGenerateDhKeyPairBySpec(const HcfAsyKeyGeneratorSpi *self, const HcfAsyKeyParamsSpec *paramsSpec, HcfKeyPair **returnKeyPair) { - if ((self == NULL) || (paramsSpec == NULL) || (returnKeyPair == NULL)) { + if ((self == NULL) || (paramsSpec == NULL) || (paramsSpec->algName == NULL) || (returnKeyPair == NULL)) { LOGE("Invalid input parameter."); return HCF_INVALID_PARAMS; } @@ -1076,7 +1183,7 @@ static HcfResult EngineGenerateDhKeyPairBySpec(const HcfAsyKeyGeneratorSpi *self static HcfResult EngineGenerateDhPubKeyBySpec(const HcfAsyKeyGeneratorSpi *self, const HcfAsyKeyParamsSpec *paramsSpec, HcfPubKey **returnPubKey) { - if ((self == NULL) || (paramsSpec == NULL) || (returnPubKey == NULL)) { + if ((self == NULL) || (paramsSpec == NULL) || (paramsSpec->algName == NULL) || (returnPubKey == NULL)) { LOGE("Invalid input parameter."); return HCF_INVALID_PARAMS; } @@ -1102,7 +1209,7 @@ static HcfResult EngineGenerateDhPubKeyBySpec(const HcfAsyKeyGeneratorSpi *self, static HcfResult EngineGenerateDhPriKeyBySpec(const HcfAsyKeyGeneratorSpi *self, const HcfAsyKeyParamsSpec *paramsSpec, HcfPriKey **returnPriKey) { - if ((self == NULL) || (paramsSpec == NULL) || (returnPriKey == NULL)) { + if ((self == NULL) || (paramsSpec == NULL) || (paramsSpec->algName == NULL) || (returnPriKey == NULL)) { LOGE("Invalid input parameter."); return HCF_INVALID_PARAMS; } @@ -1123,9 +1230,9 @@ static HcfResult EngineGenerateDhPriKeyBySpec(const HcfAsyKeyGeneratorSpi *self, return ret; } -HcfResult HcfAsyKeyGeneratorSpiDhCreate(HcfAsyKeyGenParams *params, HcfAsyKeyGeneratorSpi **returnSpi) +HcfResult HcfAsyKeyGeneratorSpiDhCreate(HcfAsyKeyGenParams *params, HcfAsyKeyGeneratorSpi **generator) { - if (params == NULL || returnSpi == NULL) { + if (params == NULL || generator == NULL) { LOGE("Invalid input parameter."); return HCF_INVALID_PARAMS; } @@ -1140,10 +1247,11 @@ HcfResult HcfAsyKeyGeneratorSpiDhCreate(HcfAsyKeyGenParams *params, HcfAsyKeyGen impl->base.base.destroy = DestroyDhKeyGeneratorSpiImpl; impl->base.engineGenerateKeyPair = EngineGenerateDhKeyPair; impl->base.engineConvertKey = EngineConvertDhKey; + impl->base.engineConvertPemKey = EngineConvertDhPemKey; impl->base.engineGenerateKeyPairBySpec = EngineGenerateDhKeyPairBySpec; impl->base.engineGeneratePubKeyBySpec = EngineGenerateDhPubKeyBySpec; impl->base.engineGeneratePriKeyBySpec = EngineGenerateDhPriKeyBySpec; - *returnSpi = (HcfAsyKeyGeneratorSpi *)impl; + *generator = (HcfAsyKeyGeneratorSpi *)impl; return HCF_SUCCESS; } \ No newline at end of file diff --git a/plugin/openssl_plugin/key/asy_key_generator/src/dh_common_param_spec_generator_openssl.c b/plugin/openssl_plugin/key/asy_key_generator/src/dh_common_param_spec_generator_openssl.c index b02c6488e8ba9cf32efd776df8a982c63e348d9a..928dab78d12531a56266ec7deb191f4cbb3b216f 100644 --- a/plugin/openssl_plugin/key/asy_key_generator/src/dh_common_param_spec_generator_openssl.c +++ b/plugin/openssl_plugin/key/asy_key_generator/src/dh_common_param_spec_generator_openssl.c @@ -131,7 +131,7 @@ static HcfResult BuildCommonParam(EVP_PKEY *dhKey, HcfDhCommParamsSpecSpi *retur static HcfResult SetAlgName(const char *algName, char **returnAlgName) { size_t srcAlgNameLen = HcfStrlen(algName); - if (!srcAlgNameLen) { + if (srcAlgNameLen == 0) { LOGE("AlgName is empty!"); return HCF_INVALID_PARAMS; } @@ -140,11 +140,7 @@ static HcfResult SetAlgName(const char *algName, char **returnAlgName) LOGE("Failed to malloc algName memory."); return HCF_ERR_MALLOC; } - if (memcpy_s(*returnAlgName, srcAlgNameLen, algName, srcAlgNameLen) != EOK) { - LOGD("[error] Failed to memcpy algName."); - HcfFree(*returnAlgName); - return HCF_ERR_CRYPTO_OPERATION; - } + (void)memcpy_s(*returnAlgName, srcAlgNameLen + 1, algName, srcAlgNameLen); return HCF_SUCCESS; } diff --git a/plugin/openssl_plugin/key/asy_key_generator/src/dsa_asy_key_generator_openssl.c b/plugin/openssl_plugin/key/asy_key_generator/src/dsa_asy_key_generator_openssl.c index 452d79a8f83fe3637fdb81587658d07fba9d1956..2dff8179acfa43b078fcdbebce29ba17484cf115 100644 --- a/plugin/openssl_plugin/key/asy_key_generator/src/dsa_asy_key_generator_openssl.c +++ b/plugin/openssl_plugin/key/asy_key_generator/src/dsa_asy_key_generator_openssl.c @@ -902,10 +902,114 @@ static HcfResult EngineConvertDsaKey(HcfAsyKeyGeneratorSpi *self, HcfParamsSpec return ret; } +static HcfResult ConvertDsaPemPubKey(const char *pubKeyStr, HcfOpensslDsaPubKey **returnPubKey) +{ + EVP_PKEY *pkey = NULL; + const char *keyType = "DSA"; + HcfResult ret = ConvertPubPemStrToKey(&pkey, keyType, EVP_PKEY_PUBLIC_KEY, pubKeyStr); + if (ret != HCF_SUCCESS) { + LOGE("Convert dsa pem public key failed."); + return ret; + } + + DSA *dsa = OpensslEvpPkeyGet1Dsa(pkey); + OpensslEvpPkeyFree(pkey); + if (dsa == NULL) { + LOGE("Pkey to dsa key failed."); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + + ret = CreateDsaPubKey(dsa, returnPubKey); + if (ret != HCF_SUCCESS) { + LOGE("Create dsa public key failed"); + OpensslDsaFree(dsa); + } + return ret; +} + +static HcfResult ConvertDsaPemPriKey(const char *priKeyStr, HcfOpensslDsaPriKey **returnPriKey) +{ + EVP_PKEY *pkey = NULL; + const char *keyType = "DSA"; + HcfResult ret = ConvertPriPemStrToKey(priKeyStr, &pkey, keyType); + if (ret != HCF_SUCCESS) { + LOGE("Convert dsa pem private key failed."); + return ret; + } + + DSA *dsa = OpensslEvpPkeyGet1Dsa(pkey); + OpensslEvpPkeyFree(pkey); + if (dsa == NULL) { + LOGE("Pkey to dsa key failed."); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + + ret = CreateDsaPriKey(dsa, returnPriKey); + if (ret != HCF_SUCCESS) { + LOGE("Create dsa private key failed"); + OpensslDsaFree(dsa); + } + + return ret; +} + +static HcfResult ConvertDsaPemPubAndPriKey(const char *pubKeyStr, const char *priKeyStr, + HcfOpensslDsaPubKey **returnPubKey, HcfOpensslDsaPriKey **returnPriKey) +{ + if (pubKeyStr != NULL && strlen(pubKeyStr) != 0) { + if (ConvertDsaPemPubKey(pubKeyStr, returnPubKey) != HCF_SUCCESS) { + LOGE("Convert dsa pem public key failed."); + return HCF_ERR_CRYPTO_OPERATION; + } + } + + if (priKeyStr != NULL && strlen(priKeyStr) != 0) { + if (ConvertDsaPemPriKey(priKeyStr, returnPriKey) != HCF_SUCCESS) { + LOGE("Convert dsa pem private key failed."); + HcfObjDestroy(*returnPubKey); + *returnPubKey = NULL; + return HCF_ERR_CRYPTO_OPERATION; + } + } + return HCF_SUCCESS; +} + +static HcfResult EngineConvertDsaPemKey(HcfAsyKeyGeneratorSpi *self, HcfParamsSpec *params, const char *pubKeyStr, + const char *priKeyStr, HcfKeyPair **returnKeyPair) +{ + (void)params; + if ((self == NULL) || (returnKeyPair == NULL) || ((pubKeyStr == NULL) && (priKeyStr == NULL))) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!HcfIsClassMatch((HcfObjectBase *)self, GetDsaKeyGeneratorSpiClass())) { + LOGE("Class not match."); + return HCF_INVALID_PARAMS; + } + + HcfOpensslDsaPubKey *pubKey = NULL; + HcfOpensslDsaPriKey *priKey = NULL; + + HcfResult ret = ConvertDsaPemPubAndPriKey(pubKeyStr, priKeyStr, &pubKey, &priKey); + if (ret != HCF_SUCCESS) { + return ret; + } + + ret = CreateDsaKeyPair(pubKey, priKey, returnKeyPair); + if (ret != HCF_SUCCESS) { + HcfObjDestroy(pubKey); + HcfObjDestroy(priKey); + } + + return ret; +} + static HcfResult EngineGenerateDsaKeyPairBySpec(const HcfAsyKeyGeneratorSpi *self, const HcfAsyKeyParamsSpec *paramsSpec, HcfKeyPair **returnKeyPair) { - if ((self == NULL) || (paramsSpec == NULL) || (returnKeyPair == NULL)) { + if ((self == NULL) || (paramsSpec == NULL) || (paramsSpec->algName == NULL) || (returnKeyPair == NULL)) { LOGE("Invalid input parameter."); return HCF_INVALID_PARAMS; } @@ -929,7 +1033,7 @@ static HcfResult EngineGenerateDsaKeyPairBySpec(const HcfAsyKeyGeneratorSpi *sel static HcfResult EngineGenerateDsaPubKeyBySpec(const HcfAsyKeyGeneratorSpi *self, const HcfAsyKeyParamsSpec *paramsSpec, HcfPubKey **returnPubKey) { - if ((self == NULL) || (paramsSpec == NULL) || (returnPubKey == NULL)) { + if ((self == NULL) || (paramsSpec == NULL) || (paramsSpec->algName == NULL) || (returnPubKey == NULL)) { LOGE("Invalid input parameter."); return HCF_INVALID_PARAMS; } @@ -954,7 +1058,7 @@ static HcfResult EngineGenerateDsaPubKeyBySpec(const HcfAsyKeyGeneratorSpi *self static HcfResult EngineGenerateDsaPriKeyBySpec(const HcfAsyKeyGeneratorSpi *self, const HcfAsyKeyParamsSpec *paramsSpec, HcfPriKey **returnPriKey) { - if ((self == NULL) || (paramsSpec == NULL) || (returnPriKey == NULL)) { + if ((self == NULL) || (paramsSpec == NULL) || (paramsSpec->algName == NULL) || (returnPriKey == NULL)) { LOGE("Invalid input parameter."); return HCF_INVALID_PARAMS; } @@ -976,9 +1080,9 @@ static HcfResult EngineGenerateDsaPriKeyBySpec(const HcfAsyKeyGeneratorSpi *self return ret; } -HcfResult HcfAsyKeyGeneratorSpiDsaCreate(HcfAsyKeyGenParams *params, HcfAsyKeyGeneratorSpi **returnSpi) +HcfResult HcfAsyKeyGeneratorSpiDsaCreate(HcfAsyKeyGenParams *params, HcfAsyKeyGeneratorSpi **returnObj) { - if (params == NULL || returnSpi == NULL) { + if (params == NULL || returnObj == NULL) { LOGE("Invalid input parameter."); return HCF_INVALID_PARAMS; } @@ -993,10 +1097,11 @@ HcfResult HcfAsyKeyGeneratorSpiDsaCreate(HcfAsyKeyGenParams *params, HcfAsyKeyGe impl->base.base.destroy = DestroyDsaKeyGeneratorSpiImpl; impl->base.engineGenerateKeyPair = EngineGenerateDsaKeyPair; impl->base.engineConvertKey = EngineConvertDsaKey; + impl->base.engineConvertPemKey = EngineConvertDsaPemKey; impl->base.engineGenerateKeyPairBySpec = EngineGenerateDsaKeyPairBySpec; impl->base.engineGeneratePubKeyBySpec = EngineGenerateDsaPubKeyBySpec; impl->base.engineGeneratePriKeyBySpec = EngineGenerateDsaPriKeyBySpec; - *returnSpi = (HcfAsyKeyGeneratorSpi *)impl; + *returnObj = (HcfAsyKeyGeneratorSpi *)impl; return HCF_SUCCESS; } diff --git a/plugin/openssl_plugin/key/asy_key_generator/src/ecc_asy_key_generator_openssl.c b/plugin/openssl_plugin/key/asy_key_generator/src/ecc_asy_key_generator_openssl.c index 4939a42d4055760142fbca22b5022895cb707ada..3289032afdddfd14ea61680a1a61c18f29c8d02f 100644 --- a/plugin/openssl_plugin/key/asy_key_generator/src/ecc_asy_key_generator_openssl.c +++ b/plugin/openssl_plugin/key/asy_key_generator/src/ecc_asy_key_generator_openssl.c @@ -1066,8 +1066,7 @@ static OSSL_PARAM *ConvertHcfBlobToOsslParams(const char *groupName, HcfBlob *po OpensslOsslParamBldFree(paramBld); return NULL; } - if (OpensslOsslParamBldPushOctetString(paramBld, "pub", pointBlob->data, pointBlob->len) - != HCF_OPENSSL_SUCCESS) { + if (OpensslOsslParamBldPushOctetString(paramBld, "pub", pointBlob->data, pointBlob->len) != HCF_OPENSSL_SUCCESS) { LOGE("Invalid pointBlob parameter."); OpensslOsslParamBldFree(paramBld); return NULL; @@ -1133,6 +1132,10 @@ static EC_KEY *ConvertOsslParamsToEccPubKey(const char *groupName, int32_t curve static HcfResult GetCompressedEccPointEncoded(HcfOpensslEccPubKey *impl, HcfBlob *returnBlob) { EC_KEY *ecKey = impl->ecKey; + if (ecKey == NULL) { + LOGE("EcKey is NULL."); + return HCF_INVALID_PARAMS; + } const EC_GROUP *group = OpensslEcKeyGet0Group(ecKey); if (group == NULL) { LOGE("Failed to get group."); @@ -1473,7 +1476,7 @@ static HcfResult GetEcKeySpecBigInteger(const HcfKey *self, const AsyKeySpecItem LOGE("Invalid input parameter."); return HCF_INVALID_PARAMS; } - bool isPrivate; + bool isPrivate = false; HcfResult res = CheckEcKeySelf(self, &isPrivate); if (res != HCF_SUCCESS) { LOGE("Invalid input key"); @@ -1517,7 +1520,7 @@ static HcfResult GetEcKeySpecString(const HcfKey *self, const AsyKeySpecItem ite LOGE("Invalid input parameter."); return HCF_INVALID_PARAMS; } - bool isPrivate; + bool isPrivate = false; HcfResult res = CheckEcKeySelf(self, &isPrivate); if (res != HCF_SUCCESS) { LOGE("Invalid input key"); @@ -1545,7 +1548,7 @@ static HcfResult GetEcKeySpecInt(const HcfKey *self, const AsyKeySpecItem item, LOGE("Invalid input parameter."); return HCF_INVALID_PARAMS; } - bool isPrivate; + bool isPrivate = false; HcfResult res = CheckEcKeySelf(self, &isPrivate); if (res != HCF_SUCCESS) { LOGE("Invalid input key"); @@ -1723,7 +1726,7 @@ static HcfResult ConvertEcPubKey(int32_t curveId, HcfBlob *pubKeyBlob, HcfOpenss OpensslEcKeyFree(ecKey); return res; } - return HCF_SUCCESS; + return HCF_SUCCESS; } static HcfResult ConvertPriFromEncoded(EC_KEY **eckey, HcfBlob *priKeyBlob) @@ -1816,6 +1819,106 @@ static HcfResult EngineConvertEccKey(HcfAsyKeyGeneratorSpi *self, HcfParamsSpec return HCF_SUCCESS; } +static HcfResult ConvertEcPemPubKey(int32_t curveId, const char *pubKeyStr, HcfOpensslEccPubKey **returnPubKey) +{ + EVP_PKEY *pkey = NULL; + const char *keyType = "EC"; + HcfResult ret = ConvertPubPemStrToKey(&pkey, keyType, EVP_PKEY_PUBLIC_KEY, pubKeyStr); + if (ret != HCF_SUCCESS) { + LOGE("Convert ecc pem public key failed."); + return ret; + } + + EC_KEY *ecKey = OpensslEvpPkeyGet1EcKey(pkey); + OpensslEvpPkeyFree(pkey); + if (ecKey == NULL) { + LOGE("Pkey to ec key failed."); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + + HcfResult res = PackEccPubKey(curveId, ecKey, g_eccGenerateFieldType, returnPubKey); + if (res != HCF_SUCCESS) { + LOGE("Pack ec public key failed."); + OpensslEcKeyFree(ecKey); + return res; + } + + return HCF_SUCCESS; +} + +static HcfResult ConvertEcPemPriKey(int32_t curveId, const char *priKeyStr, HcfOpensslEccPriKey **returnPriKey) +{ + EVP_PKEY *pkey = NULL; + const char *keyType = "EC"; + HcfResult ret = ConvertPriPemStrToKey(priKeyStr, &pkey, keyType); + if (ret != HCF_SUCCESS) { + LOGE("Convert ecc pem private key failed."); + return ret; + } + + EC_KEY *ecKey = OpensslEvpPkeyGet1EcKey(pkey); + OpensslEvpPkeyFree(pkey); + if (ecKey == NULL) { + LOGE("Pkey to ec key failed."); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + + ret = PackEccPriKey(curveId, ecKey, g_eccGenerateFieldType, returnPriKey); + if (ret != HCF_SUCCESS) { + LOGE("Pack ec private key failed."); + OpensslEcKeyFree(ecKey); + return ret; + } + + return HCF_SUCCESS; +} + +static HcfResult EngineConvertEccPemKey(HcfAsyKeyGeneratorSpi *self, HcfParamsSpec *params, const char *pubKeyStr, + const char *priKeyStr, HcfKeyPair **returnKeyPair) +{ + (void)params; + if ((self == NULL) || (returnKeyPair == NULL) || ((pubKeyStr == NULL) && (priKeyStr == NULL))) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!HcfIsClassMatch((HcfObjectBase *)self, GetEccKeyPairGeneratorClass())) { + return HCF_INVALID_PARAMS; + } + + HcfAsyKeyGeneratorSpiOpensslEccImpl *impl = (HcfAsyKeyGeneratorSpiOpensslEccImpl *)self; + HcfResult res = HCF_SUCCESS; + HcfOpensslEccPubKey *pubKey = NULL; + HcfOpensslEccPriKey *priKey = NULL; + HcfOpensslEccKeyPair *keyPair = NULL; + + do { + if (pubKeyStr != NULL && strlen(pubKeyStr) != 0) { + res = ConvertEcPemPubKey(impl->curveId, pubKeyStr, &pubKey); + if (res != HCF_SUCCESS) { + break; + } + } + if (priKeyStr != NULL && strlen(priKeyStr) != 0) { + res = ConvertEcPemPriKey(impl->curveId, priKeyStr, &priKey); + if (res != HCF_SUCCESS) { + break; + } + } + res = PackEccKeyPair(pubKey, priKey, &keyPair); + } while (0); + if (res != HCF_SUCCESS) { + LOGE("Convert ec keyPair failed."); + HcfObjDestroy(pubKey); + HcfObjDestroy(priKey); + return res; + } + + *returnKeyPair = (HcfKeyPair *)keyPair; + return HCF_SUCCESS; +} + static HcfResult PackAndAssignPubKey(const HcfAsyKeyGeneratorSpiOpensslEccImpl *impl, const char *fieldType, EC_KEY *ecKey, HcfPubKey **returnObj) { @@ -1912,7 +2015,8 @@ static HcfResult EngineGenerateKeyPair(HcfAsyKeyGeneratorSpi *self, HcfKeyPair * static HcfResult EngineGenerateKeyPairBySpec(const HcfAsyKeyGeneratorSpi *self, const HcfAsyKeyParamsSpec *params, HcfKeyPair **returnKeyPair) { - if ((self == NULL) || (returnKeyPair == NULL)) { + if ((self == NULL) || (returnKeyPair == NULL) || (params == NULL) || + (((HcfEccCommParamsSpec *)params)->field == NULL)) { LOGE("Invalid input parameter."); return HCF_INVALID_PARAMS; } @@ -1947,7 +2051,8 @@ static HcfResult EngineGenerateKeyPairBySpec(const HcfAsyKeyGeneratorSpi *self, static HcfResult EngineGeneratePubKeyBySpec(const HcfAsyKeyGeneratorSpi *self, const HcfAsyKeyParamsSpec *params, HcfPubKey **returnPubKey) { - if ((self == NULL) || (returnPubKey == NULL)) { + if ((self == NULL) || (returnPubKey == NULL) || (params == NULL) || + (((HcfEccCommParamsSpec *)params)->field == NULL)) { LOGE("Invalid input parameter."); return HCF_INVALID_PARAMS; } @@ -1979,7 +2084,8 @@ static HcfResult EngineGeneratePubKeyBySpec(const HcfAsyKeyGeneratorSpi *self, c static HcfResult EngineGeneratePriKeyBySpec(const HcfAsyKeyGeneratorSpi *self, const HcfAsyKeyParamsSpec *params, HcfPriKey **returnPriKey) { - if ((self == NULL) || (returnPriKey == NULL)) { + if ((self == NULL) || (returnPriKey == NULL) || (params == NULL) || + (((HcfEccCommParamsSpec *)params)->field == NULL)) { LOGE("Invalid input parameter."); return HCF_INVALID_PARAMS; } @@ -2032,6 +2138,7 @@ HcfResult HcfAsyKeyGeneratorSpiEccCreate(HcfAsyKeyGenParams *params, HcfAsyKeyGe returnImpl->base.base.getClass = GetEccKeyPairGeneratorClass; returnImpl->base.base.destroy = DestroyEccKeyPairGenerator; returnImpl->base.engineConvertKey = EngineConvertEccKey; + returnImpl->base.engineConvertPemKey = EngineConvertEccPemKey; returnImpl->base.engineGenerateKeyPair = EngineGenerateKeyPair; returnImpl->base.engineGenerateKeyPairBySpec = EngineGenerateKeyPairBySpec; returnImpl->base.engineGeneratePubKeyBySpec = EngineGeneratePubKeyBySpec; diff --git a/plugin/openssl_plugin/key/asy_key_generator/src/ecc_common_param_spec_generator_openssl.c b/plugin/openssl_plugin/key/asy_key_generator/src/ecc_common_param_spec_generator_openssl.c index 8630d23cd693218ca2b5b987a4123e95df8f0719..97df1ddd45687ce328a76c3997a147eee713b420 100644 --- a/plugin/openssl_plugin/key/asy_key_generator/src/ecc_common_param_spec_generator_openssl.c +++ b/plugin/openssl_plugin/key/asy_key_generator/src/ecc_common_param_spec_generator_openssl.c @@ -216,6 +216,9 @@ static void FreeEccCommParamObject(HcfEccCommParamsSpecSpi *spec) HcfFree(spec->paramsSpec.base.algName); spec->paramsSpec.base.algName = NULL; if (spec->paramsSpec.field != NULL) { + HcfECFieldFp *tmp = (HcfECFieldFp *)spec->paramsSpec.field; + HcfFree(tmp->p.data); + tmp->p.data = NULL; HcfFree(spec->paramsSpec.field->fieldType); spec->paramsSpec.field->fieldType = NULL; HcfFree(spec->paramsSpec.field); @@ -298,25 +301,29 @@ static HcfResult InitEccPoint(const int32_t curveNameValue, EC_GROUP **ecGroup, *ecGroup = NULL; return HCF_ERR_CRYPTO_OPERATION; } - *x = OpensslBnNew(); - if (*x == NULL) { - LOGE("Failed to allocate memory for BIGNUM x."); - OpensslEcGroupFree(*ecGroup); - *ecGroup = NULL; - OpensslEcPointFree(*ecPoint); - *ecPoint = NULL; - return HCF_ERR_CRYPTO_OPERATION; + if (x != NULL) { + *x = OpensslBnNew(); + if (*x == NULL) { + LOGE("Failed to allocate memory for BIGNUM x."); + OpensslEcGroupFree(*ecGroup); + *ecGroup = NULL; + OpensslEcPointFree(*ecPoint); + *ecPoint = NULL; + return HCF_ERR_CRYPTO_OPERATION; + } } - *y = OpensslBnNew(); - if (*y == NULL) { - LOGE("Failed to allocate memory for BIGNUM y."); - OpensslBnFree(*x); - *x = NULL; - OpensslEcGroupFree(*ecGroup); - *ecGroup = NULL; - OpensslEcPointFree(*ecPoint); - *ecPoint = NULL; - return HCF_ERR_CRYPTO_OPERATION; + if (y != NULL) { + *y = OpensslBnNew(); + if (*y == NULL) { + LOGE("Failed to allocate memory for BIGNUM y."); + OpensslBnFree(*x); + *x = NULL; + OpensslEcGroupFree(*ecGroup); + *ecGroup = NULL; + OpensslEcPointFree(*ecPoint); + *ecPoint = NULL; + return HCF_ERR_CRYPTO_OPERATION; + } } return HCF_SUCCESS; } @@ -436,7 +443,7 @@ HcfResult HcfEngineGetEncodedPoint(const int32_t curveNameValue, HcfPoint *point BIGNUM *bnY = NULL; HcfResult ret = HCF_SUCCESS; do { - ret = InitEccPoint(curveNameValue, &ecGroup, &ecPoint, &bnX, &bnY); + ret = InitEccPoint(curveNameValue, &ecGroup, &ecPoint, NULL, NULL); if (ret != HCF_SUCCESS) { LOGE("Failed to get EccPoint."); break; diff --git a/plugin/openssl_plugin/key/asy_key_generator/src/rsa_asy_key_generator_openssl.c b/plugin/openssl_plugin/key/asy_key_generator/src/rsa_asy_key_generator_openssl.c index 4ad98a26631e7fd07086cde964bc5a18a3089fd1..fc31e1d470aae18c3bd8a603cf85e16945ff8426 100644 --- a/plugin/openssl_plugin/key/asy_key_generator/src/rsa_asy_key_generator_openssl.c +++ b/plugin/openssl_plugin/key/asy_key_generator/src/rsa_asy_key_generator_openssl.c @@ -37,6 +37,10 @@ #define OPENSSL_RSA_KEYGEN_DEFAULT_PRIMES 2 #define MAX_KEY_SIZE 8192 #define MIN_KEY_SIZE 512 +#define PRIMES_2 2 +#define PRIMES_3 3 +#define PRIMES_4 4 +#define PRIMES_5 5 enum OpensslRsaKeySize { OPENSSL_RSA_KEY_SIZE_BY_SPEC = 0, @@ -353,6 +357,7 @@ static HcfResult CopyStrFromBIO(BIO *bio, char **returnString) LOGE("Bio read fail"); HcfPrintOpensslError(); HcfFree(*returnString); + *returnString = NULL; return HCF_ERR_CRYPTO_OPERATION; } return HCF_SUCCESS; @@ -874,6 +879,23 @@ ERR2: return ret; } +static int32_t GetRealPrimes(int32_t primesFlag) +{ + switch (primesFlag) { + case OPENSSL_RSA_PRIMES_SIZE_2: + return PRIMES_2; + case OPENSSL_RSA_PRIMES_SIZE_3: + return PRIMES_3; + case OPENSSL_RSA_PRIMES_SIZE_4: + return PRIMES_4; + case OPENSSL_RSA_PRIMES_SIZE_5: + return PRIMES_5; + default: + LOGD("set default primes 2"); + return PRIMES_2; + } +} + static HcfResult GenerateKeyPair(HcfAsyKeyGenSpiRsaParams *params, HcfKeyPair **keyPair) { // check input params is valid @@ -1337,7 +1359,7 @@ static HcfResult GeneratePriKeyBySpec(const HcfAsyKeyParamsSpec *paramsSpec, Hcf static HcfResult EngineGenerateKeyPairBySpec(const HcfAsyKeyGeneratorSpi *self, const HcfAsyKeyParamsSpec *paramsSpec, HcfKeyPair **returnKeyPair) { - if ((self == NULL) || (returnKeyPair == NULL) || (paramsSpec == NULL)) { + if ((self == NULL) || (returnKeyPair == NULL) || (paramsSpec == NULL) || (paramsSpec->algName == NULL)) { LOGE("GenerateKeyPairBySpec Params is invalid."); return HCF_INVALID_PARAMS; } @@ -1359,7 +1381,7 @@ static HcfResult EngineGenerateKeyPairBySpec(const HcfAsyKeyGeneratorSpi *self, static HcfResult EngineGeneratePubKeyBySpec(const HcfAsyKeyGeneratorSpi *self, const HcfAsyKeyParamsSpec *paramsSpec, HcfPubKey **returnPubKey) { - if ((self == NULL) || (returnPubKey == NULL) || (paramsSpec == NULL)) { + if ((self == NULL) || (returnPubKey == NULL) || (paramsSpec == NULL) || (paramsSpec->algName == NULL)) { LOGE("GeneratePubKeyBySpec Params is invalid."); return HCF_INVALID_PARAMS; } @@ -1381,7 +1403,7 @@ static HcfResult EngineGeneratePubKeyBySpec(const HcfAsyKeyGeneratorSpi *self, static HcfResult EngineGeneratePriKeyBySpec(const HcfAsyKeyGeneratorSpi *self, const HcfAsyKeyParamsSpec *paramsSpec, HcfPriKey **returnPriKey) { - if ((self == NULL) || (returnPriKey == NULL) || (paramsSpec == NULL)) { + if ((self == NULL) || (returnPriKey == NULL) || (paramsSpec == NULL) || (paramsSpec->algName == NULL)) { LOGE("GeneratePriKeyBySpec Params is invalid."); return HCF_INVALID_PARAMS; } @@ -1444,6 +1466,7 @@ static HcfResult DecodeParams(HcfAsyKeyGenParams *from, HcfAsyKeyGenSpiRsaParams } if (CheckRsaKeyGenParams(*to) != HCF_SUCCESS) { LOGE("Invalid keyGen params"); + OpensslBnFree((*to)->pubExp); HcfFree(*to); *to = NULL; return HCF_INVALID_PARAMS; diff --git a/plugin/openssl_plugin/key/asy_key_generator/src/sm2_asy_key_generator_openssl.c b/plugin/openssl_plugin/key/asy_key_generator/src/sm2_asy_key_generator_openssl.c index 675c893184e219592aef08bf7d42c7f006bfcb62..0129be4836939488d0be6408eed36ab3a37922d3 100644 --- a/plugin/openssl_plugin/key/asy_key_generator/src/sm2_asy_key_generator_openssl.c +++ b/plugin/openssl_plugin/key/asy_key_generator/src/sm2_asy_key_generator_openssl.c @@ -27,6 +27,9 @@ #define OPENSSL_SM2_ALGORITHM "SM2" #define OPENSSL_SM2_PUB_KEY_FORMAT "X.509" #define OPENSSL_SM2_PRI_KEY_FORMAT "PKCS#8" + +#define SM2_OCTET_STRING_LEN 65 // strlen(0x04) + strlen(X) + strlen(Y): 1 + 32 + 32 + static const char *const g_sm2GenerateFieldType = "Fp"; typedef struct { @@ -565,11 +568,7 @@ static HcfResult GetCurveName(const HcfKey *self, bool isPriavte, char **returnS LOGE("Allocate returnString memory failed."); return HCF_ERR_MALLOC; } - if (memcpy_s(*returnString, len, curveIdStr, len) != EOK) { - LOGE("Memcpy returnString failed."); - HcfFree(*returnString); - return HCF_ERR_MALLOC; - } + (void)memcpy_s(*returnString, len, curveIdStr, len); return HCF_SUCCESS; } @@ -597,7 +596,7 @@ static HcfResult GetSm2KeySpecBigInteger(const HcfKey *self, const AsyKeySpecIte LOGE("Invalid input parameter."); return HCF_INVALID_PARAMS; } - bool isPrivate; + bool isPrivate = false; HcfResult ret = CheckSm2KeySelf(self, &isPrivate); if (ret != HCF_SUCCESS) { LOGE("Invalid input key"); @@ -645,7 +644,7 @@ static HcfResult GetSm2KeySpecString(const HcfKey *self, const AsyKeySpecItem it LOGE("Invalid input parameter."); return HCF_INVALID_PARAMS; } - bool isPrivate; + bool isPrivate = false; HcfResult ret = CheckSm2KeySelf(self, &isPrivate); if (ret != HCF_SUCCESS) { LOGE("Invalid input key"); @@ -673,7 +672,7 @@ static HcfResult GetSm2KeySpecInt(const HcfKey *self, const AsyKeySpecItem item, LOGE("Invalid input parameter."); return HCF_INVALID_PARAMS; } - bool isPrivate; + bool isPrivate = false; HcfResult ret = CheckSm2KeySelf(self, &isPrivate); if (ret != HCF_SUCCESS) { LOGE("Invalid input key"); @@ -944,6 +943,191 @@ static HcfResult EngineConvertSm2Key(HcfAsyKeyGeneratorSpi *self, HcfParamsSpec return HCF_SUCCESS; } +static EC_KEY *GetSm2EckeyformPubKey(const EVP_PKEY *pkey) +{ + EC_KEY *ecKey = NULL; + const EC_GROUP *group = NULL; + EC_POINT *pubPoint = NULL; + unsigned char octetKey[SM2_OCTET_STRING_LEN]; + size_t octetKeyLen = 0; + + ecKey = OpensslEcKeyNewbyCurveNameEx(NULL, NULL, NID_sm2); + if (ecKey == NULL) { + LOGE("Failed to init ec key."); + return NULL; + } + + group = OpensslEcKeyGet0Group(ecKey); + if (group == NULL) { + LOGE("Failed to get group while get ec key."); + OpensslEcKeyFree(ecKey); + return NULL; + } + + pubPoint = OpensslEcPointNew(group); + if (pubPoint == NULL) { + LOGE("Failed to init ec point while get ec key."); + OpensslEcKeyFree(ecKey); + return NULL; + } + + if (!OpensslEvpPkeyGetOctetStringParam(pkey, OSSL_PKEY_PARAM_PUB_KEY, octetKey, sizeof(octetKey), + &octetKeyLen)) { + LOGE("Failed to get octet string param while get ec key."); + OpensslEcKeyFree(ecKey); + OpensslEcPointFree(pubPoint); + return NULL; + } + + if (!OpensslEcOct2Point(group, pubPoint, octetKey, octetKeyLen, NULL)) { + LOGE("Failed to convert oct to point while get ec key."); + OpensslEcKeyFree(ecKey); + OpensslEcPointFree(pubPoint); + return NULL; + } + + OpensslEcKeySetFlags(ecKey, EC_FLAG_SM2_RANGE); + if (!OpensslEcKeySetPublicKey(ecKey, pubPoint)) { + LOGE("Failed to set public key while get ec key."); + OpensslEcKeyFree(ecKey); + OpensslEcPointFree(pubPoint); + return NULL; + } + OpensslEcPointFree(pubPoint); + + return ecKey; +} + +static EC_KEY *GetSm2EckeyformPriKey(const EVP_PKEY *pkey) +{ + EC_KEY *ecKey = NULL; + BIGNUM *outPriv = NULL; + + ecKey = OpensslEcKeyNewbyCurveNameEx(NULL, NULL, NID_sm2); + if (ecKey == NULL) { + LOGE("Failed to init ec key."); + return NULL; + } + + if (OpensslEvpPkeyGetBnParam(pkey, OSSL_PKEY_PARAM_PRIV_KEY, &outPriv) != HCF_OPENSSL_SUCCESS) { + LOGE("Failed to get bn param while get ec key."); + OpensslEcKeyFree(ecKey); + return NULL; + } + + OpensslEcKeySetFlags(ecKey, EC_FLAG_SM2_RANGE); + if (OpensslEcKeySetPrivateKey(ecKey, outPriv) != HCF_OPENSSL_SUCCESS) { + LOGE("Failed to set private key while get ec key."); + OpensslEcKeyFree(ecKey); + OpensslBnClearFree(outPriv); + return NULL; + } + OpensslBnClearFree(outPriv); + + return ecKey; +} + +static HcfResult ConvertSM2PemPubKey(int32_t curveId, const char *pubKeyStr, HcfOpensslSm2PubKey **returnPubKey) +{ + EVP_PKEY *pkey = NULL; + const char *keyType = "SM2"; + HcfResult ret = ConvertPubPemStrToKey(&pkey, keyType, EVP_PKEY_PUBLIC_KEY, pubKeyStr); + if (ret != HCF_SUCCESS) { + LOGE("Convert sm2 pem public key failed."); + return ret; + } + + EC_KEY *ecKey = GetSm2EckeyformPubKey(pkey); + OpensslEvpPkeyFree(pkey); + if (ecKey == NULL) { + LOGE("Get sm2 ec pkey fail."); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + + ret = PackSm2PubKey(curveId, ecKey, g_sm2GenerateFieldType, returnPubKey); + if (ret != HCF_SUCCESS) { + LOGE("Create sm2 public key failed."); + OpensslEcKeyFree(ecKey); + return ret; + } + + return HCF_SUCCESS; +} + +static HcfResult ConvertSM2PemPriKey(int32_t curveId, const char *priKeyStr, HcfOpensslSm2PriKey **returnPriKey) +{ + EVP_PKEY *pkey = NULL; + const char *keyType = "SM2"; + HcfResult ret = ConvertPriPemStrToKey(priKeyStr, &pkey, keyType); + if (ret != HCF_SUCCESS) { + LOGE("Convert sm2 pem private key failed."); + return ret; + } + + EC_KEY *ecKey = GetSm2EckeyformPriKey(pkey); + OpensslEvpPkeyFree(pkey); + if (ecKey == NULL) { + LOGE("Get sm2 ec pkey fail."); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + + ret = PackSm2PriKey(curveId, ecKey, g_sm2GenerateFieldType, returnPriKey); + if (ret != HCF_SUCCESS) { + LOGE("Create sm2 private key failed."); + OpensslEcKeyFree(ecKey); + return ret; + } + + return HCF_SUCCESS; +} + +static HcfResult EngineConvertSm2PemKey(HcfAsyKeyGeneratorSpi *self, HcfParamsSpec *params, const char *pubKeyStr, + const char *priKeyStr, HcfKeyPair **returnKeyPair) +{ + (void)params; + if ((self == NULL) || (returnKeyPair == NULL) || ((pubKeyStr == NULL) && (priKeyStr == NULL))) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!HcfIsClassMatch((HcfObjectBase *)self, self->base.getClass())) { + LOGE("Class not match."); + return HCF_INVALID_PARAMS; + } + + HcfAsyKeyGeneratorSpiOpensslSm2Impl *impl = (HcfAsyKeyGeneratorSpiOpensslSm2Impl *)self; + HcfResult ret = HCF_SUCCESS; + HcfOpensslSm2PubKey *pubKey = NULL; + HcfOpensslSm2PriKey *priKey = NULL; + HcfOpensslSm2KeyPair *keyPair = NULL; + + do { + if (pubKeyStr != NULL && strlen(pubKeyStr) != 0) { + ret = ConvertSM2PemPubKey(impl->curveId, pubKeyStr, &pubKey); + if (ret != HCF_SUCCESS) { + break; + } + } + if (priKeyStr != NULL && strlen(priKeyStr) != 0) { + ret = ConvertSM2PemPriKey(impl->curveId, priKeyStr, &priKey); + if (ret != HCF_SUCCESS) { + break; + } + } + ret = PackSm2KeyPair(pubKey, priKey, &keyPair); + } while (0); + if (ret != HCF_SUCCESS) { + LOGE("Convert sm2 keyPair failed."); + HcfObjDestroy(pubKey); + HcfObjDestroy(priKey); + return ret; + } + + *returnKeyPair = (HcfKeyPair *)keyPair; + return HCF_SUCCESS; +} + static HcfResult PackAndAssignPubKey(const HcfAsyKeyGeneratorSpiOpensslSm2Impl *impl, const char *fieldType, EC_KEY *ecKey, HcfPubKey **returnObj) { @@ -1038,7 +1222,8 @@ static HcfResult EngineGenerateKeyPair(HcfAsyKeyGeneratorSpi *self, HcfKeyPair * static HcfResult EngineGenerateKeyPairBySpec(const HcfAsyKeyGeneratorSpi *self, const HcfAsyKeyParamsSpec *params, HcfKeyPair **returnKeyPair) { - if ((self == NULL) || (returnKeyPair == NULL)) { + if ((self == NULL) || (returnKeyPair == NULL) || (params == NULL) || + (((HcfEccCommParamsSpec *)params)->field == NULL)) { LOGE("Invalid input parameter."); return HCF_INVALID_PARAMS; } @@ -1073,7 +1258,8 @@ static HcfResult EngineGenerateKeyPairBySpec(const HcfAsyKeyGeneratorSpi *self, static HcfResult EngineGeneratePubKeyBySpec(const HcfAsyKeyGeneratorSpi *self, const HcfAsyKeyParamsSpec *params, HcfPubKey **returnPubKey) { - if ((self == NULL) || (returnPubKey == NULL)) { + if ((self == NULL) || (returnPubKey == NULL) || (params == NULL) || + (((HcfEccCommParamsSpec *)params)->field == NULL)) { LOGE("Invalid input parameter."); return HCF_INVALID_PARAMS; } @@ -1105,7 +1291,8 @@ static HcfResult EngineGeneratePubKeyBySpec(const HcfAsyKeyGeneratorSpi *self, c static HcfResult EngineGeneratePriKeyBySpec(const HcfAsyKeyGeneratorSpi *self, const HcfAsyKeyParamsSpec *params, HcfPriKey **returnPriKey) { - if ((self == NULL) || (returnPriKey == NULL)) { + if ((self == NULL) || (returnPriKey == NULL) || (params == NULL) || + (((HcfEccCommParamsSpec *)params)->field == NULL)) { LOGE("Invalid input parameter."); return HCF_INVALID_PARAMS; } @@ -1159,6 +1346,7 @@ HcfResult HcfAsyKeyGeneratorSpiSm2Create(HcfAsyKeyGenParams *params, HcfAsyKeyGe returnImpl->base.base.getClass = GetSm2KeyPairGeneratorClass; returnImpl->base.base.destroy = DestroySm2KeyPairGenerator; returnImpl->base.engineConvertKey = EngineConvertSm2Key; + returnImpl->base.engineConvertPemKey = EngineConvertSm2PemKey; returnImpl->base.engineGenerateKeyPair = EngineGenerateKeyPair; returnImpl->base.engineGenerateKeyPairBySpec = EngineGenerateKeyPairBySpec; returnImpl->base.engineGeneratePubKeyBySpec = EngineGeneratePubKeyBySpec; diff --git a/plugin/plugin.gni b/plugin/plugin.gni index 8a18e7fd4724e4e49bcaff0b76e6d8eb1333c900..2d7f0d17c7455f74f1af557df4211b3592dee626 100644 --- a/plugin/plugin.gni +++ b/plugin/plugin.gni @@ -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", +] diff --git a/test/fuzztest/crypto_operation/hcfciphercreate_fuzzer/hcfciphercreate_fuzzer.cpp b/test/fuzztest/crypto_operation/hcfciphercreate_fuzzer/hcfciphercreate_fuzzer.cpp index 7b37ad47e28e351e0a4fe7a812fa6e856c26f5dc..85dc0afdcb38bdf86afa2172b3480872fe53a0a8 100755 --- a/test/fuzztest/crypto_operation/hcfciphercreate_fuzzer/hcfciphercreate_fuzzer.cpp +++ b/test/fuzztest/crypto_operation/hcfciphercreate_fuzzer/hcfciphercreate_fuzzer.cpp @@ -70,6 +70,9 @@ namespace OHOS { uint8_t *cipherText, int cipherTextLen) { HcfBlob output = {}; + if (cipherTextLen <= 0) { + return -1; + } int32_t maxLen = cipherTextLen; int32_t ret = cipher->init(cipher, DECRYPT_MODE, &(key->key), nullptr); if (ret != 0) { @@ -149,6 +152,9 @@ namespace OHOS { uint8_t *cipherText, int cipherTextLen) { HcfBlob output = {}; + if (cipherTextLen <= 0) { + return -1; + } int32_t maxLen = cipherTextLen; int32_t ret = cipher->init(cipher, DECRYPT_MODE, reinterpret_cast(key), nullptr); if (ret != 0) { diff --git a/test/fuzztest/crypto_operation/hcfkeyagreementcreate_fuzzer/hcfkeyagreementcreate_fuzzer.cpp b/test/fuzztest/crypto_operation/hcfkeyagreementcreate_fuzzer/hcfkeyagreementcreate_fuzzer.cpp index bccfbdb32a117bdf9aa753ee8fe5a4b2ffbb4126..8a2128801e94a5e684e9feafb0638fc889a5bf23 100755 --- a/test/fuzztest/crypto_operation/hcfkeyagreementcreate_fuzzer/hcfkeyagreementcreate_fuzzer.cpp +++ b/test/fuzztest/crypto_operation/hcfkeyagreementcreate_fuzzer/hcfkeyagreementcreate_fuzzer.cpp @@ -26,6 +26,9 @@ namespace OHOS { bool HcfKeyAgreementCreateFuzzTest(const uint8_t* data, size_t size) { + if (data == nullptr || size == 0) { + return false; + } HcfKeyAgreement *keyAgreement = nullptr; std::string algoName(reinterpret_cast(data), size); int32_t res = HcfKeyAgreementCreate(algoName.c_str(), &keyAgreement); diff --git a/test/fuzztest/key/asykeygenerator_fuzzer/corpus/init b/test/fuzztest/key/asykeygenerator_fuzzer/corpus/init index 2be750d4aca6dd7dc15ec82d18aea969f3d8be30..f7603157aea7683340a32f2bd58bb845065c0503 100755 --- a/test/fuzztest/key/asykeygenerator_fuzzer/corpus/init +++ b/test/fuzztest/key/asykeygenerator_fuzzer/corpus/init @@ -11,4 +11,4 @@ # See the License for the specific language governing permissions and # limitations under the License. -FUZZ \ No newline at end of file +RSA1024 \ No newline at end of file diff --git a/test/fuzztest/key/ecckeyutil_fuzzer/corpus/init b/test/fuzztest/key/ecckeyutil_fuzzer/corpus/init index 23e26fe23c21191cfd3f9bd01be902390c4eeb2b..a2291efaa65d6a87903787e07baa9390c873bb28 100644 --- a/test/fuzztest/key/ecckeyutil_fuzzer/corpus/init +++ b/test/fuzztest/key/ecckeyutil_fuzzer/corpus/init @@ -11,4 +11,4 @@ # See the License for the specific language governing permissions and # limitations under the License. -FUZZ \ No newline at end of file +NID_brainpoolP160r1 \ No newline at end of file diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 9e6a971dbb2d50394d16b8854a9ea7c6a27c9106..dedf2d2086387df7e919e0917c1064ededcaa992 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -43,6 +43,7 @@ ohos_unittest("crypto_framework_test") { "src/aes_cipher/crypto_aes_gcm_cipher_test.cpp", "src/aes_cipher/crypto_aes_ofb_cipher_test.cpp", "src/crypto_3des_cipher_test.cpp", + "src/crypto_asy_key_convert_pem_test.cpp", "src/crypto_asy_key_generator_cov_test.cpp", "src/crypto_brainpool_asy_key_generator_test.cpp", "src/crypto_brainpool_key_agreement_test.cpp", diff --git a/test/unittest/src/crypto_asy_key_convert_pem_test.cpp b/test/unittest/src/crypto_asy_key_convert_pem_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2338d362740f7e97e075c3e5afb09059c0d32d07 --- /dev/null +++ b/test/unittest/src/crypto_asy_key_convert_pem_test.cpp @@ -0,0 +1,1084 @@ +/* + * 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 +#include "securec.h" + +#include "asy_key_generator.h" +#include "asy_key_generator_spi.h" +#include "blob.h" +#include "memory.h" +#include "params_parser.h" +#include "alg_25519_asy_key_generator_openssl.h" +#include "dh_asy_key_generator_openssl.h" +#include "dsa_asy_key_generator_openssl.h" +#include "ecc_asy_key_generator_openssl.h" +#include "sm2_asy_key_generator_openssl.h" + +using namespace std; +using namespace testing::ext; + +namespace { +class CryptoAsyKeyConvertPemTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void CryptoAsyKeyConvertPemTest::SetUpTestCase() {} +void CryptoAsyKeyConvertPemTest::TearDownTestCase() {} +void CryptoAsyKeyConvertPemTest::SetUp() {} +void CryptoAsyKeyConvertPemTest::TearDown() {} + +static string g_testSm2PriKey = "-----BEGIN PRIVATE KEY-----\n" + "MIGIAgEAMBQGCCqBHM9VAYItBggqgRzPVQGCLQRtMGsCAQEEIA200l6+4y/sASFH\n" + "W+v2ivubPvilyNPD5+iBSnyIb+pHoUQDQgAEylRVudZ35l9vBwX8Zeqq7m9cGTqo\n" + "Mc7m8Lmj107pifm2Qd7kKyYiBa1568t4yEPp5KLfPs1TGgiGoLIsvJeARA==\n" + "-----END PRIVATE KEY-----\n"; + +static string g_testSm2PubKey = "-----BEGIN PUBLIC KEY-----\n" + "MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEEDZi8UI/QxT70W8M3q3C7h+W+Zl6\n" + "8rP7SLCnZXYQPNKDqZEOPi/Vq0CRS9IS438yq4ZadxpDXothWk/bPYtOog==\n" + "-----END PUBLIC KEY-----\n"; + +static string g_testX25519PriKey = "-----BEGIN PRIVATE KEY-----\n" + "MC4CAQAwBQYDK2VuBCIEIDBcZrfXH+c4pAmTEFu9yoyCEIZSiGkfIZgFy2Ov58dh\n" + "-----END PRIVATE KEY-----\n"; + +static string g_testX25519PubKey = "-----BEGIN PUBLIC KEY-----\n" + "MCowBQYDK2VuAyEA2L8/1ZjPmQi2x46Rg3+H/BLwJvmbKocfaMeWr4IuMWg=\n" + "-----END PUBLIC KEY-----\n"; + +static string g_testEd25519PriKey = "-----BEGIN PRIVATE KEY-----\n" + "MC4CAQAwBQYDK2VwBCIEIGeiM+8OWg71i9eF6Z8PszWstvLW11eJJKKo9RyHyXkV\n" + "-----END PRIVATE KEY-----\n"; + +static string g_testEd25519PubKey = "-----BEGIN PUBLIC KEY-----\n" + "MCowBQYDK2VwAyEAPfx7zgwln/YVAT0oFLCp87qNS43QBSHJ0ttb0GImUNI=\n" + "-----END PUBLIC KEY-----\n"; + +static string g_testEccSecp224r1PriKey = "-----BEGIN PRIVATE KEY-----\n" + "MHgCAQAwEAYHKoZIzj0CAQYFK4EEACEEYTBfAgEBBByoNkUhCLcFLDPh3yAnFvx9\n" + "QRnVZJHMhTQnO1SXoTwDOgAEvc6xX46WjjwfIz+/VBVH49OCEVRrGaVGi65dTabd\n" + "UUTvtreiwA2lW2hS2EI3LaE3VvBROnOIYqU=\n" + "-----END PRIVATE KEY-----\n"; + +static string g_testEccSecp224r1PubKey = "-----BEGIN PUBLIC KEY-----\n" + "ME4wEAYHKoZIzj0CAQYFK4EEACEDOgAEvc6xX46WjjwfIz+/VBVH49OCEVRrGaVG\n" + "i65dTabdUUTvtreiwA2lW2hS2EI3LaE3VvBROnOIYqU=\n" + "-----END PUBLIC KEY-----\n"; + +static string g_testDsa1024Prikey = "-----BEGIN PRIVATE KEY-----\n" + "MIIBWgIBADCCATMGByqGSM44BAEwggEmAoGBAP2TzPnHnQkBvcT5LE3upXUv21Pg\n" + "bLgrPycAMjr88vVCixnL/EnAO5HIbqmLHoum9wShT9Lb4UnBDeOB3gF/JE9xyAJ0\n" + "ULNfWMykUr3/YudEHBi5C63gvhA80sLkB3udQxXoWdhrMDTC+JxAmOaoLJlXLOXm\n" + "KpP9RpdGIBLfXXu1Ah0AqNktdrld7vGDCD9/JXYmfDtipMde3LDwc0luhQKBgB0+\n" + "Sa/8d4t4KTJaBe7x3gb0SD2B9K/GoZbgS0a5nRpvwai4pqmEcU9dtwW6fwUFg4Eq\n" + "9Kj7cJZc2k6b8b0Dwt0c/iUE+VE7cVCCsO6nh5i+r0P2Upkx+DBR8ZuRrpxQqNjl\n" + "ES81GmQTKGtUqy3+EKXR08wcf3njBsE1hDq5nECeBB4CHHFSEVmDW3oGTmo4xStB\n" + "hdZIq5iPeBfIGIHFt0M=\n" + "-----END PRIVATE KEY-----\n"; + +static string g_testDsa1024Pubkey = "-----BEGIN PUBLIC KEY-----\n" + "MIIBvzCCATMGByqGSM44BAEwggEmAoGBAP2TzPnHnQkBvcT5LE3upXUv21PgbLgr\n" + "PycAMjr88vVCixnL/EnAO5HIbqmLHoum9wShT9Lb4UnBDeOB3gF/JE9xyAJ0ULNf\n" + "WMykUr3/YudEHBi5C63gvhA80sLkB3udQxXoWdhrMDTC+JxAmOaoLJlXLOXmKpP9\n" + "RpdGIBLfXXu1Ah0AqNktdrld7vGDCD9/JXYmfDtipMde3LDwc0luhQKBgB0+Sa/8\n" + "d4t4KTJaBe7x3gb0SD2B9K/GoZbgS0a5nRpvwai4pqmEcU9dtwW6fwUFg4Eq9Kj7\n" + "cJZc2k6b8b0Dwt0c/iUE+VE7cVCCsO6nh5i+r0P2Upkx+DBR8ZuRrpxQqNjlES81\n" + "GmQTKGtUqy3+EKXR08wcf3njBsE1hDq5nECeA4GFAAKBgQDDkKC11pEMGnF93lsH\n" + "61vLd7y2xvt6mKRw/AExsYgQBdOMJ+w2sSapEbRI/XUCX7Z4E0nN89xBl/PzbywO\n" + "0yfRqdLTwk5RSurQW7WglYPtMzR24dPCxa9woqyo5OTSCTx0FH2BQVsNdEloYQKo\n" + "6c4+rzj2DLaALOBrKEg9wTAmng==\n" + "-----END PUBLIC KEY-----\n"; + +static string g_testDhModp1536PriKey = "-----BEGIN PRIVATE KEY-----\n" + "MIH4AgEAMIHVBgkqhkiG9w0BAwEwgccCgcEA///////////JD9qiIWjCNMTGYouA\n" + "3BzRKQJOCIpnzHQCC76mOxObIlFKCHmONATd75UZs806QxswKwpt8l8UN0/hNW1t\n" + "UcJF5IW1dmJefsb0TELppjftawv/XLb0Brft7jhr+1qJn6WunyQRfEsf5kkoZlHs\n" + "5Fs9wgB8uKFjvwWY2kg2HFXTmmkWP6j9JM9fg2VdI9yjrZYcYvNWIIVSu57VKQdw\n" + "lpZtZww1Tkq8mATxdGwIyiNzJ///////////AgECBBsCGXIeKZHN2Qp5+JSnHAam\n" + "RiDePOsqbd2mae8=\n" + "-----END PRIVATE KEY-----\n"; + +static string g_testDhModp1536PubKey = "-----BEGIN PUBLIC KEY-----\n" + "MIIBoDCB1QYJKoZIhvcNAQMBMIHHAoHBAP//////////yQ/aoiFowjTExmKLgNwc\n" + "0SkCTgiKZ8x0Agu+pjsTmyJRSgh5jjQE3e+VGbPNOkMbMCsKbfJfFDdP4TVtbVHC\n" + "ReSFtXZiXn7G9ExC6aY37WsL/1y29Aa37e44a/taiZ+lrp8kEXxLH+ZJKGZR7ORb\n" + "PcIAfLihY78FmNpINhxV05ppFj+o/STPX4NlXSPco62WHGLzViCFUrue1SkHcJaW\n" + "bWcMNU5KvJgE8XRsCMojcyf//////////wIBAgOBxQACgcEAuj+cH1r8RNxBPAl7\n" + "CG76b50cbn1Rb04be/ONImxdhO9zEx/eUtnT1/3PR7j+7UNfvf6J7leQ5YorUz6F\n" + "5anKVUURi1XljLK6GcWBtqyCP0MMuO8FX5Dk8JBlCjTzuP5ClA0gofVAfcp3FYcq\n" + "VrSUDFn1SZt2MdkWe6zR4SDkFrlGTYa2EY5WKD5AR4piXi3m0PvPp+10oe3x6BOZ\n" + "RBvXAtLiP0nTUnhDX2N8FdyiU9Xn9QxajBRI1Jn85v/Qwa0o\n" + "-----END PUBLIC KEY-----\n"; + + +static string g_testDhFfdhe2048PriKey = "-----BEGIN PRIVATE KEY-----\n" + "MIIBPgIBADCCARcGCSqGSIb3DQEDATCCAQgCggEBAP//////////rfhUWKK7Spqv\n" + "3FYgJz088di5xYPOLTaVqeE2QRRkM/vMk53OJJs++X0v42NjDHXY9oGyAq7EYXrT\n" + "3x7V1f1lYSQz9R9fBm7QhWNlVT3tGvO1VxNef1fJNZhPDHDg5ot34qaJ2vPv6HId\n" + "8VihNq3nNTCsyk9IOnl6vAqxgrMk+2HRCKlLssjj+7lq2rdg1/RoHU9Co945TfSu\n" + "Vu3nY3K7GQsHp8juCm1wngL84c334uzANATNKDQvYZFy/pzphYP/jk8SMu7ygYPD\n" + "/jsbTG+tczu1/LwuwiAFxY7xg30Wg7LG80omwbLv+ohrQjhhKFyX//////////8C\n" + "AQIEHgIcC6C96/TJHrL6iOaoXiBKyamHP861V3XxMs3Fsw==\n" + "-----END PRIVATE KEY-----\n"; + +static string g_testDhFfdhe2048PubKey = "-----BEGIN PUBLIC KEY-----\n" + "MIICJTCCARcGCSqGSIb3DQEDATCCAQgCggEBAP//////////rfhUWKK7Spqv3FYg\n" + "Jz088di5xYPOLTaVqeE2QRRkM/vMk53OJJs++X0v42NjDHXY9oGyAq7EYXrT3x7V\n" + "1f1lYSQz9R9fBm7QhWNlVT3tGvO1VxNef1fJNZhPDHDg5ot34qaJ2vPv6HId8Vih\n" + "Nq3nNTCsyk9IOnl6vAqxgrMk+2HRCKlLssjj+7lq2rdg1/RoHU9Co945TfSuVu3n\n" + "Y3K7GQsHp8juCm1wngL84c334uzANATNKDQvYZFy/pzphYP/jk8SMu7ygYPD/jsb\n" + "TG+tczu1/LwuwiAFxY7xg30Wg7LG80omwbLv+ohrQjhhKFyX//////////8CAQID\n" + "ggEGAAKCAQEA99dycUYKbYBfecmzMQ+QnGDQ7IfF41i8GbEE6m6Lb27br7XFHxUB\n" + "xS85SOYQGUhup5FCyftzRdx2/zYHatdg51Mn+YxgB1OEa/gTxpRY1UC49bs+p/w6\n" + "Q8+ZRslDXnTRCGSeiw4TCzC0ynMN1i0TcTnOh33Vd8exKIg73jedgLi6//+wZjtH\n" + "ufYua4jKKux/Qas/ILi0K1pQOZ0J4z0FuKVlLvprth8vwRF8kpLVg5q25JQ9K7do\n" + "/BZEwcfXvd61/FoWQv75DEydiFHC/iMppwwa8QhYj5jC5C9yZLXlvoOiOB5UPkti\n" + "59nqvRQJevtDMFX/fB9KLWVkgAIUqVLEVw==\n" + "-----END PUBLIC KEY-----\n"; + +static string g_testDhFfdhe3072PriKey = "-----BEGIN PRIVATE KEY-----\n" + "MIIBxQIBADCCAZcGCSqGSIb3DQEDATCCAYgCggGBAP//////////rfhUWKK7Spqv\n" + "3FYgJz088di5xYPOLTaVqeE2QRRkM/vMk53OJJs++X0v42NjDHXY9oGyAq7EYXrT\n" + "3x7V1f1lYSQz9R9fBm7QhWNlVT3tGvO1VxNef1fJNZhPDHDg5ot34qaJ2vPv6HId\n" + "8VihNq3nNTCsyk9IOnl6vAqxgrMk+2HRCKlLssjj+7lq2rdg1/RoHU9Co945TfSu\n" + "Vu3nY3K7GQsHp8juCm1wngL84c334uzANATNKDQvYZFy/pzphYP/jk8SMu7ygYPD\n" + "/jsbTG+tczu1/LwuwiAFxY7xg30Wg7LG80omwbLv+ohrQjhhH8/c3jVbO2UZA1u8\n" + "NPTe+ZwCOGG0b8nW5skHetkdJpH39+5ZjLD6wYbZHK7+EwmFE5JwtBMMk7xDeUT0\n" + "/URS4tdN02Ty4h5x9Uv/XK6Cq5yd9p7obSvFIjY6DavFIZebDeraHb+aQtXESE4K\n" + "vNBr+lPd7zwbIO4/1Z18JeQdK2bGLjf//////////wIBAgQlAiMDFnJti6Y7aWEb\n" + "9//FRAcAqlpDn1l6EbzY8cpVYPS4VhG4aw==\n" + "-----END PRIVATE KEY-----\n"; + +static string g_testDhFfdhe3072PubKey = "-----BEGIN PUBLIC KEY-----\n" + "MIIDJDCCAZcGCSqGSIb3DQEDATCCAYgCggGBAP//////////rfhUWKK7Spqv3FYg\n" + "Jz088di5xYPOLTaVqeE2QRRkM/vMk53OJJs++X0v42NjDHXY9oGyAq7EYXrT3x7V\n" + "1f1lYSQz9R9fBm7QhWNlVT3tGvO1VxNef1fJNZhPDHDg5ot34qaJ2vPv6HId8Vih\n" + "Nq3nNTCsyk9IOnl6vAqxgrMk+2HRCKlLssjj+7lq2rdg1/RoHU9Co945TfSuVu3n\n" + "Y3K7GQsHp8juCm1wngL84c334uzANATNKDQvYZFy/pzphYP/jk8SMu7ygYPD/jsb\n" + "TG+tczu1/LwuwiAFxY7xg30Wg7LG80omwbLv+ohrQjhhH8/c3jVbO2UZA1u8NPTe\n" + "+ZwCOGG0b8nW5skHetkdJpH39+5ZjLD6wYbZHK7+EwmFE5JwtBMMk7xDeUT0/URS\n" + "4tdN02Ty4h5x9Uv/XK6Cq5yd9p7obSvFIjY6DavFIZebDeraHb+aQtXESE4KvNBr\n" + "+lPd7zwbIO4/1Z18JeQdK2bGLjf//////////wIBAgOCAYUAAoIBgCnL/c2/ajEL\n" + "hD+XQUVOA96sz/Z/tB5Oimrj7EFi/F0mv4NQX3Xj+AeS1vfvEVMDuTDFWiVLIyIX\n" + "8k+1efJf8MxZvd6ZyqyCua0LQIc1kSAr/QGqOL0sUZMlKpoyuZ8eGN0mM7JlJFag\n" + "8yvXtreycFaoZhaHUlqfj5ICEmgALhX3FjR5H3Lm1AAdiDzAwEi9VmhdTKnt0qia\n" + "3J20vI8n0SgtYTHssYHDJwW6n4LomLim1Jp/AqOhkXUFTyaYLW32bSXM466D06pt\n" + "LNedT2tYNVV2oOS7mwGDJOPoJ2ON6Rh82eGuPtmeLvA+5oVaB1+isDAxNLXxCohT\n" + "LiDZ1tDKe+/syblIMR6LCTQmb4EpgZHQsfO7BSsTHwI9/55POrTZ944rMuV7Ro3y\n" + "aGvxMBLmuoBMKK+jkOF3NuzGxosJaKiAH2skbccdzYs1Qt401dCh0IXqCVjFIwHp\n" + "cywQXQv6YZ0B45T9b7m6H1LjUbAfOdxjLYGe6JtJ8phBw9KTsBpCgA==\n" + "-----END PUBLIC KEY-----\n"; + +static string g_testDhFfdhe4096PriKey = "-----BEGIN PRIVATE KEY-----\n" + "MIICSwIBADCCAhcGCSqGSIb3DQEDATCCAggCggIBAP//////////rfhUWKK7Spqv\n" + "3FYgJz088di5xYPOLTaVqeE2QRRkM/vMk53OJJs++X0v42NjDHXY9oGyAq7EYXrT\n" + "3x7V1f1lYSQz9R9fBm7QhWNlVT3tGvO1VxNef1fJNZhPDHDg5ot34qaJ2vPv6HId\n" + "8VihNq3nNTCsyk9IOnl6vAqxgrMk+2HRCKlLssjj+7lq2rdg1/RoHU9Co945TfSu\n" + "Vu3nY3K7GQsHp8juCm1wngL84c334uzANATNKDQvYZFy/pzphYP/jk8SMu7ygYPD\n" + "/jsbTG+tczu1/LwuwiAFxY7xg30Wg7LG80omwbLv+ohrQjhhH8/c3jVbO2UZA1u8\n" + "NPTe+ZwCOGG0b8nW5skHetkdJpH39+5ZjLD6wYbZHK7+EwmFE5JwtBMMk7xDeUT0\n" + "/URS4tdN02Ty4h5x9Uv/XK6Cq5yd9p7obSvFIjY6DavFIZebDeraHb+aQtXESE4K\n" + "vNBr+lPd7zwbIO4/1Z18JeQdK2aeHvFub1LDFk30+3kw6eTliFe2rH1fQtafbRh3\n" + "Y88dVQNABIf1W6V+Mcx6cTXIhu+0MYrtah4BLZ5oMqkHYAqRgTDEbcd4+XGtADgJ\n" + "KZmjM8uLehoduT1xQAA8Kk7OqfmNCswKgpHNzsl9z47JtVp/iKRrTbWoUfRBguHG\n" + "igB+XmVfav//////////AgECBCsCKRfw3Z6+8+P0Hn/8ftdOa3wcFp/IU7vBV5Y3\n" + "dj1X9NSoW567eG6/s2Qs\n" + "-----END PRIVATE KEY-----\n"; + +static string g_testDhFfdhe4096PubKey = "-----BEGIN PUBLIC KEY-----\n" + "MIIEJTCCAhcGCSqGSIb3DQEDATCCAggCggIBAP//////////rfhUWKK7Spqv3FYg\n" + "Jz088di5xYPOLTaVqeE2QRRkM/vMk53OJJs++X0v42NjDHXY9oGyAq7EYXrT3x7V\n" + "1f1lYSQz9R9fBm7QhWNlVT3tGvO1VxNef1fJNZhPDHDg5ot34qaJ2vPv6HId8Vih\n" + "Nq3nNTCsyk9IOnl6vAqxgrMk+2HRCKlLssjj+7lq2rdg1/RoHU9Co945TfSuVu3n\n" + "Y3K7GQsHp8juCm1wngL84c334uzANATNKDQvYZFy/pzphYP/jk8SMu7ygYPD/jsb\n" + "TG+tczu1/LwuwiAFxY7xg30Wg7LG80omwbLv+ohrQjhhH8/c3jVbO2UZA1u8NPTe\n" + "+ZwCOGG0b8nW5skHetkdJpH39+5ZjLD6wYbZHK7+EwmFE5JwtBMMk7xDeUT0/URS\n" + "4tdN02Ty4h5x9Uv/XK6Cq5yd9p7obSvFIjY6DavFIZebDeraHb+aQtXESE4KvNBr\n" + "+lPd7zwbIO4/1Z18JeQdK2aeHvFub1LDFk30+3kw6eTliFe2rH1fQtafbRh3Y88d\n" + "VQNABIf1W6V+Mcx6cTXIhu+0MYrtah4BLZ5oMqkHYAqRgTDEbcd4+XGtADgJKZmj\n" + "M8uLehoduT1xQAA8Kk7OqfmNCswKgpHNzsl9z47JtVp/iKRrTbWoUfRBguHGigB+\n" + "XmVfav//////////AgECA4ICBgACggIBAKigucWOH8I8vq12hTuGkZiJhdfksOMo\n" + "i/9xtSf+9Ba6eLnSJUBWVO/rbEBi+iJGYwff1r8u8l7AtD2Hcw/wSPZAlt0LXXVX\n" + "TLGk4UxQNxpMaCdsHdxCNxnPQ7HSbkig4ot96+8N2vwXgLUWcd2DIagrh1iN7OAI\n" + "D1j/mCFDwi7gP3az5TgViowTvLi6o5JcN4oew6MMVOiv626lGzk4okaOAyjUlW10\n" + "ZbV8j0Bk7PukOUzXCwDC6V2TxLkDUNkXwg4pDHVGYmQCO9MpECA9zrW+facYwMkg\n" + "k8GJoQ1r7xtD+2fYpFyYhlQPZ5dO1GuCdVa1WbS2/8PRw8jZu5ckQS35OCoBB7JC\n" + "bz1dmWRueDpi2ktpDgjxyOIN7uZQyIFIpsfapt/o0ZszkVWxJvYrR0SdU+dXMjRp\n" + "QlPotOEVq39Hqp7hDa4YDM/Ioi8JIMhAnrynEPlPgzwU2PVelPfJ5adox5+hjG0u\n" + "xdmMGTCI+EMUa7WluPms8movWCvFOT+AUaPS8vkRB5hHcslcWIN+8eUWQRWXuPJ0\n" + "wDDaOWfONV+/irUnlBldB7QL8lqv+hmzqMKkT6Qq3RVcewlIBFTQ5R+T2MjB287V\n" + "sz5ANidkSXiZAqBrOGP4izqZWyY7e0KckPFw9pPJOcImAde33iRsCS+SX2x+ik1Q\n" + "AbVOf7Vd2viT\n" + "-----END PUBLIC KEY-----\n"; + +static string g_testDhFfdhe6144PriKey = "-----BEGIN PRIVATE KEY-----\n" + "MIIDUQIBADCCAxcGCSqGSIb3DQEDATCCAwgCggMBAP//////////rfhUWKK7Spqv\n" + "3FYgJz088di5xYPOLTaVqeE2QRRkM/vMk53OJJs++X0v42NjDHXY9oGyAq7EYXrT\n" + "3x7V1f1lYSQz9R9fBm7QhWNlVT3tGvO1VxNef1fJNZhPDHDg5ot34qaJ2vPv6HId\n" + "8VihNq3nNTCsyk9IOnl6vAqxgrMk+2HRCKlLssjj+7lq2rdg1/RoHU9Co945TfSu\n" + "Vu3nY3K7GQsHp8juCm1wngL84c334uzANATNKDQvYZFy/pzphYP/jk8SMu7ygYPD\n" + "/jsbTG+tczu1/LwuwiAFxY7xg30Wg7LG80omwbLv+ohrQjhhH8/c3jVbO2UZA1u8\n" + "NPTe+ZwCOGG0b8nW5skHetkdJpH39+5ZjLD6wYbZHK7+EwmFE5JwtBMMk7xDeUT0\n" + "/URS4tdN02Ty4h5x9Uv/XK6Cq5yd9p7obSvFIjY6DavFIZebDeraHb+aQtXESE4K\n" + "vNBr+lPd7zwbIO4/1Z18JeQdK2aeHvFub1LDFk30+3kw6eTliFe2rH1fQtafbRh3\n" + "Y88dVQNABIf1W6V+Mcx6cTXIhu+0MYrtah4BLZ5oMqkHYAqRgTDEbcd4+XGtADgJ\n" + "KZmjM8uLehoduT1xQAA8Kk7OqfmNCswKgpHNzsl9z47JtVp/iKRrTbWoUfRBguHG\n" + "igB+Xg3ZAgv9ZLZFA2x6Tmd9LDhTKjojukRCyvU+pju0VDKbdiTIkXvdZLHA/Uyz\n" + "jowzTHAcOs2tBlf8z+xxmx9cPk5GBB84gUf7TP20d6UkcfepqWkQuFUyLttjQNig\n" + "DvCSNQUR4wq+wf/546Juf7KfjBgwI8NYfjjaAHfZtHY+TkuUsrvBlMZlHnfK+ZLu\n" + "qsAjKigb9rOnOcEiYRaCCujbWEemfL75yQkbRi1TjNcrA3Rq539eYiksMRViqEZQ\n" + "XcgtuFQziuSfUjXJW5EXjM8t1crO9APsnRgQxicrBFs7cfnca4DWP91KjprbHmli\n" + "ppUm1DFhwaQdVw15ONrUpA4ynNDkDmX//////////wIBAgQxAi9TPRFZd41FTBHp\n" + "XLtToxZ2gzSWglVgDRJXLTl9cbrJpO3q+hGp5aHn0ICfgt73Xg==\n" + "-----END PRIVATE KEY-----\n"; + +static string g_testDhFfdhe6144PubKey = "-----BEGIN PUBLIC KEY-----\n" + "MIIGJTCCAxcGCSqGSIb3DQEDATCCAwgCggMBAP//////////rfhUWKK7Spqv3FYg\n" + "Jz088di5xYPOLTaVqeE2QRRkM/vMk53OJJs++X0v42NjDHXY9oGyAq7EYXrT3x7V\n" + "1f1lYSQz9R9fBm7QhWNlVT3tGvO1VxNef1fJNZhPDHDg5ot34qaJ2vPv6HId8Vih\n" + "Nq3nNTCsyk9IOnl6vAqxgrMk+2HRCKlLssjj+7lq2rdg1/RoHU9Co945TfSuVu3n\n" + "Y3K7GQsHp8juCm1wngL84c334uzANATNKDQvYZFy/pzphYP/jk8SMu7ygYPD/jsb\n" + "TG+tczu1/LwuwiAFxY7xg30Wg7LG80omwbLv+ohrQjhhH8/c3jVbO2UZA1u8NPTe\n" + "+ZwCOGG0b8nW5skHetkdJpH39+5ZjLD6wYbZHK7+EwmFE5JwtBMMk7xDeUT0/URS\n" + "4tdN02Ty4h5x9Uv/XK6Cq5yd9p7obSvFIjY6DavFIZebDeraHb+aQtXESE4KvNBr\n" + "+lPd7zwbIO4/1Z18JeQdK2aeHvFub1LDFk30+3kw6eTliFe2rH1fQtafbRh3Y88d\n" + "VQNABIf1W6V+Mcx6cTXIhu+0MYrtah4BLZ5oMqkHYAqRgTDEbcd4+XGtADgJKZmj\n" + "M8uLehoduT1xQAA8Kk7OqfmNCswKgpHNzsl9z47JtVp/iKRrTbWoUfRBguHGigB+\n" + "Xg3ZAgv9ZLZFA2x6Tmd9LDhTKjojukRCyvU+pju0VDKbdiTIkXvdZLHA/Uyzjowz\n" + "THAcOs2tBlf8z+xxmx9cPk5GBB84gUf7TP20d6UkcfepqWkQuFUyLttjQNigDvCS\n" + "NQUR4wq+wf/546Juf7KfjBgwI8NYfjjaAHfZtHY+TkuUsrvBlMZlHnfK+ZLuqsAj\n" + "Kigb9rOnOcEiYRaCCujbWEemfL75yQkbRi1TjNcrA3Rq539eYiksMRViqEZQXcgt\n" + "uFQziuSfUjXJW5EXjM8t1crO9APsnRgQxicrBFs7cfnca4DWP91KjprbHmlippUm\n" + "1DFhwaQdVw15ONrUpA4ynNDkDmX//////////wIBAgOCAwYAAoIDAQCHLU8SlkQw\n" + "3QT/NXoXC+9p8zv5D9E4m5bdiWYqkRnnjM/TpHm3tvsWEIXjOBm7L24ekIvU6bwd\n" + "BTh7oKs0bVdXMlT00BV0CZu7VxSernhE0zMccGTGEOyOjJE14YOVu/+gSDrc16QH\n" + "fgNSbKUEd96Xmwdm46ZuGHyWwegnTAZrsJtTufX5xbrOFFHcCJFA5I5vEs6yXl7s\n" + "dH/QmjzWkmtSt26QV9tazxtjeTnpDkhCzOlk0EFksdPaE5Ddwkrqqo6723qAcNzh\n" + "FmJ7/GEL2w/pwLAk+WhCiHilLYti5f4ZixAyIRewQMbiLG4qZhD18L9a9+5WVl+t\n" + "lfFFncZQ8k+Ma3mzNMfgVceBHvAeqzqGyXAzG0aNvmYLT9DQ7MMB1x5IGz/EbvFl\n" + "aJdmv1s7RDBIgxvaE3HwcyUxvahtc/8b4jG1XWz9mSjTv3jUs8d/OWN4daRvlPvU\n" + "Nkz4eoUkqjE6tYmLDBAXfPLeUPPN3J4MIHEA9OdA8y+9VjBoVUGXscInOY74bF5V\n" + "Ry08ecLaJbC5puuD7y9FVzcy+b9tUyhbdKB+xI17uW4R3wbsBEBqRdgNeeGtnDHb\n" + "pSNSBwCsxYdR+08a29PoXw25ABzZesl8jqggMepgFUHIBT6aIGAtU/+Ht+H7++Az\n" + "7R746IqQ9ZPfW5dOB0ZHV7QlWc8rp8mPq39KJtuvkqR7oVXLG4etedeKPOo6G0Fn\n" + "hsqU8YVwnEzCxTiOQ974RQeL4QXC6vvx8g5wJXHqO5jJ7kGpIGvPzlEm0BENn2sk\n" + "fJKPwNV/sKxHQzHp9ngjuIwLtP4AlHBgILJWLhfW+yIC7l3szYZWVnZ3Og1URsYg\n" + "uvq1mapA+Npz5tWTsDrNg9+Dl9NX90pILn91g33b2fuPFL4faOIcicaYIGm3TWLS\n" + "gN1JbUD1LLjV8oxTJ/MRRRzktBs3NElGAks0NKkIMzoCF2X++r7Qow+rbkHtT6bN\n" + "oGE+prxc+oLDee7WBVc0wPPG5sRdXzWVHlySi40OYjMoWhFq5rA+s4s=\n" + "-----END PUBLIC KEY-----\n"; + +static string g_testDhFfdhe8192PriKey = "-----BEGIN PRIVATE KEY-----\n" + "MIIEVAIBADCCBBcGCSqGSIb3DQEDATCCBAgCggQBAP//////////rfhUWKK7Spqv\n" + "3FYgJz088di5xYPOLTaVqeE2QRRkM/vMk53OJJs++X0v42NjDHXY9oGyAq7EYXrT\n" + "3x7V1f1lYSQz9R9fBm7QhWNlVT3tGvO1VxNef1fJNZhPDHDg5ot34qaJ2vPv6HId\n" + "8VihNq3nNTCsyk9IOnl6vAqxgrMk+2HRCKlLssjj+7lq2rdg1/RoHU9Co945TfSu\n" + "Vu3nY3K7GQsHp8juCm1wngL84c334uzANATNKDQvYZFy/pzphYP/jk8SMu7ygYPD\n" + "/jsbTG+tczu1/LwuwiAFxY7xg30Wg7LG80omwbLv+ohrQjhhH8/c3jVbO2UZA1u8\n" + "NPTe+ZwCOGG0b8nW5skHetkdJpH39+5ZjLD6wYbZHK7+EwmFE5JwtBMMk7xDeUT0\n" + "/URS4tdN02Ty4h5x9Uv/XK6Cq5yd9p7obSvFIjY6DavFIZebDeraHb+aQtXESE4K\n" + "vNBr+lPd7zwbIO4/1Z18JeQdK2aeHvFub1LDFk30+3kw6eTliFe2rH1fQtafbRh3\n" + "Y88dVQNABIf1W6V+Mcx6cTXIhu+0MYrtah4BLZ5oMqkHYAqRgTDEbcd4+XGtADgJ\n" + "KZmjM8uLehoduT1xQAA8Kk7OqfmNCswKgpHNzsl9z47JtVp/iKRrTbWoUfRBguHG\n" + "igB+Xg3ZAgv9ZLZFA2x6Tmd9LDhTKjojukRCyvU+pju0VDKbdiTIkXvdZLHA/Uyz\n" + "jowzTHAcOs2tBlf8z+xxmx9cPk5GBB84gUf7TP20d6UkcfepqWkQuFUyLttjQNig\n" + "DvCSNQUR4wq+wf/546Juf7KfjBgwI8NYfjjaAHfZtHY+TkuUsrvBlMZlHnfK+ZLu\n" + "qsAjKigb9rOnOcEiYRaCCujbWEemfL75yQkbRi1TjNcrA3Rq539eYiksMRViqEZQ\n" + "XcgtuFQziuSfUjXJW5EXjM8t1crO9APsnRgQxicrBFs7cfnca4DWP91KjprbHmli\n" + "ppUm1DFhwaQdVw15ONrUpA4ynM/0aqo2rQBM9gDIOB5CWjHZUa5k/bI/zslQnUNo\n" + "f+tp7dHMXguMw732SxDvhrYxQqOriClVWy90fJMmZcssDxzAG9cCKTiIOdKvBeRU\n" + "UErHi3WCgihGwLo1w19cWRYMwEb9glFUH8aMnIawIrtwmYdqRg50UaipMQlwP+4c\n" + "IX5sOCblLFGqaR4OQjz8menjFlDBIXtiSBbNrZqV+dW4AZSI2cCgof4wdaV34jGD\n" + "+B1KPy+kVx78jOC6ik/otoVd/nKwpm7e0vur++WKMPr6vhxdcah+L3Qe+MH+hv6m\n" + "u/3lMGd/DZfRHUn3qEQ9CCLlBqn0YU4BHiqUg4/4jNaMi7fFxkJM//////////8C\n" + "AQIENAIyNvBPpNeXtnI5saYMiXvrUSRJw7Yq6QWkYU2C9Bf6vGpP3dEsmHQVbWPe\n" + "IEHpmLKk1g8=\n" + "-----END PRIVATE KEY-----\n"; + +static string g_testDhFfdhe8192PubKey = "-----BEGIN PUBLIC KEY-----\n" + "MIIIJTCCBBcGCSqGSIb3DQEDATCCBAgCggQBAP//////////rfhUWKK7Spqv3FYg\n" + "Jz088di5xYPOLTaVqeE2QRRkM/vMk53OJJs++X0v42NjDHXY9oGyAq7EYXrT3x7V\n" + "1f1lYSQz9R9fBm7QhWNlVT3tGvO1VxNef1fJNZhPDHDg5ot34qaJ2vPv6HId8Vih\n" + "Nq3nNTCsyk9IOnl6vAqxgrMk+2HRCKlLssjj+7lq2rdg1/RoHU9Co945TfSuVu3n\n" + "Y3K7GQsHp8juCm1wngL84c334uzANATNKDQvYZFy/pzphYP/jk8SMu7ygYPD/jsb\n" + "TG+tczu1/LwuwiAFxY7xg30Wg7LG80omwbLv+ohrQjhhH8/c3jVbO2UZA1u8NPTe\n" + "+ZwCOGG0b8nW5skHetkdJpH39+5ZjLD6wYbZHK7+EwmFE5JwtBMMk7xDeUT0/URS\n" + "4tdN02Ty4h5x9Uv/XK6Cq5yd9p7obSvFIjY6DavFIZebDeraHb+aQtXESE4KvNBr\n" + "+lPd7zwbIO4/1Z18JeQdK2aeHvFub1LDFk30+3kw6eTliFe2rH1fQtafbRh3Y88d\n" + "VQNABIf1W6V+Mcx6cTXIhu+0MYrtah4BLZ5oMqkHYAqRgTDEbcd4+XGtADgJKZmj\n" + "M8uLehoduT1xQAA8Kk7OqfmNCswKgpHNzsl9z47JtVp/iKRrTbWoUfRBguHGigB+\n" + "Xg3ZAgv9ZLZFA2x6Tmd9LDhTKjojukRCyvU+pju0VDKbdiTIkXvdZLHA/Uyzjowz\n" + "THAcOs2tBlf8z+xxmx9cPk5GBB84gUf7TP20d6UkcfepqWkQuFUyLttjQNigDvCS\n" + "NQUR4wq+wf/546Juf7KfjBgwI8NYfjjaAHfZtHY+TkuUsrvBlMZlHnfK+ZLuqsAj\n" + "Kigb9rOnOcEiYRaCCujbWEemfL75yQkbRi1TjNcrA3Rq539eYiksMRViqEZQXcgt\n" + "uFQziuSfUjXJW5EXjM8t1crO9APsnRgQxicrBFs7cfnca4DWP91KjprbHmlippUm\n" + "1DFhwaQdVw15ONrUpA4ynM/0aqo2rQBM9gDIOB5CWjHZUa5k/bI/zslQnUNof+tp\n" + "7dHMXguMw732SxDvhrYxQqOriClVWy90fJMmZcssDxzAG9cCKTiIOdKvBeRUUErH\n" + "i3WCgihGwLo1w19cWRYMwEb9glFUH8aMnIawIrtwmYdqRg50UaipMQlwP+4cIX5s\n" + "OCblLFGqaR4OQjz8menjFlDBIXtiSBbNrZqV+dW4AZSI2cCgof4wdaV34jGD+B1K\n" + "Py+kVx78jOC6ik/otoVd/nKwpm7e0vur++WKMPr6vhxdcah+L3Qe+MH+hv6mu/3l\n" + "MGd/DZfRHUn3qEQ9CCLlBqn0YU4BHiqUg4/4jNaMi7fFxkJM//////////8CAQID\n" + "ggQGAAKCBAEAsDdW0aV/QrWols/oaofco+HGc9BEdt+WwxibMrtn3IBv7XG7qnzL\n" + "h5x63WKlt5Gn+13KcNlap7YN1GM8AJpt7V4w3vuuevjU6yPDsVe7r658zadlkEoS\n" + "6bhsBcUOnq7NYxJdC70dOY77moDhuwLbv1InwRTUL71sv7tTONZ54SDonW9W8uSj\n" + "EIT7Pru3hDl1GNQKyGIKTTVZbaxFTL7OVNCL12Y20ijhEzWh5LhkhocWLL5ef+g+\n" + "WdH52ta1nwaT2nJjposAxfngsNy7u1SeZjovHhQp5Ef7yV87MW2kcX8u5KNN1wES\n" + "22JE5/95wr4O3OlmTmlUYDABm0A5TsCWENonuejSMtRwCufUZ3UmCrBDkXXD4kRb\n" + "JhykGp1smKboHwzk2VlZWpSLK02F0QaIEoyWGKyxinX63lG0GsLEaK7lIUo9Irve\n" + "ugdPbjxbERdCmnq7JprzZnyLWvdXUErh2l6NyNw8ZMfO3Cl8F3DCeWS8eaBh1fiN\n" + "6TAu+fyhgAVvGjW79BJCq1Sym+OlP71AXckzSHWVeqbBvwXLM54bQmcEJXakQQQk\n" + "ZMwyuvHRtmBsxHVxqb8Y8K6oVzr7i3EmyYCZNXv4JNAgIFbXKe6PkuNVnblxCNea\n" + "qMCviXtKpoIFpFcukwi8WjotLN7oXNW80/tv9kOOG5DI3ziPeJheHQLbzJuUA8Ew\n" + "57sqCjAXhIIrQ5W0QDULGbQnHY5IAeyi4YIiSGQg3ECAbHkdmYG8a9WyabM/Sh6H\n" + "+i2bU0S0W8w2zt6woAiBu1/AqCXDCJIy2aU6n3h3R/BLWJvOFcTUBy/NmKvB1LHq\n" + "ynTydOK+Qy0wzKr0ubB5rhWqk9Zv7ROC22LQJfXdH9bdjQQcOFSDOMIvKmD5HBaD\n" + "XzcNvn0LSYexTSPbY7U/1JwpXp54BYvSVf1JdxGO3UM85ODKSg8dlmpV3R29+6VA\n" + "xiJwVqaQY18AfWFxEOcTasxB5cv8DtCEYbq2L4fSg4Ix/ja3u4yU7HnWi76CajwT\n" + "gzKs9EB7ZshsUCp6IMRBThY8x7fKOtcpxL6JiL+SjB/eQfzQDhVo0rohiZ1m3g3p\n" + "+n1Sru1JdnWIl+iozCU5Iwy2HG4IfK2noUDBxpn8kFl+ZK4RQTuyzCbbFOeIFNrt\n" + "TrMTJszuiyLwqxZNdONKJoA0HMyxEnpt4wgN30jOyJtf2XY0yaM0s+gfAzyw09HF\n" + "t6wfDQ2Vj0RBBF9fLp/RBGZArt5lN5DIL/JwB0Lwec6cyDf6PlG7Cc2BOaejKgof\n" + "ffoNDeTER8jTZb63tfTkyiOxDjwggHZdx8RzG7wde04TLegw3VGdVAX6Q5WrnLeS\n" + "TPUgTvYxns26sKVlFjRKqVKVCmy68iMB5Q==\n" + "-----END PUBLIC KEY-----\n"; + +static string g_testDhModp2048PriKey = "-----BEGIN PRIVATE KEY-----\n" + "MIIBPwIBADCCARcGCSqGSIb3DQEDATCCAQgCggEBAP//////////yQ/aoiFowjTE\n" + "xmKLgNwc0SkCTgiKZ8x0Agu+pjsTmyJRSgh5jjQE3e+VGbPNOkMbMCsKbfJfFDdP\n" + "4TVtbVHCReSFtXZiXn7G9ExC6aY37WsL/1y29Aa37e44a/taiZ+lrp8kEXxLH+ZJ\n" + "KGZR7ORbPcIAfLihY78FmNpINhxV05ppFj+o/STPX4NlXSPco62WHGLzViCFUrue\n" + "1SkHcJaWbWcMNU5KvJgE8XRsCMoYIXwykF5GLjbOO+OedywYDoYDmyeDouwHoo+1\n" + "xV3wb0xSyd4ry/aVWBcYOZVJfOqVauUV0iYYmPoFEBVyjlqKrKpo//////////8C\n" + "AQIEHwIdAPRToxgVjHMVN8nkoSWKprLl8llag1wAYmiLrng=\n" + "-----END PRIVATE KEY-----\n"; + +static string g_testDhModp2048PubKey = "-----BEGIN PUBLIC KEY-----\n" + "MIICJTCCARcGCSqGSIb3DQEDATCCAQgCggEBAP//////////yQ/aoiFowjTExmKL\n" + "gNwc0SkCTgiKZ8x0Agu+pjsTmyJRSgh5jjQE3e+VGbPNOkMbMCsKbfJfFDdP4TVt\n" + "bVHCReSFtXZiXn7G9ExC6aY37WsL/1y29Aa37e44a/taiZ+lrp8kEXxLH+ZJKGZR\n" + "7ORbPcIAfLihY78FmNpINhxV05ppFj+o/STPX4NlXSPco62WHGLzViCFUrue1SkH\n" + "cJaWbWcMNU5KvJgE8XRsCMoYIXwykF5GLjbOO+OedywYDoYDmyeDouwHoo+1xV3w\n" + "b0xSyd4ry/aVWBcYOZVJfOqVauUV0iYYmPoFEBVyjlqKrKpo//////////8CAQID\n" + "ggEGAAKCAQEAggsOz2iHuIXDEXGeei4/4c2E1I2gVJ/MuELlf1l2vZdnQZzldZYs\n" + "HMDz77rfHHzXOisSpgEr7eY5lcRogtf5+cT7pBljnou/e+yKUlfdo0rrC/+koAp8\n" + "N+hAYTkH2Fwt/oEWckcEuuYJLnU5L0j7AcWSGjZrI0driQaQM40hzgfHl7j1fRcU\n" + "t9Tl2ycdzrV0F/C7SIa/P1qstdxTzjAZlmoWVC2W3eC5wM3b/A/tsH73C84vKpcn\n" + "JCvcfg7HpvXmwTbywGfoXtlDgcM3GaZVFvAdqHcEdQyvWp9ePqQ23oSxC//7TgXi\n" + "CUiaF/zepTKo3Z2aBTio3ghUCg6hfcRWdw==\n" + "-----END PUBLIC KEY-----\n"; + +static string g_testDhModp3072PriKey = "-----BEGIN PRIVATE KEY-----\n" + "MIIBxQIBADCCAZcGCSqGSIb3DQEDATCCAYgCggGBAP//////////yQ/aoiFowjTE\n" + "xmKLgNwc0SkCTgiKZ8x0Agu+pjsTmyJRSgh5jjQE3e+VGbPNOkMbMCsKbfJfFDdP\n" + "4TVtbVHCReSFtXZiXn7G9ExC6aY37WsL/1y29Aa37e44a/taiZ+lrp8kEXxLH+ZJ\n" + "KGZR7ORbPcIAfLihY78FmNpINhxV05ppFj+o/STPX4NlXSPco62WHGLzViCFUrue\n" + "1SkHcJaWbWcMNU5KvJgE8XRsCMoYIXwykF5GLjbOO+OedywYDoYDmyeDouwHoo+1\n" + "xV3wb0xSyd4ry/aVWBcYOZVJfOqVauUV0iYYmPoFEBVyjlqKqsQtrTMXDQRQejOo\n" + "VSGr3xy6ZOz7hQRY2+8KiupxV10GDH2zlw+FpuHkx6v1rozbCTPXHoyU4EolYZ3O\n" + "49ImGtLua/Ev+gbZighk2HYCcz7IamRSHysYF3sgDLvhF1d6YV1sdwmIwLrZRuII\n" + "4k+gdOWrMUPbW/zg/RCOS4LRIKk60sr//////////wIBAgQlAiMENiPbUKDmUyxx\n" + "OFZZ2Fsb0Z4ONl0+xPwLUxWG9gmXoRLL6A==\n" + "-----END PRIVATE KEY-----\n"; + +static string g_testDhModp3072PubKey = "-----BEGIN PUBLIC KEY-----\n" + "MIIDJTCCAZcGCSqGSIb3DQEDATCCAYgCggGBAP//////////yQ/aoiFowjTExmKL\n" + "gNwc0SkCTgiKZ8x0Agu+pjsTmyJRSgh5jjQE3e+VGbPNOkMbMCsKbfJfFDdP4TVt\n" + "bVHCReSFtXZiXn7G9ExC6aY37WsL/1y29Aa37e44a/taiZ+lrp8kEXxLH+ZJKGZR\n" + "7ORbPcIAfLihY78FmNpINhxV05ppFj+o/STPX4NlXSPco62WHGLzViCFUrue1SkH\n" + "cJaWbWcMNU5KvJgE8XRsCMoYIXwykF5GLjbOO+OedywYDoYDmyeDouwHoo+1xV3w\n" + "b0xSyd4ry/aVWBcYOZVJfOqVauUV0iYYmPoFEBVyjlqKqsQtrTMXDQRQejOoVSGr\n" + "3xy6ZOz7hQRY2+8KiupxV10GDH2zlw+FpuHkx6v1rozbCTPXHoyU4EolYZ3O49Im\n" + "GtLua/Ev+gbZighk2HYCcz7IamRSHysYF3sgDLvhF1d6YV1sdwmIwLrZRuII4k+g\n" + "dOWrMUPbW/zg/RCOS4LRIKk60sr//////////wIBAgOCAYYAAoIBgQDeqifvv/RC\n" + "T+VpuDB9QD0WHxjTgXAlhH3jwQn7rdqz7VgLOKezuiWKXRbPiAmvq7YvweHQF3m5\n" + "mVSgcmTY7Jdea/tZS3G3/fjxzxaRuVH73E0BmbNCIeiL/KQcRLqqHJ4s486ezeoP\n" + "MgMIuYZ/Q95otbsAbufiiI2TvFXy9M7//m097+nL3eAnMV3bomJ1vgLacO6nm3xT\n" + "a+MfYCZFzzreTkUWrnzcvvPLdXI3cOVimqiuWhMuxd3LTAm7cnTNyCCpQQ+VwwZT\n" + "CX1b5MBiNuEHGKqBAF65L2o1yi5kPgjq4ojiJNEjx4owoSDdZP5GG+IJPO/ccLQo\n" + "KCnRW+zAJykpaZp7Ujpc2eNJ+IoR+uXUvhuott7CpgRAZlhTCkv7ORvYuTX8AwUo\n" + "JJ1weksOcRxoWpLSoi4g4t90HnOeXXx0x3dqzjGlXId2VflcWNApNsHgC1Z6G+Qs\n" + "QJTpEM684ClYVc+T8wexkX3EdfYmBiIRaUlJ7DTxQzJKhTtuP7kg4mk=\n" + "-----END PUBLIC KEY-----\n"; + +static string g_testDhModp4096PriKey = "-----BEGIN PRIVATE KEY-----\n" + "MIICSwIBADCCAhcGCSqGSIb3DQEDATCCAggCggIBAP//////////yQ/aoiFowjTE\n" + "xmKLgNwc0SkCTgiKZ8x0Agu+pjsTmyJRSgh5jjQE3e+VGbPNOkMbMCsKbfJfFDdP\n" + "4TVtbVHCReSFtXZiXn7G9ExC6aY37WsL/1y29Aa37e44a/taiZ+lrp8kEXxLH+ZJ\n" + "KGZR7ORbPcIAfLihY78FmNpINhxV05ppFj+o/STPX4NlXSPco62WHGLzViCFUrue\n" + "1SkHcJaWbWcMNU5KvJgE8XRsCMoYIXwykF5GLjbOO+OedywYDoYDmyeDouwHoo+1\n" + "xV3wb0xSyd4ry/aVWBcYOZVJfOqVauUV0iYYmPoFEBVyjlqKqsQtrTMXDQRQejOo\n" + "VSGr3xy6ZOz7hQRY2+8KiupxV10GDH2zlw+FpuHkx6v1rozbCTPXHoyU4EolYZ3O\n" + "49ImGtLua/Ev+gbZighk2HYCcz7IamRSHysYF3sgDLvhF1d6YV1sdwmIwLrZRuII\n" + "4k+gdOWrMUPbW/zg/RCOS4LRIKkhCAEacjwSp4fm14hxmhC9ulsmmcMnGGr04jwa\n" + "lGg0thUL2iWD6coq1Ezo27vC2wTejvkujvwUH77Kpih8WUdOa8BdmbKWT6CQw6Ij\n" + "O6GGUVvn7R9hKXDO4tevuBvddiFwSBzQBpEn1bBaqZO06piNj93Bhv+33JCmwI9N\n" + "9DXJNAYxmf//////////AgECBCsCKRNHTBYLOilaRpAM+smrwpKazwY6qmI60sZa\n" + "trdrzm3cdKsTGMV+G4Xj\n" + "-----END PRIVATE KEY-----\n"; + +static string g_testDhModp4096PubKey = "-----BEGIN PUBLIC KEY-----\n" + "MIIEJTCCAhcGCSqGSIb3DQEDATCCAggCggIBAP//////////yQ/aoiFowjTExmKL\n" + "gNwc0SkCTgiKZ8x0Agu+pjsTmyJRSgh5jjQE3e+VGbPNOkMbMCsKbfJfFDdP4TVt\n" + "bVHCReSFtXZiXn7G9ExC6aY37WsL/1y29Aa37e44a/taiZ+lrp8kEXxLH+ZJKGZR\n" + "7ORbPcIAfLihY78FmNpINhxV05ppFj+o/STPX4NlXSPco62WHGLzViCFUrue1SkH\n" + "cJaWbWcMNU5KvJgE8XRsCMoYIXwykF5GLjbOO+OedywYDoYDmyeDouwHoo+1xV3w\n" + "b0xSyd4ry/aVWBcYOZVJfOqVauUV0iYYmPoFEBVyjlqKqsQtrTMXDQRQejOoVSGr\n" + "3xy6ZOz7hQRY2+8KiupxV10GDH2zlw+FpuHkx6v1rozbCTPXHoyU4EolYZ3O49Im\n" + "GtLua/Ev+gbZighk2HYCcz7IamRSHysYF3sgDLvhF1d6YV1sdwmIwLrZRuII4k+g\n" + "dOWrMUPbW/zg/RCOS4LRIKkhCAEacjwSp4fm14hxmhC9ulsmmcMnGGr04jwalGg0\n" + "thUL2iWD6coq1Ezo27vC2wTejvkujvwUH77Kpih8WUdOa8BdmbKWT6CQw6IjO6GG\n" + "UVvn7R9hKXDO4tevuBvddiFwSBzQBpEn1bBaqZO06piNj93Bhv+33JCmwI9N9DXJ\n" + "NAYxmf//////////AgECA4ICBgACggIBANVYMZwPOuZPzRGg5ved0+Tqqkca2zqI\n" + "fJT91Bi/4ks8Ppxf1D7PvmNXUtxPjjrxNleDATsZOjKsjSunUB7szzGizuH6CaO9\n" + "HFogxp/ugvSRF6GkISbcTN8Ek89iqImZkC67e48L1sgtixrd5BKMF1i5MJs7vdOj\n" + "gH0vFCoGxPR878HnmN8E0+gS2z6JVXvgIYQApMqXuptICrGUGQrTILUDf/lDLh3l\n" + "VMQO908GJcmGWImSheWUyNqz88eZrff4lFTRUz4jx0dKowN3SrTGNkWMcNsK7bIg\n" + "Qe0408Ax68olQBgbKCAllfHUBGIP0XIDvvXiuqMaFni7NKsecYKCNPy2iDyzCNen\n" + "kdvFc/buG5VUWSNjEQNfO/7K2OBZTUoofYS1/v8AXmPI1KBJB6Cd3yObVghv74lT\n" + "Itri59BffG8HkpfI4zGVuk1nZ8sBJqqCY1ZR4Xcpj/PbcA5PioeUTKrkffsm/Xby\n" + "1u7LEiOZFag3nJ0DArGwCtxoODdFFaF6rq5IcCcNcrP/lW9E+oY+Rus0eRN0h0w8\n" + "MhWqJQ6y6fdPgcTvimWtUfE2o/9vXvvONJDk4bUUpRw/D24Mg4x9/0Zjp5zWaia/\n" + "sLNTm2RLMGU0PjBGIc/33+6JFbO3t4FdsDU+mTiaissfgAnzBLEnsMjw3Du/HC9s\n" + "L+99jo6k4lcq\n" + "-----END PUBLIC KEY-----\n"; + +static string g_testDhModp6144PriKey = "-----BEGIN PRIVATE KEY-----\n" + "MIIDUQIBADCCAxcGCSqGSIb3DQEDATCCAwgCggMBAP//////////yQ/aoiFowjTE\n" + "xmKLgNwc0SkCTgiKZ8x0Agu+pjsTmyJRSgh5jjQE3e+VGbPNOkMbMCsKbfJfFDdP\n" + "4TVtbVHCReSFtXZiXn7G9ExC6aY37WsL/1y29Aa37e44a/taiZ+lrp8kEXxLH+ZJ\n" + "KGZR7ORbPcIAfLihY78FmNpINhxV05ppFj+o/STPX4NlXSPco62WHGLzViCFUrue\n" + "1SkHcJaWbWcMNU5KvJgE8XRsCMoYIXwykF5GLjbOO+OedywYDoYDmyeDouwHoo+1\n" + "xV3wb0xSyd4ry/aVWBcYOZVJfOqVauUV0iYYmPoFEBVyjlqKqsQtrTMXDQRQejOo\n" + "VSGr3xy6ZOz7hQRY2+8KiupxV10GDH2zlw+FpuHkx6v1rozbCTPXHoyU4EolYZ3O\n" + "49ImGtLua/Ev+gbZighk2HYCcz7IamRSHysYF3sgDLvhF1d6YV1sdwmIwLrZRuII\n" + "4k+gdOWrMUPbW/zg/RCOS4LRIKkhCAEacjwSp4fm14hxmhC9ulsmmcMnGGr04jwa\n" + "lGg0thUL2iWD6coq1Ezo27vC2wTejvkujvwUH77Kpih8WUdOa8BdmbKWT6CQw6Ij\n" + "O6GGUVvn7R9hKXDO4tevuBvddiFwSBzQBpEn1bBaqZO06piNj93Bhv+33JCmwI9N\n" + "9DXJNAKEkjbD+rTSfHAmwdTcsmAmRt7JdR52Pbo3vfj/lAatnlMO5ds4L0EwAa6w\n" + "alPtkCfYMReXJ7CGWokY2j7b68+bFO1Ezmy6ztS7G9t/FEfmzCVLMyBRUSvXr0Jv\n" + "uPQBN4zSv1mDygHGS5Ls8DLqFdFyHQP0gtfObnT+9tVecC9GmAyCtahAMZALHJ5Z\n" + "58l/vsfo8yOpen42zIi+Dx1Ft/9YWsVL1AeyK0FUqsyPbX6/SOHYFMxe0g+AN+Cn\n" + "lxXu8pvjKAah1Yu3xdp29VCqPYofv/DrGcyxoxPVXNpWyewu8pYyOH/o1248BGgE\n" + "Po9mP0hg7hK/LVsLdHTW5pT5Hm3MQCT//////////wIBAgQxAi9/Au8+qm3n56dp\n" + "3l5vq0PO5DQUxznbuMdnJu/hkHz7hSh5+MNgKQECtgnxjatsWg==\n" + "-----END PRIVATE KEY-----\n"; + +static string g_testDhModp6144PubKey = "-----BEGIN PUBLIC KEY-----\n" + "MIIGJDCCAxcGCSqGSIb3DQEDATCCAwgCggMBAP//////////yQ/aoiFowjTExmKL\n" + "gNwc0SkCTgiKZ8x0Agu+pjsTmyJRSgh5jjQE3e+VGbPNOkMbMCsKbfJfFDdP4TVt\n" + "bVHCReSFtXZiXn7G9ExC6aY37WsL/1y29Aa37e44a/taiZ+lrp8kEXxLH+ZJKGZR\n" + "7ORbPcIAfLihY78FmNpINhxV05ppFj+o/STPX4NlXSPco62WHGLzViCFUrue1SkH\n" + "cJaWbWcMNU5KvJgE8XRsCMoYIXwykF5GLjbOO+OedywYDoYDmyeDouwHoo+1xV3w\n" + "b0xSyd4ry/aVWBcYOZVJfOqVauUV0iYYmPoFEBVyjlqKqsQtrTMXDQRQejOoVSGr\n" + "3xy6ZOz7hQRY2+8KiupxV10GDH2zlw+FpuHkx6v1rozbCTPXHoyU4EolYZ3O49Im\n" + "GtLua/Ev+gbZighk2HYCcz7IamRSHysYF3sgDLvhF1d6YV1sdwmIwLrZRuII4k+g\n" + "dOWrMUPbW/zg/RCOS4LRIKkhCAEacjwSp4fm14hxmhC9ulsmmcMnGGr04jwalGg0\n" + "thUL2iWD6coq1Ezo27vC2wTejvkujvwUH77Kpih8WUdOa8BdmbKWT6CQw6IjO6GG\n" + "UVvn7R9hKXDO4tevuBvddiFwSBzQBpEn1bBaqZO06piNj93Bhv+33JCmwI9N9DXJ\n" + "NAKEkjbD+rTSfHAmwdTcsmAmRt7JdR52Pbo3vfj/lAatnlMO5ds4L0EwAa6walPt\n" + "kCfYMReXJ7CGWokY2j7b68+bFO1Ezmy6ztS7G9t/FEfmzCVLMyBRUSvXr0JvuPQB\n" + "N4zSv1mDygHGS5Ls8DLqFdFyHQP0gtfObnT+9tVecC9GmAyCtahAMZALHJ5Z58l/\n" + "vsfo8yOpen42zIi+Dx1Ft/9YWsVL1AeyK0FUqsyPbX6/SOHYFMxe0g+AN+CnlxXu\n" + "8pvjKAah1Yu3xdp29VCqPYofv/DrGcyxoxPVXNpWyewu8pYyOH/o1248BGgEPo9m\n" + "P0hg7hK/LVsLdHTW5pT5Hm3MQCT//////////wIBAgOCAwUAAoIDAGB/u7i3VHL4\n" + "Mj1OapD7dC5GaQK1joynj/rVLiQihtgOzgEegvwFlXb+0U2s054fngWA9DdVL8WF\n" + "sqhyd+TANDNx52utLRMOyKeovJDpdyCrFU5XOORYC/0W/sKpLhgzD+lPDayj85WK\n" + "xrsutvS/dXQ8sBEe06YOWAEYWoCZ2PMZw7pI8fj0JTfNS0fxHCDO+1uVJeADulM+\n" + "qKDlBHFd0blzRRfUwj/Of3CrtsBajQiH3aG05QkqJyumvMOhEUrkgBGbhnWg9Qi0\n" + "cSZgH5vmRnGCPEvhuX5eRBDwXwTy9UxWxr4c/Y5krnmu0CmZQVNV+cZga71f7MJW\n" + "DUXbgigcF/yZJB/6Ujj70OS7W251UMWpjAMt5pIPuYfFKQ7JyJ/u6AQkgaGcpMLu\n" + "L66ptUJsvGqdACzAq0PieiO8aCuWBqJMKUU3zduVxjPXMjERfUNNeqbefyvmjYb6\n" + "XjF8c/WB0d3d1FTypJ749KTUFXBrhZdOHb+xVYmK4QEdqxZ7XntG/C1GYkGnLaSs\n" + "v7caJ68xs8eP8/0XI7Wd3q1Uxk77dSRBqmq+WsAvnwKY8P3gdbzp/L79j56WZ9Fi\n" + "PghywBjb35CDwa514z4VUfxoeDzjBN6uESYyQf2CeQXIUECZGXepj4s21KXWNhOF\n" + "rVgWu2PhoLIirhdwZEhFTTRAvs+LkOMsVhjkWvlS4+7aRqIiusWUl+SLtbO2Jc0n\n" + "yBS2bVcGkLxniAnUyomou1wbAKr6AFXZQ7W9eT2wiBaHsNyiH7MdWyLw5kpAp5MZ\n" + "wq4hKy1fJu6YDrFMWlP2UDRXyTj8G6aIdsYk1GdUOqnrB+j9q9xxo+prZ10QAIb/\n" + "NpgJmxJa/eJChgMbwlOvfDRHBoqUDnIKOOleHwsj8CHlQiAVd+UoqPORA4jwkH3n\n" + "L86S+1lmy3gYiDz69wauEruz7suOFdViRxA/OIoh0l+F9m7lz8YHo65zljQBdFF0\n" + "PX+9AUeZh/diVQGs7lPp9qiXfdDZ+1l6XskgfNn1N41+RDxBrRHnWA==\n" + "-----END PUBLIC KEY-----\n"; + +static string g_testDhModp8192PriKey = "-----BEGIN PRIVATE KEY-----\n" + "MIIEVQIBADCCBBcGCSqGSIb3DQEDATCCBAgCggQBAP//////////yQ/aoiFowjTE\n" + "xmKLgNwc0SkCTgiKZ8x0Agu+pjsTmyJRSgh5jjQE3e+VGbPNOkMbMCsKbfJfFDdP\n" + "4TVtbVHCReSFtXZiXn7G9ExC6aY37WsL/1y29Aa37e44a/taiZ+lrp8kEXxLH+ZJ\n" + "KGZR7ORbPcIAfLihY78FmNpINhxV05ppFj+o/STPX4NlXSPco62WHGLzViCFUrue\n" + "1SkHcJaWbWcMNU5KvJgE8XRsCMoYIXwykF5GLjbOO+OedywYDoYDmyeDouwHoo+1\n" + "xV3wb0xSyd4ry/aVWBcYOZVJfOqVauUV0iYYmPoFEBVyjlqKqsQtrTMXDQRQejOo\n" + "VSGr3xy6ZOz7hQRY2+8KiupxV10GDH2zlw+FpuHkx6v1rozbCTPXHoyU4EolYZ3O\n" + "49ImGtLua/Ev+gbZighk2HYCcz7IamRSHysYF3sgDLvhF1d6YV1sdwmIwLrZRuII\n" + "4k+gdOWrMUPbW/zg/RCOS4LRIKkhCAEacjwSp4fm14hxmhC9ulsmmcMnGGr04jwa\n" + "lGg0thUL2iWD6coq1Ezo27vC2wTejvkujvwUH77Kpih8WUdOa8BdmbKWT6CQw6Ij\n" + "O6GGUVvn7R9hKXDO4tevuBvddiFwSBzQBpEn1bBaqZO06piNj93Bhv+33JCmwI9N\n" + "9DXJNAKEkjbD+rTSfHAmwdTcsmAmRt7JdR52Pbo3vfj/lAatnlMO5ds4L0EwAa6w\n" + "alPtkCfYMReXJ7CGWokY2j7b68+bFO1Ezmy6ztS7G9t/FEfmzCVLMyBRUSvXr0Jv\n" + "uPQBN4zSv1mDygHGS5Ls8DLqFdFyHQP0gtfObnT+9tVecC9GmAyCtahAMZALHJ5Z\n" + "58l/vsfo8yOpen42zIi+Dx1Ft/9YWsVL1AeyK0FUqsyPbX6/SOHYFMxe0g+AN+Cn\n" + "lxXu8pvjKAah1Yu3xdp29VCqPYofv/DrGcyxoxPVXNpWyewu8pYyOH/o1248BGgE\n" + "Po9mP0hg7hK/LVsLdHTW5pT5Hm2+EVl0o5JvEv7l5Dh3fLapMt+M2L7E0HO5Mbo7\n" + "yDK2jZ3TAHQfp7+K/EftJXb2k2ukJGY6q2OcWuT1aDQjtHQr8cl4I48Wy+OdZS3j\n" + "/bi+/ISK2SIiLgSkA3wHE+tXqBoj8Mc0c/xkbOowa0vLyIYvg4Xd+p1Lf6LAh+h5\n" + "aDMD7VvdOgYrPPWzonimbSoT+D9E+C3fMQ7gdKtqNkWX6JmgJV3BZPMcxQhGhR35\n" + "q0gZXe1+obHVEL1+501z+vNrwx7Pomg1kEb064efkkAJQ4tIHGzXiJoALtXuOCvJ\n" + "GQ2m/AJuR5VY5EdWd+mqnjBQ4nZWlN/IH1bogLlucWDJgN2Y7dPf//////////8C\n" + "AQIENQIzAL5VbOx8Gf9Okpw22McpN5hm04wj+Mok9ZB+eZuuMD9hTBw5SMrz6lP7\n" + "m/WaPrKgRpnw\n" + "-----END PRIVATE KEY-----\n"; + +static string g_testDhModp8192PubKey = "-----BEGIN PUBLIC KEY-----\n" + "MIIIJDCCBBcGCSqGSIb3DQEDATCCBAgCggQBAP//////////yQ/aoiFowjTExmKL\n" + "gNwc0SkCTgiKZ8x0Agu+pjsTmyJRSgh5jjQE3e+VGbPNOkMbMCsKbfJfFDdP4TVt\n" + "bVHCReSFtXZiXn7G9ExC6aY37WsL/1y29Aa37e44a/taiZ+lrp8kEXxLH+ZJKGZR\n" + "7ORbPcIAfLihY78FmNpINhxV05ppFj+o/STPX4NlXSPco62WHGLzViCFUrue1SkH\n" + "cJaWbWcMNU5KvJgE8XRsCMoYIXwykF5GLjbOO+OedywYDoYDmyeDouwHoo+1xV3w\n" + "b0xSyd4ry/aVWBcYOZVJfOqVauUV0iYYmPoFEBVyjlqKqsQtrTMXDQRQejOoVSGr\n" + "3xy6ZOz7hQRY2+8KiupxV10GDH2zlw+FpuHkx6v1rozbCTPXHoyU4EolYZ3O49Im\n" + "GtLua/Ev+gbZighk2HYCcz7IamRSHysYF3sgDLvhF1d6YV1sdwmIwLrZRuII4k+g\n" + "dOWrMUPbW/zg/RCOS4LRIKkhCAEacjwSp4fm14hxmhC9ulsmmcMnGGr04jwalGg0\n" + "thUL2iWD6coq1Ezo27vC2wTejvkujvwUH77Kpih8WUdOa8BdmbKWT6CQw6IjO6GG\n" + "UVvn7R9hKXDO4tevuBvddiFwSBzQBpEn1bBaqZO06piNj93Bhv+33JCmwI9N9DXJ\n" + "NAKEkjbD+rTSfHAmwdTcsmAmRt7JdR52Pbo3vfj/lAatnlMO5ds4L0EwAa6walPt\n" + "kCfYMReXJ7CGWokY2j7b68+bFO1Ezmy6ztS7G9t/FEfmzCVLMyBRUSvXr0JvuPQB\n" + "N4zSv1mDygHGS5Ls8DLqFdFyHQP0gtfObnT+9tVecC9GmAyCtahAMZALHJ5Z58l/\n" + "vsfo8yOpen42zIi+Dx1Ft/9YWsVL1AeyK0FUqsyPbX6/SOHYFMxe0g+AN+CnlxXu\n" + "8pvjKAah1Yu3xdp29VCqPYofv/DrGcyxoxPVXNpWyewu8pYyOH/o1248BGgEPo9m\n" + "P0hg7hK/LVsLdHTW5pT5Hm2+EVl0o5JvEv7l5Dh3fLapMt+M2L7E0HO5Mbo7yDK2\n" + "jZ3TAHQfp7+K/EftJXb2k2ukJGY6q2OcWuT1aDQjtHQr8cl4I48Wy+OdZS3j/bi+\n" + "/ISK2SIiLgSkA3wHE+tXqBoj8Mc0c/xkbOowa0vLyIYvg4Xd+p1Lf6LAh+h5aDMD\n" + "7VvdOgYrPPWzonimbSoT+D9E+C3fMQ7gdKtqNkWX6JmgJV3BZPMcxQhGhR35q0gZ\n" + "Xe1+obHVEL1+501z+vNrwx7Pomg1kEb064efkkAJQ4tIHGzXiJoALtXuOCvJGQ2m\n" + "/AJuR5VY5EdWd+mqnjBQ4nZWlN/IH1bogLlucWDJgN2Y7dPf//////////8CAQID\n" + "ggQFAAKCBAB6skc5bwB1kCSZx9QV53rVicQu8L4Gt1qtYJoHNICF6u0H0vzM0arj\n" + "emLcV6L1h+CVykAUoCTX3EJcClkjE4gi80A6mJ3IZ4FOZObG98lrs/Ha653WpFyG\n" + "hYYGwHEE8i1gRwLK80cDSESkcxZJdB9BVyZpwtpUfrGbkt1Bh7fC33CYvK9Px0CZ\n" + "8LWKii/nyn6q9d6z4veGOgcJI590NEuNnrX5FedC1UkQcG0207YOOFoSXZ5WHOvb\n" + "m+807q8rLt4/YCpN4yzbfknxz4VQgRNchmhRQ4kGiCdmVuiAgIVF55emrNGK6Z0m\n" + "OtnpPo5BjK75yvDfWMURGhbr1TlpK26hxsinZYhcy0KH7HjKHB4i+4MQcMgxlRfj\n" + "8ePBYwEeJtzutP0u6BhdQ7Y2Wh+mdCi1HdvMKuspswpyPVPnvezrLh+xQ7WzatI5\n" + "i1dATcFxfAy88Z7yCCmzXYIl1/iljzATxgORdnNtXjvtT+mcLlDBLQMrmi5ZaRn4\n" + "wJgONdlTQlTRzopKLK5zmnZnVPNYDU2yjI6R5R5KJkI3Q+hdMrs6ssIEpkzED3g4\n" + "kpNABcS9vzGr303mbgfs0HR0Low4NoggmTQVMhmZo1PsKt5cL5cNk60Yirzvm3S+\n" + "k8WxVAuMwcDjBsFRO825FyaAPJ4ZnrPomQIHdsGxkLHvZWNvnryI1/GE9aWNM+5N\n" + "Pk/uhQeatK2zV4+/AmqHEvQkQ5Khd3XIOAt8+BT344cSjCcl5bGl3nz3ry8y0mPo\n" + "DECOvisp5hJkYeDYlW8ai45xDjklah7qekS9BBKpEHW8hMp1OojHrtnfS5MXN+Bf\n" + "imAkw7a0n/9c8q4XfvQLDpOkyWNar+Wq9D4zfHcqu0JAneDwhnS+O1g/lCJYQygg\n" + "pck4RkVz2K3ObjuNYc/VKmdnSZYU9bBKAXUJMOYJi2Gag6IP381tQI26VzBbwEff\n" + "xFAsnkscbztukiknM5bCvSekWphW8t5ghMQbB6/5dROgo5+M5OdG5G2lDa1aKjmL\n" + "urLui37vKOcfvKZm+y0DifTSt2/ljZULtJO5E+Lp/WqWTB8rJLcxFbSfgr9CqgZN\n" + "lIyRF6Wdovi75U5eWfP0uWK7vuc2rfxQtPiEHAC16DrFqUKZN9DprNXjU5mwqf9t\n" + "IWoeXS1uEIHZE2zQee9VPzKXQIOrXNONPdw2DY7a9d3ScFaoxDs3I7YbZ8GrjHum\n" + "eyNf+5LGJqzuvpCzb6defkeWP8sMkdTpby4qM86OW42Jvl27Z9GsPjB3ee6YiHMj\n" + "4BCVsldbYN4iGQqsovsXQagdVFZdHSemeuiByJTcJRKE0pPUhbCpl9ndFTQ7Ah23\n" + "0wF19uLDbk10PhmuiWORmIO27t9Ps6iu\n" + "-----END PUBLIC KEY-----\n"; + +static string g_testDsa2048Prikey = "-----BEGIN PRIVATE KEY-----\n" + "MIICXAIBADCCAjUGByqGSM44BAEwggIoAoIBAQDPXEvnKzvLwPGASwVMsFMI4JgW\n" + "FaKAjDi9c194Nt71Fpo3zNPNikXXKoHEqJYRF1EVzzlmkiARhE9hwAESuKgK3oJP\n" + "/Aygovtr5+pwo16E9LqR3/t2Qp2ZENs45BGQ+DrwUr6S55T3Mo3NyMsbr3SDKsZY\n" + "eFnsN2A67i4jbQpVvJL+fAvWUgGuEIXIa5oQJ1LokQ0iBarXVJ5tu+JLVjgqkQnW\n" + "1iWA24xkMq2NOWUDgcWjPxrVW8TPuuaB6cKMKDT6t8zRVrCGBxThF7RBGWWWOYev\n" + "CQ7lbSAkDYZFzKqFt4DRj3NuWXFlrqdxrOHrd74StAA7HuU8i+5T7ExI5ir7Ah0A\n" + "+ujqphLK8rDnXYwlgVE2OouAIPaM/e7VPql9qwKCAQBeSv4sbWm4Ru6j35i2W4+a\n" + "Fq7uSdF5P93xruLI+u4a/h7nZVHbXUP7kET5oNbbSRzmxaSQtlFhDJZMFjSHxAme\n" + "6Cl/sa+RYK0gpDqccWo2+e1QeEv3+4t5HmYevWY7blehaB3ITySHB586E86Rl4+r\n" + "kqvnI7Mh2wFEZGknrRi+oZLTr5PZti2nd+ouPVMNl8l3T6oZcXUO1wUSMFY3yExO\n" + "fh66W2wqp9wvSyVUM7T06MKHQ/e6T2+7VUIXhnorDYldtkWJla4X6zuSaryFeKZo\n" + "XPno390zxFukACbLgM5R/9RqTVynmJc4wx+ixCvei3hB2keHlenGQEVJXJtZf56m\n" + "BB4CHDze5XQTmFMIAFjht3dyZGMtO5PqvxJOnVHwnKk=\n" + "-----END PRIVATE KEY-----\n"; + +static string g_testDsa3072Prikey = "-----BEGIN PRIVATE KEY-----\n" + "MIIDXgIBADCCAzYGByqGSM44BAEwggMpAoIBgQCjDOJwnOl9/hQ/CviGJvA3BTDA\n" + "IqlmaFJMSQzF4rp28YzW6P2+3ssi/vzGjnA+7O1ZdZV1xchkO0sPDF9lEKGNUnRb\n" + "eM0IgVkfV2Bdjqn7y0o+q6NoiaNLbMuyEiGaNKhzfoP9x8NDlSd+W/d4jwYg+JF0\n" + "4gCXpNXCMatcbviDzYGbun1rL5sTKltApYKCCMtyvf9AcUsN0RyXjo9TSXP750C9\n" + "3T6FeuCsDGXniwtIghIIDCHBOCvkHwEu/zueicAAPaHP9iipgZ3wO33ToaUdYqdl\n" + "8OPFu9JMgKLpJNwT9PhtBf6inOsVb4udVJmXFQ7UHdszo4yDkyUW4ob8qJ1RwKyj\n" + "q3ZfJ5Y2kilbH0Nphpyg3FJyAzDPofhj33sFUfKJkRHwOzf+xwszjKuLbLIjDHvm\n" + "8mudFhzSFqFiKyRqS97lGcK2T4SahSn8lZ+P9kyRZuZCpXw8GJIcbLJSgZWfaQvh\n" + "aI2WMWS8ggQwxn7gz4W5QGQ/R29dIvCZPqr3+qECHQDkpzzLWcDIHmmqIrLZH8Nt\n" + "u+3Q0XQBQtaZOWnVAoIBgQCDuEO0G8cE7n4txT/T17RmzTEILRPc2+2mmvcPFYDc\n" + "uS1mC8838zXU3VM1juVP/vpuTdPi01D7yQIb23jjb77n4roAwsflQvY5fc6sBBOJ\n" + "/BjJcF9CLHRBgTXknYgN4qSZx8+X7/w8A22JEC4u6gMQKLPwnEJdK/fx51tnqVYY\n" + "lK9sTeAuGLdsD5CbJzgqXNRlS0JGGyw2CmGQKwTPybLYQcHnB2ZnYunOSGyrsZB7\n" + "suVlJ5OfLwdN0or06wltu9yv2Tz+74d5Kdessx4sSfgZ4yDtcXLYCKMPJjI2cLH0\n" + "lgZ7msfBYcPmk8L8hPWq2GDWTONdpngdiEk8fRwWsHRM4jvfxoMv1lmoK7F9VTUd\n" + "BLzgYka+/xIIfQB5VBXZrHaGQnbGLZRoWYPHeLuh21wxSwmoB8YFZQs2umOSBJm7\n" + "sJP1UZM7DYCZSe4QRmsTrwdhlvdd4tNsxHKGnZXMQNBgSJGPL5ag5+8Z6wEPoIo4\n" + "0EO1ILw13ufx/qBlcNZjLZQEHwIdAMr8b91HR/l73ek2RWENJsV0YLng7R1mj+Jm\n" + "sbg=\n" + "-----END PRIVATE KEY-----\n"; + +static string g_testDsa2048PubKey = "-----BEGIN PUBLIC KEY-----\n" + "MIIDQjCCAjUGByqGSM44BAEwggIoAoIBAQDPXEvnKzvLwPGASwVMsFMI4JgWFaKA\n" + "jDi9c194Nt71Fpo3zNPNikXXKoHEqJYRF1EVzzlmkiARhE9hwAESuKgK3oJP/Ayg\n" + "ovtr5+pwo16E9LqR3/t2Qp2ZENs45BGQ+DrwUr6S55T3Mo3NyMsbr3SDKsZYeFns\n" + "N2A67i4jbQpVvJL+fAvWUgGuEIXIa5oQJ1LokQ0iBarXVJ5tu+JLVjgqkQnW1iWA\n" + "24xkMq2NOWUDgcWjPxrVW8TPuuaB6cKMKDT6t8zRVrCGBxThF7RBGWWWOYevCQ7l\n" + "bSAkDYZFzKqFt4DRj3NuWXFlrqdxrOHrd74StAA7HuU8i+5T7ExI5ir7Ah0A+ujq\n" + "phLK8rDnXYwlgVE2OouAIPaM/e7VPql9qwKCAQBeSv4sbWm4Ru6j35i2W4+aFq7u\n" + "SdF5P93xruLI+u4a/h7nZVHbXUP7kET5oNbbSRzmxaSQtlFhDJZMFjSHxAme6Cl/\n" + "sa+RYK0gpDqccWo2+e1QeEv3+4t5HmYevWY7blehaB3ITySHB586E86Rl4+rkqvn\n" + "I7Mh2wFEZGknrRi+oZLTr5PZti2nd+ouPVMNl8l3T6oZcXUO1wUSMFY3yExOfh66\n" + "W2wqp9wvSyVUM7T06MKHQ/e6T2+7VUIXhnorDYldtkWJla4X6zuSaryFeKZoXPno\n" + "390zxFukACbLgM5R/9RqTVynmJc4wx+ixCvei3hB2keHlenGQEVJXJtZf56mA4IB\n" + "BQACggEAH9bSRnDNxEOC2oQl7dUO++NWwF4hpmx7z6zeYSN/ViGaFkl0cytASaKw\n" + "sKXtKjmwQogxNO/eE2q2R0UsB8CCtyJ6LeiIo6yv81gWopI+ZtFgr67vFHcx8q8D\n" + "jlkmy6gvt7iB8cPn8Mp95KDPHqlqgeMguxZs5uLucRJ0WS1YFWMqTGiCuH4SYrph\n" + "NtmTNScnlxco4vwxLWRjejWpy+PJF+6XpvSnIp88ARTrpqPEy9xcM1Cr5NJqO3qT\n" + "C4Gyt3FtSTC/R2iRm3IrLHMoJjSdbgXnX9LhvVOOzWyPtxe78/tUh3NsC0kI0IdG\n" + "HSTT3iq3yULgcAmq/+o02x4FYZq/2A==\n" + "-----END PUBLIC KEY-----\n"; + +static string g_testDsa3072PubKey = "-----BEGIN PUBLIC KEY-----\n" + "MIIEwzCCAzYGByqGSM44BAEwggMpAoIBgQCjDOJwnOl9/hQ/CviGJvA3BTDAIqlm\n" + "aFJMSQzF4rp28YzW6P2+3ssi/vzGjnA+7O1ZdZV1xchkO0sPDF9lEKGNUnRbeM0I\n" + "gVkfV2Bdjqn7y0o+q6NoiaNLbMuyEiGaNKhzfoP9x8NDlSd+W/d4jwYg+JF04gCX\n" + "pNXCMatcbviDzYGbun1rL5sTKltApYKCCMtyvf9AcUsN0RyXjo9TSXP750C93T6F\n" + "euCsDGXniwtIghIIDCHBOCvkHwEu/zueicAAPaHP9iipgZ3wO33ToaUdYqdl8OPF\n" + "u9JMgKLpJNwT9PhtBf6inOsVb4udVJmXFQ7UHdszo4yDkyUW4ob8qJ1RwKyjq3Zf\n" + "J5Y2kilbH0Nphpyg3FJyAzDPofhj33sFUfKJkRHwOzf+xwszjKuLbLIjDHvm8mud\n" + "FhzSFqFiKyRqS97lGcK2T4SahSn8lZ+P9kyRZuZCpXw8GJIcbLJSgZWfaQvhaI2W\n" + "MWS8ggQwxn7gz4W5QGQ/R29dIvCZPqr3+qECHQDkpzzLWcDIHmmqIrLZH8Ntu+3Q\n" + "0XQBQtaZOWnVAoIBgQCDuEO0G8cE7n4txT/T17RmzTEILRPc2+2mmvcPFYDcuS1m\n" + "C8838zXU3VM1juVP/vpuTdPi01D7yQIb23jjb77n4roAwsflQvY5fc6sBBOJ/BjJ\n" + "cF9CLHRBgTXknYgN4qSZx8+X7/w8A22JEC4u6gMQKLPwnEJdK/fx51tnqVYYlK9s\n" + "TeAuGLdsD5CbJzgqXNRlS0JGGyw2CmGQKwTPybLYQcHnB2ZnYunOSGyrsZB7suVl\n" + "J5OfLwdN0or06wltu9yv2Tz+74d5Kdessx4sSfgZ4yDtcXLYCKMPJjI2cLH0lgZ7\n" + "msfBYcPmk8L8hPWq2GDWTONdpngdiEk8fRwWsHRM4jvfxoMv1lmoK7F9VTUdBLzg\n" + "Yka+/xIIfQB5VBXZrHaGQnbGLZRoWYPHeLuh21wxSwmoB8YFZQs2umOSBJm7sJP1\n" + "UZM7DYCZSe4QRmsTrwdhlvdd4tNsxHKGnZXMQNBgSJGPL5ag5+8Z6wEPoIo40EO1\n" + "ILw13ufx/qBlcNZjLZQDggGFAAKCAYBo6EVks/SjgbT0WYsrCIZbvKPkqccsg+Fd\n" + "veKz9eUpJpo93EfZgDqMNka8zSzo4vO7fYJPgxw+YkPVCzdtCqxKJLvDeSsogQ/j\n" + "1LGyuVoOdXU4E1SHgKTtkviKU2zCJoSE6/gH3i9cfaVvBpr1kiQV5isDJb02Wqh8\n" + "bq1skTVoy+eg6x75mPrd5eRmzQiDOmWtkwfxfBC2ybeXBsS39DsqDXAfTRC0kaK8\n" + "Od2KSM0btuZatIo28Qw65io2ABbTW973BwJ3uKhWgaVoBIwzvsyYd6FfSpWEQ36A\n" + "u7kiGH5QltjvTVtoOlSnV8U+g2S+6X2mMhfVz6TUOWf1E4d6jLZ9Oet5gap8aJ2M\n" + "NbYpNxnyfFIG9q0RAVqPUAddvW5hOypCeIXUuLIz2c+tHIvWcwlOomrv0e4K1jgP\n" + "Egh1ccqwqqiM+Pz57SAIYdsN+sDxanWK9IUBpNQmCtbhRhVgt8PzbFVoBKs5wFbj\n" + "J5CGPcuzhta1Ju41XMtRHHigBtL62r4=\n" + "-----END PUBLIC KEY-----\n"; + +static string g_testEccP160r1PriKey = "-----BEGIN PRIVATE KEY-----\n" + "MGQCAQAwFAYHKoZIzj0CAQYJKyQDAwIIAQEBBEkwRwIBAQQUASO/LfZI7/oU61jD\n" + "jI3iN3daCsKhLAMqAAR9QXIl11ePlAzVlwjLUnkKjxX6LBAU4Q0sOo1eeDM+nEg5\n" + "XenI3o1+\n" + "-----END PRIVATE KEY-----\n"; + +static string g_testEccP160r1PubKey = "-----BEGIN PUBLIC KEY-----\n" + "MEIwFAYHKoZIzj0CAQYJKyQDAwIIAQEBAyoABH1BciXXV4+UDNWXCMtSeQqPFfos\n" + "EBThDSw6jV54Mz6cSDld6cjejX4=\n" + "-----END PUBLIC KEY-----\n"; + +static string g_testEccP160t1PriKey = "-----BEGIN PRIVATE KEY-----\n" + "MGQCAQAwFAYHKoZIzj0CAQYJKyQDAwIIAQECBEkwRwIBAQQU3/XiFisN/54Kj4nQ\n" + "Bwjr1dceZQihLAMqAATKWOgm/tH+UYnAv8hs/Y/D34fMv4BwU4k3/Z+gRBKRN4cy\n" + "ypd5NiES\n" + "-----END PRIVATE KEY-----\n"; + +static string g_testEccP160t1PubKey = "-----BEGIN PUBLIC KEY-----\n" + "MEIwFAYHKoZIzj0CAQYJKyQDAwIIAQECAyoABMpY6Cb+0f5RicC/yGz9j8Pfh8y/\n" + "gHBTiTf9n6BEEpE3hzLKl3k2IRI=\n" + "-----END PUBLIC KEY-----\n"; + +static string g_testEccP192r1PriKey = "-----BEGIN PRIVATE KEY-----\n" + "MHACAQAwFAYHKoZIzj0CAQYJKyQDAwIIAQEDBFUwUwIBAQQYZJ2mohQak6UuCZdW\n" + "Ox8uUsOp70Pg2T0+oTQDMgAEezNHhaP+k9qgeQ/9ZHAc/AhkWrGNJ8AjwFqrj4lc\n" + "EyDnCz3QxK3MEmfPxkhlNXWb\n" + "-----END PRIVATE KEY-----\n"; + +static string g_testEccP192r1PubKey = "-----BEGIN PUBLIC KEY-----\n" + "MEowFAYHKoZIzj0CAQYJKyQDAwIIAQEDAzIABHszR4Wj/pPaoHkP/WRwHPwIZFqx\n" + "jSfAI8Baq4+JXBMg5ws90MStzBJnz8ZIZTV1mw==\n" + "-----END PUBLIC KEY-----\n"; + +static string g_testEccP192t1PriKey = "-----BEGIN PRIVATE KEY-----\n" + "MHACAQAwFAYHKoZIzj0CAQYJKyQDAwIIAQEEBFUwUwIBAQQYG9Qnpo0Mnsc038+F\n" + "8cL9eend4xNz6blPoTQDMgAECrDcmHkXtKe1+TKqYtM2jfe805qYBR7kgBWmEmJN\n" + "KAfv8Oo+/1u/VpNe2nYBURRn\n" + "-----END PRIVATE KEY-----\n"; + +static string g_testEccP192t1PubKey = "-----BEGIN PUBLIC KEY-----\n" + "MEowFAYHKoZIzj0CAQYJKyQDAwIIAQEEAzIABAqw3Jh5F7SntfkyqmLTNo33vNOa\n" + "mAUe5IAVphJiTSgH7/DqPv9bv1aTXtp2AVEUZw==\n" + "-----END PUBLIC KEY-----\n"; + +static string g_testEccP224r1PriKey = "-----BEGIN PRIVATE KEY-----\n" + "MHwCAQAwFAYHKoZIzj0CAQYJKyQDAwIIAQEFBGEwXwIBAQQcjRIweUszgw6kye8e\n" + "uH+EDixtMWACgjAFKLlD86E8AzoABKJPILw4pJ703KZWzwCiU2WIZgaxlHo3M/LI\n" + "hOuGsmvnaBmH6nfTt4E7NqHkgBnJVNTmELXpPDt2\n" + "-----END PRIVATE KEY-----\n"; + +static string g_testEccP224r1PubKey = "-----BEGIN PUBLIC KEY-----\n" + "MFIwFAYHKoZIzj0CAQYJKyQDAwIIAQEFAzoABKJPILw4pJ703KZWzwCiU2WIZgax\n" + "lHo3M/LIhOuGsmvnaBmH6nfTt4E7NqHkgBnJVNTmELXpPDt2\n" + "-----END PUBLIC KEY-----\n"; + +static string g_testEccP224t1PriKey = "-----BEGIN PRIVATE KEY-----\n" + "MHwCAQAwFAYHKoZIzj0CAQYJKyQDAwIIAQEGBGEwXwIBAQQc0FrhunNRyAF63WWu\n" + "RnlazhSV2vURHyWcGu6deKE8AzoABIdtC73AhzV0Jr90EHl9DHuyQfsrb9917sCj\n" + "+4YGoKqXTKp8Ww4dc1dDIxd9FKyz9J///x1RUqUn\n" + "-----END PRIVATE KEY-----\n"; + +static string g_testEccP224t1PubKey = "-----BEGIN PUBLIC KEY-----\n" + "MFIwFAYHKoZIzj0CAQYJKyQDAwIIAQEGAzoABIdtC73AhzV0Jr90EHl9DHuyQfsr\n" + "b9917sCj+4YGoKqXTKp8Ww4dc1dDIxd9FKyz9J///x1RUqUn\n" + "-----END PUBLIC KEY-----\n"; + +static string g_testEccP256r1PriKey = "-----BEGIN PRIVATE KEY-----\n" + "MIGIAgEAMBQGByqGSM49AgEGCSskAwMCCAEBBwRtMGsCAQEEIGEWmKHlX2Q7RNcn\n" + "TjcbiQO83eOZdeohwj6GrZTswNZYoUQDQgAELXkxbTULz0F0MP9if30WZ2SUw3Sz\n" + "Oht9darQcWO6fzUlHzJPAz//wv+narhYYYGO9c9K7YTGSUPA9x3G4l31rA==\n" + "-----END PRIVATE KEY-----\n"; + +static string g_testEccP256r1PubKey = "-----BEGIN PUBLIC KEY-----\n" + "MFowFAYHKoZIzj0CAQYJKyQDAwIIAQEHA0IABC15MW01C89BdDD/Yn99FmdklMN0\n" + "szobfXWq0HFjun81JR8yTwM//8L/p2q4WGGBjvXPSu2ExklDwPcdxuJd9aw=\n" + "-----END PUBLIC KEY-----\n"; + +static string g_testEccP256t1PriKey = "-----BEGIN PRIVATE KEY-----\n" + "MIGIAgEAMBQGByqGSM49AgEGCSskAwMCCAEBCARtMGsCAQEEICKa3/xdoohLWjrn\n" + "mR/5Iyb8yyb6FPAa9R4vTa6x53b+oUQDQgAEgeCO46sHVnF8StJg7SiKW/Nwbw76\n" + "Nai8MrlYN8axQN9oEgwrTNVzu0M4X2fquIxI8i52Rp+/iPL50zE8UI4RKA==\n" + "-----END PRIVATE KEY-----\n"; + +static string g_testEccP256t1PubKey = "-----BEGIN PUBLIC KEY-----\n" + "MFowFAYHKoZIzj0CAQYJKyQDAwIIAQEIA0IABIHgjuOrB1ZxfErSYO0oilvzcG8O\n" + "+jWovDK5WDfGsUDfaBIMK0zVc7tDOF9n6riMSPIudkafv4jy+dMxPFCOESg=\n" + "-----END PUBLIC KEY-----\n"; + +static string g_testEccP320r1PriKey = "-----BEGIN PRIVATE KEY-----\n" + "MIGiAgEAMBQGByqGSM49AgEGCSskAwMCCAEBCQSBhjCBgwIBAQQoQg1ccOHTcKft\n" + "H7HYc+bMzIqlWs76bfL9ie1Z7AvZaCHTxdvkXkSnzKFUA1IABA+GdgqTHGQORU7c\n" + "oz/8036686oDnSs8kMjNQ4GIdGHcwXiurGviJmO/T+yJAU2wqiTefWGjOpNVzOMJ\n" + "HHnad3xgbzrevv5ajO6PUHeI14OP\n" + "-----END PRIVATE KEY-----\n"; + +static string g_testEccP320r1PubKey = "-----BEGIN PUBLIC KEY-----\n" + "MGowFAYHKoZIzj0CAQYJKyQDAwIIAQEJA1IABA+GdgqTHGQORU7coz/8036686oD\n" + "nSs8kMjNQ4GIdGHcwXiurGviJmO/T+yJAU2wqiTefWGjOpNVzOMJHHnad3xgbzre\n" + "vv5ajO6PUHeI14OP\n" + "-----END PUBLIC KEY-----\n"; + +static string g_testEccP320t1PriKey = "-----BEGIN PRIVATE KEY-----\n" + "MIGiAgEAMBQGByqGSM49AgEGCSskAwMCCAEBCgSBhjCBgwIBAQQoNBUB9bYEND/J\n" + "Aa/5LWOwPFVAteMc06veS4FgGuyhTXxwGFJuwvGx56FUA1IABDdabgr6v4yG2hLZ\n" + "2zTxP2+vKDwVJaHvBQ8StEkkfYKzKus5hUILOQTEbpi6/ODPw0ZRC1+uK87IuPMu\n" + "1DnWIRvDUrSFCcjURCTAwudMTt5y\n" + "-----END PRIVATE KEY-----\n"; + +static string g_testEccP320t1PubKey = "-----BEGIN PUBLIC KEY-----\n" + "MGowFAYHKoZIzj0CAQYJKyQDAwIIAQEKA1IABDdabgr6v4yG2hLZ2zTxP2+vKDwV\n" + "JaHvBQ8StEkkfYKzKus5hUILOQTEbpi6/ODPw0ZRC1+uK87IuPMu1DnWIRvDUrSF\n" + "CcjURCTAwudMTt5y\n" + "-----END PUBLIC KEY-----\n"; + +static string g_testEccP384r1PriKey = "-----BEGIN PRIVATE KEY-----\n" + "MIG6AgEAMBQGByqGSM49AgEGCSskAwMCCAEBCwSBnjCBmwIBAQQwf+M859VdL3Cx\n" + "DUQ6xzEpPbgmHhlMa9veRNok/VlKFwHs7gUpirvA+vzCz1sJA0ePoWQDYgAEgYsV\n" + "W0pKIDXz4qWgvqkFLD6yB+99GvXDnMKRQPIHcSOfAnThZtr5LJH/xXMNs29aez3a\n" + "TqgYmVtiAQgM+C6shAaqqj6qZoE0ACSgemVKHxV065JStQts9xfqhK2QOey9\n" + "-----END PRIVATE KEY-----\n"; + +static string g_testEccP384r1PubKey = "-----BEGIN PUBLIC KEY-----\n" + "MHowFAYHKoZIzj0CAQYJKyQDAwIIAQELA2IABIGLFVtKSiA18+KloL6pBSw+sgfv\n" + "fRr1w5zCkUDyB3EjnwJ04Wba+SyR/8VzDbNvWns92k6oGJlbYgEIDPgurIQGqqo+\n" + "qmaBNAAkoHplSh8VdOuSUrULbPcX6oStkDnsvQ==\n" + "-----END PUBLIC KEY-----\n"; + +static string g_testEccP384t1PriKey = "-----BEGIN PRIVATE KEY-----\n" + "MIG6AgEAMBQGByqGSM49AgEGCSskAwMCCAEBDASBnjCBmwIBAQQwaPOGmvKk9UPa\n" + "GnpoWTpvs2gmq5C1CC8pMc8aVFPWY4yhUszcnYiIuIMfs+AzMo6CoWQDYgAEdemX\n" + "VIj45zsc/28xYiSObxmuf4OskgIvBrptXx8DwJMOmZvFawXswxZErzv13gvmcPMd\n" + "rif01/fGgrr/QTQAKx8l/5TkECkHdOflHS84Wy2h1mkbb3KFJH7Opm5JMmtw\n" + "-----END PRIVATE KEY-----\n"; + +static string g_testEccP384t1PubKey = "-----BEGIN PUBLIC KEY-----\n" + "MHowFAYHKoZIzj0CAQYJKyQDAwIIAQEMA2IABHXpl1SI+Oc7HP9vMWIkjm8Zrn+D\n" + "rJICLwa6bV8fA8CTDpmbxWsF7MMWRK879d4L5nDzHa4n9Nf3xoK6/0E0ACsfJf+U\n" + "5BApB3Tn5R0vOFstodZpG29yhSR+zqZuSTJrcA==\n" + "-----END PUBLIC KEY-----\n"; + +static string g_testEccP512r1PriKey = "-----BEGIN PRIVATE KEY-----\n" + "MIHsAgEAMBQGByqGSM49AgEGCSskAwMCCAEBDQSB0DCBzQIBAQRAjQ8+FR54Dggv\n" + "o5bICxr+k+6fjjeakaYFxwaqlVtznmLdX9WqantFAld3mSRI0fEwa8quplRS/SO1\n" + "egRx/i/CbKGBhQOBggAEdtNym0AqquTwWqRH8ardukuoopQQu3dbq30IWsZfyx/h\n" + "ZLMNJWpLVMKcIg0F/qccFlqKvj3kMy6c7keIAMkBKXeCJ+6NKM3cgcKr1crfvagC\n" + "mbAjSHsKXQRLIk3WCxL4xqXk+GC/Na64lsUnqDIw/ieztxmhkT9O5zLdW6qAKhI=\n" + "-----END PRIVATE KEY-----\n"; + +static string g_testEccP512r1PubKey = "-----BEGIN PUBLIC KEY-----\n" + "MIGbMBQGByqGSM49AgEGCSskAwMCCAEBDQOBggAEdtNym0AqquTwWqRH8ardukuo\n" + "opQQu3dbq30IWsZfyx/hZLMNJWpLVMKcIg0F/qccFlqKvj3kMy6c7keIAMkBKXeC\n" + "J+6NKM3cgcKr1crfvagCmbAjSHsKXQRLIk3WCxL4xqXk+GC/Na64lsUnqDIw/iez\n" + "txmhkT9O5zLdW6qAKhI=\n" + "-----END PUBLIC KEY-----\n"; + +static string g_testEccP512t1PriKey = "-----BEGIN PRIVATE KEY-----\n" + "MIHsAgEAMBQGByqGSM49AgEGCSskAwMCCAEBDgSB0DCBzQIBAQRAhSMiRfKXVUGS\n" + "hMiCfkdszV0TmdWib5WIoNFKyHQGgtt8kZcXl5NX84SsoO28leLDJ9fSd1qV/Dwq\n" + "+INCiNKnGaGBhQOBggAEKGhHCsQ5qabxssAoCZiEZT9wxdTOliHqv+mStkwQRPZD\n" + "Or4uSUqGTQHXUWY/9+J3fMnvws7uf9p9GnRB9rpHL2K/NkiviW+hX+ikIuyT7nGr\n" + "jPT8olwleVaidVbgPjLtliZV98evrcZKZ/x1plcWX7l8I2Bhg5845fximjWUvQU=\n" + "-----END PRIVATE KEY-----\n"; + +static string g_testEccP512t1PubKey = "-----BEGIN PUBLIC KEY-----\n" + "MIGbMBQGByqGSM49AgEGCSskAwMCCAEBDgOBggAEKGhHCsQ5qabxssAoCZiEZT9w\n" + "xdTOliHqv+mStkwQRPZDOr4uSUqGTQHXUWY/9+J3fMnvws7uf9p9GnRB9rpHL2K/\n" + "NkiviW+hX+ikIuyT7nGrjPT8olwleVaidVbgPjLtliZV98evrcZKZ/x1plcWX7l8\n" + "I2Bhg5845fximjWUvQU=\n" + "-----END PUBLIC KEY-----\n"; + +static string g_testEccPrime256v1PriKey = "-----BEGIN PRIVATE KEY-----\n" + "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgrwZLoHLb9awzKiT1\n" + "5/FXrItjgIExhDon3mGVrVHllqahRANCAAQCOkE1Xx5YKUjKGaN86zL5JO6irKe9\n" + "XXjC3kashJ7fYzLkrkIuHyuqEM7hvmw0F7w/DrUkonPgCN+t395C9/EW\n" + "-----END PRIVATE KEY-----\n"; + +static string g_testEccPrime256v1PubKey = "-----BEGIN PUBLIC KEY-----\n" + "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEAjpBNV8eWClIyhmjfOsy+STuoqyn\n" + "vV14wt5GrISe32My5K5CLh8rqhDO4b5sNBe8Pw61JKJz4Ajfrd/eQvfxFg==\n" + "-----END PUBLIC KEY-----\n"; + +static string g_testEccSecp384r1PriKey = "-----BEGIN PRIVATE KEY-----\n" + "MIG2AgEAMBAGByqGSM49AgEGBSuBBAAiBIGeMIGbAgEBBDBq2KueaDvMuB0n7Wd3\n" + "s5vThqu5wxBIdN3BzE12+RzqL+Q+iqzPuHS4YE11syurz9ahZANiAAQ86CZ+Fvmm\n" + "w36OiBIx412pYe+HWd2TBCkWr5p6tIKcdszG0AhMxPkgzjAtrSUHg+/rsd5TWSdx\n" + "B0SmbWQTcukqrdb8ITAkgmk4HUjQ85TjWXDokYK5wXWE0fWV5BpzkZ4=\n" + "-----END PRIVATE KEY-----\n"; + +static string g_testEccSecp384r1PubKey = "-----BEGIN PUBLIC KEY-----\n" + "MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEPOgmfhb5psN+jogSMeNdqWHvh1ndkwQp\n" + "Fq+aerSCnHbMxtAITMT5IM4wLa0lB4Pv67HeU1kncQdEpm1kE3LpKq3W/CEwJIJp\n" + "OB1I0POU41lw6JGCucF1hNH1leQac5Ge\n" + "-----END PUBLIC KEY-----\n"; + +static string g_testEccSecp521r1PriKey = "-----BEGIN PRIVATE KEY-----\n" + "MIHuAgEAMBAGByqGSM49AgEGBSuBBAAjBIHWMIHTAgEBBEIByYx3SSpA7rou1Fpa\n" + "I4ySKDxaJHPXrlM/C/0WFG9UboT6vjvpp3BA4CrkE5FH8hP3ouUbkAFDMvSJbkL1\n" + "paUdOB2hgYkDgYYABACEkXDyF6CWltw6eN83x4x0NbZpncw2iwuZBC/nIR9+scXp\n" + "+Gj48ft8F9Er+CrtQEvNwz1PGWVTk+dnpJ/ztlfu4ADhyb5B9GWtwNi4D+rgHtYX\n" + "LlsthM8GGlAbuMIV0y/QTqqtwYFEJwBVwopsVn1rjWnFxIaZRcEJa6dwM58+sLYc\n" + "Ng==\n" + "-----END PRIVATE KEY-----\n"; + +static string g_testEccSecp521r1PubKey = "-----BEGIN PUBLIC KEY-----\n" + "MIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQAhJFw8heglpbcOnjfN8eMdDW2aZ3M\n" + "NosLmQQv5yEffrHF6fho+PH7fBfRK/gq7UBLzcM9TxllU5PnZ6Sf87ZX7uAA4cm+\n" + "QfRlrcDYuA/q4B7WFy5bLYTPBhpQG7jCFdMv0E6qrcGBRCcAVcKKbFZ9a41pxcSG\n" + "mUXBCWuncDOfPrC2HDY=\n" + "-----END PUBLIC KEY-----\n"; + +static void AsyKeyConvertPemTest(const char *algoName, const char *pubKey, const char *priKey) +{ + HcfAsyKeyGenerator *generator = nullptr; + HcfResult res = HcfAsyKeyGeneratorCreate(algoName, &generator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(generator, nullptr); + + HcfKeyPair *dupKeyPair = nullptr; + res = generator->convertPemKey(generator, nullptr, pubKey, priKey, &dupKeyPair); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(dupKeyPair, nullptr); + + HcfKeyPair *dupKeyPair2 = nullptr; + res = generator->convertPemKey(generator, nullptr, nullptr, priKey, &dupKeyPair2); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(dupKeyPair2, nullptr); + + HcfKeyPair *dupKeyPair3 = nullptr; + res = generator->convertPemKey(generator, nullptr, pubKey, nullptr, &dupKeyPair3); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(dupKeyPair3, nullptr); + + HcfObjDestroy(dupKeyPair); + HcfObjDestroy(dupKeyPair2); + HcfObjDestroy(dupKeyPair3); + HcfObjDestroy(generator); +} + +HWTEST_F(CryptoAsyKeyConvertPemTest, CryptoAsyKeyConvertPemTest001, TestSize.Level0) +{ + AsyKeyConvertPemTest("SM2_256", g_testSm2PubKey.c_str(), g_testSm2PriKey.c_str()); + AsyKeyConvertPemTest("X25519", g_testX25519PubKey.c_str(), g_testX25519PriKey.c_str()); + AsyKeyConvertPemTest("Ed25519", g_testEd25519PubKey.c_str(), g_testEd25519PriKey.c_str()); + AsyKeyConvertPemTest("ECC224", g_testEccSecp224r1PubKey.c_str(), g_testEccSecp224r1PriKey.c_str()); + AsyKeyConvertPemTest("DSA1024", g_testDsa1024Pubkey.c_str(), g_testDsa1024Prikey.c_str()); + AsyKeyConvertPemTest("DH_modp1536", g_testDhModp1536PubKey.c_str(), g_testDhModp1536PriKey.c_str()); + + AsyKeyConvertPemTest("DH_ffdhe2048", g_testDhFfdhe2048PubKey.c_str(), g_testDhFfdhe2048PriKey.c_str()); + AsyKeyConvertPemTest("DH_ffdhe3072", g_testDhFfdhe3072PubKey.c_str(), g_testDhFfdhe3072PriKey.c_str()); + AsyKeyConvertPemTest("DH_ffdhe4096", g_testDhFfdhe4096PubKey.c_str(), g_testDhFfdhe4096PriKey.c_str()); + AsyKeyConvertPemTest("DH_ffdhe6144", g_testDhFfdhe6144PubKey.c_str(), g_testDhFfdhe6144PriKey.c_str()); + AsyKeyConvertPemTest("DH_ffdhe8192", g_testDhFfdhe8192PubKey.c_str(), g_testDhFfdhe8192PriKey.c_str()); + AsyKeyConvertPemTest("DH_modp2048", g_testDhModp2048PubKey.c_str(), g_testDhModp2048PriKey.c_str()); + AsyKeyConvertPemTest("DH_modp3072", g_testDhModp3072PubKey.c_str(), g_testDhModp3072PriKey.c_str()); + AsyKeyConvertPemTest("DH_modp4096", g_testDhModp4096PubKey.c_str(), g_testDhModp4096PriKey.c_str()); + AsyKeyConvertPemTest("DH_modp6144", g_testDhModp6144PubKey.c_str(), g_testDhModp6144PriKey.c_str()); + AsyKeyConvertPemTest("DH_modp8192", g_testDhModp8192PubKey.c_str(), g_testDhModp8192PriKey.c_str()); + + AsyKeyConvertPemTest("DSA2048", g_testDsa2048PubKey.c_str(), g_testDsa2048Prikey.c_str()); + AsyKeyConvertPemTest("DSA3072", g_testDsa3072PubKey.c_str(), g_testDsa3072Prikey.c_str()); + + AsyKeyConvertPemTest("ECC_BrainPoolP160r1", g_testEccP160r1PubKey.c_str(), g_testEccP160r1PriKey.c_str()); + AsyKeyConvertPemTest("ECC_BrainPoolP160t1", g_testEccP160t1PubKey.c_str(), g_testEccP160t1PriKey.c_str()); + AsyKeyConvertPemTest("ECC_BrainPoolP192r1", g_testEccP192r1PubKey.c_str(), g_testEccP192r1PriKey.c_str()); + AsyKeyConvertPemTest("ECC_BrainPoolP192t1", g_testEccP192t1PubKey.c_str(), g_testEccP192t1PriKey.c_str()); + AsyKeyConvertPemTest("ECC_BrainPoolP224r1", g_testEccP224r1PubKey.c_str(), g_testEccP224r1PriKey.c_str()); + AsyKeyConvertPemTest("ECC_BrainPoolP224t1", g_testEccP224t1PubKey.c_str(), g_testEccP224t1PriKey.c_str()); + AsyKeyConvertPemTest("ECC_BrainPoolP256r1", g_testEccP256r1PubKey.c_str(), g_testEccP256r1PriKey.c_str()); + AsyKeyConvertPemTest("ECC_BrainPoolP256t1", g_testEccP256t1PubKey.c_str(), g_testEccP256t1PriKey.c_str()); + AsyKeyConvertPemTest("ECC_BrainPoolP320r1", g_testEccP320r1PubKey.c_str(), g_testEccP320r1PriKey.c_str()); + AsyKeyConvertPemTest("ECC_BrainPoolP320t1", g_testEccP320t1PubKey.c_str(), g_testEccP320t1PriKey.c_str()); + AsyKeyConvertPemTest("ECC_BrainPoolP384r1", g_testEccP384r1PubKey.c_str(), g_testEccP384r1PriKey.c_str()); + AsyKeyConvertPemTest("ECC_BrainPoolP384t1", g_testEccP384t1PubKey.c_str(), g_testEccP384t1PriKey.c_str()); + AsyKeyConvertPemTest("ECC_BrainPoolP512r1", g_testEccP512r1PubKey.c_str(), g_testEccP512r1PriKey.c_str()); + AsyKeyConvertPemTest("ECC_BrainPoolP512t1", g_testEccP512t1PubKey.c_str(), g_testEccP512t1PriKey.c_str()); + AsyKeyConvertPemTest("ECC256", g_testEccPrime256v1PubKey.c_str(), g_testEccPrime256v1PriKey.c_str()); + AsyKeyConvertPemTest("ECC384", g_testEccSecp384r1PubKey.c_str(), g_testEccSecp384r1PriKey.c_str()); + AsyKeyConvertPemTest("ECC521", g_testEccSecp521r1PubKey.c_str(), g_testEccSecp521r1PriKey.c_str()); +} + +static void AsyKeyPemParamNullErrorTest(const char *algoName, const char *pubKey, const char *priKey) +{ + HcfAsyKeyGenerator *generator = nullptr; + HcfResult res = HcfAsyKeyGeneratorCreate(algoName, &generator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(generator, nullptr); + + HcfKeyPair *dupKeyPair = nullptr; + res = generator->convertPemKey(generator, nullptr, nullptr, nullptr, &dupKeyPair); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(dupKeyPair, nullptr); + + res = generator->convertPemKey(nullptr, nullptr, pubKey, priKey, &dupKeyPair); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(dupKeyPair, nullptr); + + res = generator->convertPemKey(generator, nullptr, pubKey, priKey, nullptr); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(dupKeyPair, nullptr); + HcfObjDestroy(generator); +} + +// test ConvertPemKey parma is null +HWTEST_F(CryptoAsyKeyConvertPemTest, CryptoAsyKeyConvertPemTest002, TestSize.Level0) +{ + AsyKeyPemParamNullErrorTest("SM2_256", g_testSm2PubKey.c_str(), g_testSm2PriKey.c_str()); + AsyKeyPemParamNullErrorTest("X25519", g_testX25519PubKey.c_str(), g_testX25519PriKey.c_str()); + AsyKeyPemParamNullErrorTest("Ed25519", g_testEd25519PubKey.c_str(), g_testEd25519PriKey.c_str()); + AsyKeyPemParamNullErrorTest("ECC224", g_testEccSecp224r1PubKey.c_str(), g_testEccSecp224r1PriKey.c_str()); + AsyKeyPemParamNullErrorTest("DSA1024", g_testDsa1024Pubkey.c_str(), g_testDsa1024Prikey.c_str()); + AsyKeyPemParamNullErrorTest("DH_modp1536", g_testDhModp1536PubKey.c_str(), g_testDhModp1536PriKey.c_str()); +} + +static void AsyKeyPemParamFormatErrorTest(const char *algoName, const char *pubKey, const char *priKey) +{ + HcfAsyKeyGenerator *generator = nullptr; + HcfResult res = HcfAsyKeyGeneratorCreate(algoName, &generator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(generator, nullptr); + + HcfKeyPair *dupKeyPair = nullptr; + res = generator->convertPemKey(generator, nullptr, "pubkey", priKey, &dupKeyPair); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(dupKeyPair, nullptr); + + res = generator->convertPemKey(generator, nullptr, pubKey, "prikey", &dupKeyPair); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(dupKeyPair, nullptr); + + res = generator->convertPemKey(generator, nullptr, "pubkey", "prikey", &dupKeyPair); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(dupKeyPair, nullptr); + + HcfObjDestroy(generator); +} + +// test ConvertPemKey pubkey and prikey is invalid +HWTEST_F(CryptoAsyKeyConvertPemTest, CryptoAsyKeyConvertPemTest003, TestSize.Level0) +{ + AsyKeyPemParamFormatErrorTest("SM2_256", g_testSm2PubKey.c_str(), g_testSm2PriKey.c_str()); + AsyKeyPemParamFormatErrorTest("X25519", g_testX25519PubKey.c_str(), g_testX25519PriKey.c_str()); + AsyKeyPemParamFormatErrorTest("Ed25519", g_testEd25519PubKey.c_str(), g_testEd25519PriKey.c_str()); + AsyKeyPemParamFormatErrorTest("ECC224", g_testEccSecp224r1PubKey.c_str(), g_testEccSecp224r1PriKey.c_str()); + AsyKeyPemParamFormatErrorTest("DSA1024", g_testDsa1024Pubkey.c_str(), g_testDsa1024Prikey.c_str()); + AsyKeyPemParamFormatErrorTest("DH_modp1536", g_testDhModp1536PubKey.c_str(), g_testDhModp1536PriKey.c_str()); +} + +static void AsyKeyPemParamMatchErrorTest(const char *algoName, const char *pubKey, const char *priKey) +{ + HcfAsyKeyGenerator *generator = nullptr; + HcfResult res = HcfAsyKeyGeneratorCreate(algoName, &generator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(generator, nullptr); + + HcfKeyPair *dupKeyPair = nullptr; + res = generator->convertPemKey(generator, nullptr, pubKey, priKey, &dupKeyPair); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(dupKeyPair, nullptr); + + res = generator->convertPemKey(generator, nullptr, nullptr, priKey, &dupKeyPair); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(dupKeyPair, nullptr); + + res = generator->convertPemKey(generator, nullptr, pubKey, nullptr, &dupKeyPair); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(dupKeyPair, nullptr); + + HcfObjDestroy(generator); +} + +HWTEST_F(CryptoAsyKeyConvertPemTest, CryptoAsyKeyConvertPemTest004, TestSize.Level0) +{ + AsyKeyPemParamMatchErrorTest("SM2_256", g_testX25519PubKey.c_str(), g_testX25519PriKey.c_str()); + AsyKeyPemParamMatchErrorTest("SM2_256", g_testEd25519PubKey.c_str(), g_testEd25519PriKey.c_str()); + AsyKeyPemParamMatchErrorTest("SM2_256", g_testEccSecp224r1PubKey.c_str(), g_testEccSecp224r1PriKey.c_str()); + AsyKeyPemParamMatchErrorTest("SM2_256", g_testDsa1024Pubkey.c_str(), g_testDsa1024Prikey.c_str()); + AsyKeyPemParamMatchErrorTest("SM2_256", g_testDhModp1536PubKey.c_str(), g_testDhModp1536PriKey.c_str()); + AsyKeyPemParamMatchErrorTest("X25519", g_testSm2PubKey.c_str(), g_testSm2PriKey.c_str()); + AsyKeyPemParamMatchErrorTest("X25519", g_testEd25519PubKey.c_str(), g_testEd25519PriKey.c_str()); + AsyKeyPemParamMatchErrorTest("X25519", g_testEccSecp224r1PubKey.c_str(), g_testEccSecp224r1PriKey.c_str()); + AsyKeyPemParamMatchErrorTest("X25519", g_testDsa1024Pubkey.c_str(), g_testDsa1024Prikey.c_str()); + AsyKeyPemParamMatchErrorTest("X25519", g_testDhModp1536PubKey.c_str(), g_testDhModp1536PriKey.c_str()); + AsyKeyPemParamMatchErrorTest("Ed25519", g_testSm2PubKey.c_str(), g_testSm2PriKey.c_str()); + AsyKeyPemParamMatchErrorTest("Ed25519", g_testX25519PubKey.c_str(), g_testX25519PriKey.c_str()); + AsyKeyPemParamMatchErrorTest("Ed25519", g_testEccSecp224r1PubKey.c_str(), g_testEccSecp224r1PriKey.c_str()); + AsyKeyPemParamMatchErrorTest("Ed25519", g_testDsa1024Pubkey.c_str(), g_testDsa1024Prikey.c_str()); + AsyKeyPemParamMatchErrorTest("Ed25519", g_testDhModp1536PubKey.c_str(), g_testDhModp1536PriKey.c_str()); + AsyKeyPemParamMatchErrorTest("ECC224", g_testSm2PubKey.c_str(), g_testSm2PriKey.c_str()); + AsyKeyPemParamMatchErrorTest("ECC224", g_testX25519PubKey.c_str(), g_testX25519PriKey.c_str()); + AsyKeyPemParamMatchErrorTest("ECC224", g_testEd25519PubKey.c_str(), g_testEd25519PriKey.c_str()); + AsyKeyPemParamMatchErrorTest("ECC224", g_testDsa1024Pubkey.c_str(), g_testDsa1024Prikey.c_str()); + AsyKeyPemParamMatchErrorTest("ECC224", g_testDhModp1536PubKey.c_str(), g_testDhModp1536PriKey.c_str()); + AsyKeyPemParamMatchErrorTest("DSA1024", g_testSm2PubKey.c_str(), g_testSm2PriKey.c_str()); + AsyKeyPemParamMatchErrorTest("DSA1024", g_testX25519PubKey.c_str(), g_testX25519PriKey.c_str()); + AsyKeyPemParamMatchErrorTest("DSA1024", g_testEd25519PubKey.c_str(), g_testEd25519PriKey.c_str()); + AsyKeyPemParamMatchErrorTest("DSA1024", g_testEccSecp224r1PubKey.c_str(), g_testEccSecp224r1PriKey.c_str()); + AsyKeyPemParamMatchErrorTest("DSA1024", g_testDhModp1536PubKey.c_str(), g_testDhModp1536PriKey.c_str()); + AsyKeyPemParamMatchErrorTest("DH_modp1536", g_testSm2PubKey.c_str(), g_testSm2PriKey.c_str()); + AsyKeyPemParamMatchErrorTest("DH_modp1536", g_testX25519PubKey.c_str(), g_testX25519PriKey.c_str()); + AsyKeyPemParamMatchErrorTest("DH_modp1536", g_testEd25519PubKey.c_str(), g_testEd25519PriKey.c_str()); + AsyKeyPemParamMatchErrorTest("DH_modp1536", g_testEccSecp224r1PubKey.c_str(), g_testEccSecp224r1PriKey.c_str()); + AsyKeyPemParamMatchErrorTest("DH_modp1536", g_testDsa1024Pubkey.c_str(), g_testDsa1024Prikey.c_str()); +} +} diff --git a/test/unittest/src/crypto_common_cov_test.cpp b/test/unittest/src/crypto_common_cov_test.cpp index e8b5672a2748cf47db8524e9e6bac00c190e5b0f..d20e7cb77b6cf788cb9c64c4622db5519a6fcd86 100644 --- a/test/unittest/src/crypto_common_cov_test.cpp +++ b/test/unittest/src/crypto_common_cov_test.cpp @@ -51,10 +51,6 @@ void CryptoCommonCovTest::SetUp() {} void CryptoCommonCovTest::TearDown() {} -constexpr uint32_t PRIMES_2 = 2; -constexpr uint32_t PRIMES_3 = 3; -constexpr uint32_t PRIMES_4 = 4; -constexpr uint32_t PRIMES_5 = 5; constexpr uint32_t BEGIN_POS = 1; constexpr uint32_t PARCEL_LENGTH = 1; constexpr uint32_t PARCEL_UINT_MAX = 0xffffffffU; @@ -171,30 +167,6 @@ HWTEST_F(CryptoCommonCovTest, CryptoCommonTest011, TestSize.Level0) EXPECT_NE(ret, HCF_SUCCESS); } -HWTEST_F(CryptoCommonCovTest, CryptoCommonTest012, TestSize.Level0) -{ - int32_t ret = GetRealPrimes(HCF_OPENSSL_PRIMES_2); - EXPECT_EQ(ret, PRIMES_2); -} - -HWTEST_F(CryptoCommonCovTest, CryptoCommonTest013, TestSize.Level0) -{ - int32_t ret = GetRealPrimes(HCF_OPENSSL_PRIMES_3); - EXPECT_EQ(ret, PRIMES_3); -} - -HWTEST_F(CryptoCommonCovTest, CryptoCommonTest014, TestSize.Level0) -{ - int32_t ret = GetRealPrimes(HCF_OPENSSL_PRIMES_4); - EXPECT_EQ(ret, PRIMES_4); -} - -HWTEST_F(CryptoCommonCovTest, CryptoCommonTest015, TestSize.Level0) -{ - int32_t ret = GetRealPrimes(HCF_OPENSSL_PRIMES_5); - EXPECT_EQ(ret, PRIMES_5); -} - HWTEST_F(CryptoCommonCovTest, CryptoCommonTest016, TestSize.Level0) { HcfResult ret = BigIntegerToBigNum(nullptr, nullptr); diff --git a/test/unittest/src/native/native_asym_key_test.cpp b/test/unittest/src/native/native_asym_key_test.cpp index cf4c157c301089b20332a1b40a359a09337462a8..fc0dea1272ba220c44648f77f3818595ada5af61 100644 --- a/test/unittest/src/native/native_asym_key_test.cpp +++ b/test/unittest/src/native/native_asym_key_test.cpp @@ -64,7 +64,7 @@ HWTEST_F(NativeAsymKeyTest, NativeAsymKeyTest001, TestSize.Level0) const char *algoName = OH_CryptoAsymKeyGenerator_GetAlgoName(generator); ASSERT_NE(algoName, nullptr); - + OH_CryptoPubKey *pubKey = OH_CryptoKeyPair_GetPubKey(keyCtx); Crypto_DataBlob dataBlob = { .data = nullptr, .len = 0 }; @@ -109,7 +109,6 @@ HWTEST_F(NativeAsymKeyTest, NativeAsymKeyTest002, TestSize.Level0) cmpRes = strcmp(reinterpret_cast(retBlobX509.data), reinterpret_cast(pubKeyX509Str.data)); EXPECT_EQ(cmpRes, CRYPTO_SUCCESS); - OH_Crypto_FreeDataBlob(&retBlob); OH_Crypto_FreeDataBlob(&retBlobX509); OH_CryptoKeyPair_Destroy(dupKeyPair); @@ -124,7 +123,7 @@ HWTEST_F(NativeAsymKeyTest, NativeAsymKeyTest003, TestSize.Level0) EXPECT_EQ(ret, CRYPTO_SUCCESS); ret = OH_CryptoAsymKeyGenerator_Generate(generator, &keyCtx); EXPECT_EQ(ret, CRYPTO_SUCCESS); - + OH_CryptoPubKey *pubKey = OH_CryptoKeyPair_GetPubKey(keyCtx); Crypto_DataBlob dataBlobE = { .data = nullptr, .len = 0 }; ret = OH_CryptoPubKey_GetParam(pubKey, CRYPTO_RSA_E_DATABLOB, &dataBlobE); @@ -164,8 +163,8 @@ HWTEST_F(NativeAsymKeyTest, NativeAsymKeyTest004, TestSize.Level0) OH_CryptoPubKey *pubKey1 = OH_CryptoKeyPair_GetPubKey(dupKeyPair); ASSERT_EQ(ret, CRYPTO_SUCCESS); - Crypto_DataBlob dataBlob = { .data = nullptr, .len = 0 }; - + Crypto_DataBlob dataBlob = { .data = nullptr, .len = 0 }; + ret = OH_CryptoPubKey_GetParam(pubKey1, CRYPTO_RSA_N_DATABLOB, &dataBlob); ASSERT_EQ(ret, CRYPTO_SUCCESS); ASSERT_NE(dataBlob.data, nullptr); @@ -206,7 +205,7 @@ HWTEST_F(NativeAsymKeyTest, NativeAsymKeyTest005, TestSize.Level0) OH_CryptoPubKey *pubKey1 = OH_CryptoKeyPair_GetPubKey(dupKeyPair); ASSERT_EQ(ret, CRYPTO_SUCCESS); Crypto_DataBlob dataBlob = { .data = nullptr, .len = 0 }; - + ret = OH_CryptoPubKey_GetParam(pubKey1, CRYPTO_ED25519_PK_DATABLOB, &dataBlob); ASSERT_EQ(ret, CRYPTO_SUCCESS); ASSERT_NE(dataBlob.data, nullptr); diff --git a/test/unittest/src/rsa_common_param_spec.cpp b/test/unittest/src/rsa_common_param_spec.cpp index e7efc4dcca2171dd9137ecc886cf47fc86c01837..f6537f4c249b93d6b1436299142b55bc3ff24be2 100644 --- a/test/unittest/src/rsa_common_param_spec.cpp +++ b/test/unittest/src/rsa_common_param_spec.cpp @@ -47,6 +47,9 @@ void EndianSwap(unsigned char *pData, int startIndex, int length) // 512 defined the length of byte array void GenerateRsa512CorrectCommonKeySpec(unsigned char *dataN, HcfRsaCommParamsSpec *returnSpec) { + if (dataN == nullptr) { + return; + } RemoveLastChar(CORRECT_512_N, dataN, RSA_512_N_BYTE_SIZE); if (!IsBigEndian()) { // the device is not big endian diff --git a/test/unittest/src/sm4_common.cpp b/test/unittest/src/sm4_common.cpp index e6953c809dc877dff748cbdbbe47cb20a3e475e4..bba4858eff69a4cefb972224375ce293a62b932b 100644 --- a/test/unittest/src/sm4_common.cpp +++ b/test/unittest/src/sm4_common.cpp @@ -37,7 +37,7 @@ HcfResult GenerateSm4SymKey(HcfSymKey **key) HcfSymKeyGenerator *generator = nullptr; HcfResult ret = HcfSymKeyGeneratorCreate("SM4_128", &generator); - if (ret != HCF_SUCCESS) { + if (ret != HCF_SUCCESS || generator == nullptr) { LOGE("HcfSymKeyGeneratorCreate failed!"); return ret; } @@ -55,7 +55,7 @@ int32_t GenerateSymKeyForSm4(const char *algoName, HcfSymKey **key) HcfSymKeyGenerator *generator = nullptr; int32_t ret = HcfSymKeyGeneratorCreate(algoName, &generator); - if (ret != 0) { + if (ret != 0 || generator == nullptr) { LOGE("HcfSymKeyGeneratorCreate failed!"); return ret; }