diff --git a/BUILD.gn b/BUILD.gn new file mode 100644 index 0000000..cabef68 --- /dev/null +++ b/BUILD.gn @@ -0,0 +1,45 @@ +# Copyright (C) 2022 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. + +group("crypto_framework_lib") { + if (os_level == "standard") { + deps = [ + "//base/security/crypto_framework/frameworks:crypto_framework_lib", + ] + } +} + +group("crypto_openssl_plugin_lib") { + if (os_level == "standard") { + deps = [ + "//base/security/crypto_framework/plugin:crypto_openssl_plugin_lib", + ] + } +} + +group("cryptoframework_napi") { + if (os_level == "standard") { + deps = [ + "//base/security/crypto_framework/frameworks:cryptoframework_napi", + ] + } +} + +group("crypto_framework_test") { + testonly = true + if (os_level == "standard") { + deps = [ + "//base/security/crypto_framework/test/unittest:crypto_framework_test", + ] + } +} diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..4947287 --- /dev/null +++ b/LICENSE @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/README.en.md b/README.en.md deleted file mode 100644 index 9d2e9b5..0000000 --- a/README.en.md +++ /dev/null @@ -1,36 +0,0 @@ -# security_crypto_framework - -#### Description -{**When you're done, you can delete the content in this README and update the file with details for others getting started with your repository**} - -#### Software Architecture -Software architecture description - -#### Installation - -1. xxxx -2. xxxx -3. xxxx - -#### Instructions - -1. xxxx -2. xxxx -3. xxxx - -#### Contribution - -1. Fork the repository -2. Create Feat_xxx branch -3. Commit your code -4. Create Pull Request - - -#### Gitee Feature - -1. You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md -2. Gitee blog [blog.gitee.com](https://blog.gitee.com) -3. Explore open source project [https://gitee.com/explore](https://gitee.com/explore) -4. The most valuable open source project [GVP](https://gitee.com/gvp) -5. The manual of Gitee [https://gitee.com/help](https://gitee.com/help) -6. The most popular members [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/) diff --git a/README.md b/README.md deleted file mode 100644 index dbff55b..0000000 --- a/README.md +++ /dev/null @@ -1,39 +0,0 @@ -# security_crypto_framework - -#### 介绍 -{**以下是 Gitee 平台说明,您可以替换此简介** -Gitee 是 OSCHINA 推出的基于 Git 的代码托管平台(同时支持 SVN)。专为开发者提供稳定、高效、安全的云端软件开发协作平台 -无论是个人、团队、或是企业,都能够用 Gitee 实现代码托管、项目管理、协作开发。企业项目请看 [https://gitee.com/enterprises](https://gitee.com/enterprises)} - -#### 软件架构 -软件架构说明 - - -#### 安装教程 - -1. xxxx -2. xxxx -3. xxxx - -#### 使用说明 - -1. xxxx -2. xxxx -3. xxxx - -#### 参与贡献 - -1. Fork 本仓库 -2. 新建 Feat_xxx 分支 -3. 提交代码 -4. 新建 Pull Request - - -#### 特技 - -1. 使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md -2. Gitee 官方博客 [blog.gitee.com](https://blog.gitee.com) -3. 你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解 Gitee 上的优秀开源项目 -4. [GVP](https://gitee.com/gvp) 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目 -5. Gitee 官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help) -6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/) diff --git a/README_zh.md b/README_zh.md new file mode 100644 index 0000000..0918896 --- /dev/null +++ b/README_zh.md @@ -0,0 +1,30 @@ +# 加解密算法库框架 + +## 简介 +为屏蔽底层硬件和算法库,向上提供统一的密码算法库加解密和证书相关接口。 + +## 目录 +``` +base/security/crypto_framwork +├── build # 配置构建相关 +├── interfaces # 对外接口目录 +├── test # unitest +├── common # 内部依赖的公共方法 +├── plugin # 算法适配的插件 +│ └── openssl_plugin # openssl 插件 +├── frameworks # api调用SPI的实现 +│ ├── spi # 放SPI的头文件 +│ ├── js +│ └── napi # 通过napi封装的JS接口代码实现 +│ ├── algorithm_parameter # 算法参数 +│ ├── certificate # 证书 +│ ├── crypto_operation # 算法操作,包括mac、md、加解密、签名验签、秘钥协商 +│ ├── key +│ └── rand +``` + +## 相关仓 + +**安全子系统** + +[security\_crypto\_framwork](https://gitee.com/openharmony/security_crypto_framwork) \ No newline at end of file diff --git a/build/config.gni b/build/config.gni new file mode 100644 index 0000000..36eb12d --- /dev/null +++ b/build/config.gni @@ -0,0 +1,15 @@ +/* + * Copyright (C) 2022 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. + */ + \ No newline at end of file diff --git a/bundle.json b/bundle.json new file mode 100644 index 0000000..59802e6 --- /dev/null +++ b/bundle.json @@ -0,0 +1,45 @@ +{ + "name": "@ohos/crypto_framework", + "version": "3.1", + "description": "Openharmony's crypto framework.", + "publishAs": "code-segment", + "segment": { + "destPath": "base/security/crypto_framework" + }, + "dirs": {}, + "scripts": {}, + "author": {}, + "repository": "", + "license": "Apache License 2.0", + "component": { + "name": "crypto_framework", + "subsystem": "security", + "syscap": [ "SystemCapability.Security.CryptoFramework" ], + "features": [], + "adapted_system_type": [ + "standard" + ], + "rom": "1024KB", + "ram": "", + "deps": { + "components": [ + "hiviewdfx_hilog_native" + ], + "third_party": [ + "bounds_checking_function", + "openssl" + ] + }, + "build": { + "sub_component": [ + "//base/security/crypto_framework:crypto_framework_lib", + "//base/security/crypto_framework:crypto_openssl_plugin_lib", + "//base/security/crypto_framework:cryptoframework_napi" + ], + "inner_kits": [], + "test": [ + "//base/security/crypto_framework:crypto_framework_test" + ] + } + } +} diff --git a/common/BUILD.gn b/common/BUILD.gn new file mode 100644 index 0000000..3d8e2c0 --- /dev/null +++ b/common/BUILD.gn @@ -0,0 +1,42 @@ +# Copyright (C) 2022 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("//build/ohos.gni") +import("//base/security/crypto_framework/common/common.gni") + +ohos_static_library("crypto_plugin_common") { + subsystem_name = "security" + part_name = "crypto_framework" + include_dirs = [ + "//utils/native/base/include", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + ] + include_dirs += crypto_framwork_common_inc_path + + sources = crypto_framwork_common_files + + defines = [ "HILOG_ENABLE" ] + cflags = [ + "-DHILOG_ENABLE", + "-fPIC", + "-Wall", + ] + + deps = [ + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + ] +} diff --git a/common/common.gni b/common/common.gni new file mode 100644 index 0000000..247823a --- /dev/null +++ b/common/common.gni @@ -0,0 +1,29 @@ +# Copyright (C) 2022 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. + +crypto_framwork_common_inc_path = [ + "//base/security/crypto_framework/interfaces/innerkits/common", + "//base/security/crypto_framework/common/inc", +] + +framework_common_util_files = [ + "//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/hcf_parcel.c", + "//base/security/crypto_framework/common/src/hcf_string.c", + "//base/security/crypto_framework/common/src/params_parser.c", +] + +crypto_framwork_common_files = framework_common_util_files \ No newline at end of file diff --git a/common/inc/config.h b/common/inc/config.h new file mode 100644 index 0000000..b325be3 --- /dev/null +++ b/common/inc/config.h @@ -0,0 +1,24 @@ +/* + * Copyright (C) 2022 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_CONFIG_H +#define HCF_CONFIG_H + +#define HCF_MAX_STR_LEN 1024 // input string parameter max length limit, include \0 +#define HCF_MAX_ALGO_NAME_LEN 128 // input algoName parameter max length limit, include \0 +#define LOG_PRINT_MAX_LEN 1024 // log max length limit +#define HCF_MAX_BUFFER_LEN 8192 + +#endif diff --git a/common/inc/fwk_class.h b/common/inc/fwk_class.h new file mode 100644 index 0000000..d124e03 --- /dev/null +++ b/common/inc/fwk_class.h @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2022 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_FWK_CLASS_H +#define HCF_FWK_CLASS_H + +#include "x509_certificate.h" +#include "x509_certificate_spi.h" + +typedef struct { + HcfX509Certificate base; + HcfX509CertificateSpi *spiObj; +} HcfX509CertificateImpl; + +#define HCF_X509_CERTIFICATE_CLASS "HcfX509Certificate" + +#endif diff --git a/common/inc/hcf_parcel.h b/common/inc/hcf_parcel.h new file mode 100644 index 0000000..9587790 --- /dev/null +++ b/common/inc/hcf_parcel.h @@ -0,0 +1,97 @@ +/* +* Copyright (C) 2021 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 HC_PARCEL_H +#define HC_PARCEL_H + +#include +#include +#include "memory.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define PARCEL_DEFAULT_LENGTH 0 +#define PARCEL_DEFAULT_ALLOC_UNIT 0 + + typedef struct { + char *data; + unsigned int beginPos; + unsigned int endPos; + unsigned int length; + unsigned int allocUnit; + } HcParcel; + + HcParcel CreateParcel(uint32_t size, uint32_t allocUnit); + void DeleteParcel(HcParcel *parcel); + void ClearParcel(HcParcel *parcel); + void ResetParcel(HcParcel *parcel, uint32_t size, uint32_t allocUnit); + bool ParcelReadWithoutPopData(HcParcel *parcel, void *dst, uint32_t dataSize); + bool ParcelRead(HcParcel *parcel, void *dst, uint32_t dataSize); + bool ParcelWrite(HcParcel *parcel, const void *src, uint32_t dataSize); + bool ParcelReadRevert(HcParcel *parcel, void *dst, uint32_t dataSize); + bool ParcelWriteRevert(HcParcel *parcel, const void *src, uint32_t dataSize); + uint32_t GetParcelDataSize(const HcParcel *parcel); + const char *GetParcelData(const HcParcel *parcel); + const char* GetParcelLastChar(const HcParcel *parcel); + + bool ParcelReadInt32(HcParcel *parcel, int *dst); + bool ParcelReadUint32(HcParcel *parcel, uint32_t *dst); + bool ParcelReadInt16(HcParcel *parcel, short *dst); + bool ParcelReadUint16(HcParcel *parcel, uint16_t *dst); + bool ParcelReadInt8(HcParcel *parcel, char *dst); + bool ParcelReadUint8(HcParcel *parcel, uint8_t *dst); + bool ParcelReadUint64(HcParcel *parcel, uint64_t *dst); + bool ParcelReadInt64(HcParcel *parcel, int64_t *dst); + bool ParcelWriteInt32(HcParcel *parcel, int src); + bool ParcelWriteUint32(HcParcel *parcel, uint32_t src); + bool ParcelWriteInt16(HcParcel *parcel, short src); + bool ParcelWriteUint16(HcParcel *parcel, uint16_t src); + bool ParcelWriteInt8(HcParcel *parcel, char src); + bool ParcelWriteUint8(HcParcel *parcel, uint8_t src); + bool ParcelWriteUint64(HcParcel *parcel, uint64_t src); + bool ParcelWriteInt64(HcParcel *parcel, int64_t src); + bool ParcelWriteString(HcParcel *parcel, const char *str); + bool ParcelReadString(HcParcel *parcel, char **str); + bool ParcelReadParcel(HcParcel *src, HcParcel *dst, uint32_t size, bool copy); + bool ParcelCopy(HcParcel *src, HcParcel *dst); + + bool ParcelReadInt32Revert(HcParcel *parcel, int32_t *dst); + bool ParcelReadUint32Revert(HcParcel *parcel, uint32_t *dst); + bool ParcelReadInt16Revert(HcParcel *parcel, short *dst); + bool ParcelReadUint16Revert(HcParcel *parcel, uint16_t *dst); + bool ParcelReadInt8Revert(HcParcel *parcel, char *dst); + bool ParcelReadUint8Revert(HcParcel *parcel, uint8_t *dst); + bool ParcelReadUint64Revert(HcParcel *parcel, uint64_t *dst); + bool ParcelReadInt64Revert(HcParcel *parcel, int64_t *dst); + bool ParcelWriteInt32Revert(HcParcel *parcel, int src); + bool ParcelWriteUint32Revert(HcParcel *parcel, uint32_t src); + bool ParcelWriteInt16Revert(HcParcel *parcel, short src); + bool ParcelWriteUint16Revert(HcParcel *parcel, uint16_t src); + bool ParcelWriteInt8Revert(HcParcel *parcel, char src); + bool ParcelWriteUint8Revert(HcParcel *parcel, uint8_t src); + bool ParcelWriteUint64Revert(HcParcel *parcel, uint64_t src); + bool ParcelWriteInt64Revert(HcParcel *parcel, int64_t src); + + void DataRevert(void *data, uint32_t length); + bool ParcelPopBack(HcParcel *parcel, uint32_t size); + bool ParcelPopFront(HcParcel *parcel, uint32_t size); + bool ParcelEraseBlock(HcParcel *parcel, uint32_t start, uint32_t data_size, void *dst); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/common/inc/hcf_string.h b/common/inc/hcf_string.h new file mode 100644 index 0000000..eb19c52 --- /dev/null +++ b/common/inc/hcf_string.h @@ -0,0 +1,147 @@ +/* +* Copyright (C) 2021 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 HC_STRING_H +#define HC_STRING_H + +#include "hcf_parcel.h" + +#ifdef __cplusplus +extern "C" { +#endif + + typedef struct HcString { + HcParcel parcel; // parcel data, used to storage the string data + } HcString; + + /* + * Append a HcString + * Notice: It will add '\0' automatically. + * @param self: self pointer. + * @param str: append string. + * @return true (ok), false (error) + */ + bool StringAppend(HcString *self, HcString str); + + /* + * Append string pointer + * Notice: It will add '\0' automatically. + * @param self: self pointer. + * @param str: string pointer. + * @return true (ok), false (error) + */ + bool StringAppendPointer(HcString *self, const char *str); + + /* + * Append a char + * Notice: It will add '\0' automatically. + * @param self: self pointer. + * @param str: char. + * @return true (ok), false (error) + */ + bool StringAppendChar(HcString *self, char c); + + /* + * Assign a value to the HcString + * Notice: It will add '\0' automatically. + * @param self: self pointer. + * @param str: assign value of ta_sting. + * @return true (ok), false (error) + */ + bool StringSet(HcString *self, HcString str); + + /* + * Assign a value to the HcString + * Notice: It will add '\0' automatically. + * @param self: self pointer. + * @param str: assign value of string pointer. + * @return true (ok), false (error) + */ + bool StringSetPointer(HcString *self, const char *str); + + /* + * Assign a value to the HcString with fixed length + * Notice: It will add '\0' automatically. + * @param self: self pointer. + * @param str: assign value of string pointer. + * @param len: the length of string. + * @return true (ok), false (error) + */ + bool StringSetPointerWithLength(HcString* self, const char *str, uint32_t len); + + /* + * Get the string pointer data + * @param self: self pointer. + * @return the pointer data of the string + */ + const char* StringGet(const HcString *self); + + /* + * Get the length of the string + * @param self: self pointer. + * @return the length of the string + */ + uint32_t StringLength(const HcString *self); + + /* + * Find a char from string + * @param self: self pointer. + * @param c: the char you want find + * @param begin: the position find from + * @return the position of the char + */ + int StringFind(const HcString *self, char c, uint32_t begin); + + /* + * Get sub string from a string. + * @param self: self pointer. + * @param begin: the begin position of the sub string. + * @param len: the length of the sub string. + * @param dst: the string pointer which saved the sub string content. + * @return the operation result. + */ + bool StringSubString(const HcString *self, uint32_t begin, uint32_t len, HcString* dst); + + /* + * Compare the string with another string. + * @param self: self pointer. + * @param dst: the pointer of another string. + * @return the compare result. + * -1: self is smaller than dst + * 0: self is equal with dst + * 1: self is bigger than dst + */ + int StringCompare(const HcString *self, const char* dst); + + /* + * Create a string. + * Notice: You should delete string when you don't need the string anymore. + * @return the created string. + */ + HcString CreateString(void); + + /* + * Delete a string. In fact it will not destroy the string, + * but only free the allocated memory of the string and reset the member's value + * of the string. You can continue to use the string if you want. + * Notice: You should delete the string when you don't need it any more to avoid memory leak. + * @param str: The string you want to delete. + */ + void DeleteString(HcString *str); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/common/inc/log.h b/common/inc/log.h new file mode 100644 index 0000000..80405eb --- /dev/null +++ b/common/inc/log.h @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2022 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_LOG_H +#define HCF_LOG_H + +#ifdef HILOG_ENABLE + +typedef enum { + HCF_LOG_LEVEL_DEBUG = 0, + HCF_LOG_LEVEL_INFO = 1, + HCF_LOG_LEVEL_WARN = 2, + HCF_LOG_LEVEL_ERROR = 3 +} HcfLogLevel; + +#ifdef __cplusplus +extern "C" { +#endif + +void HcfLogPrint(HcfLogLevel level, const char *funName, const char *fmt, ...); + +#ifdef __cplusplus +} +#endif + +#include "hilog/log.h" + +#define LOGD(fmt, ...) (HcfLogPrint(HCF_LOG_LEVEL_DEBUG, __FUNCTION__, fmt, ##__VA_ARGS__)) +#define LOGI(fmt, ...) (HcfLogPrint(HCF_LOG_LEVEL_INFO, __FUNCTION__, fmt, ##__VA_ARGS__)) +#define LOGW(fmt, ...) (HcfLogPrint(HCF_LOG_LEVEL_WARN, __FUNCTION__, fmt, ##__VA_ARGS__)) +#define LOGE(fmt, ...) (HcfLogPrint(HCF_LOG_LEVEL_ERROR, __FUNCTION__, fmt, ##__VA_ARGS__)) + +#define HCF_LOG_DEBUG(fmt, ...) HiLogPrint(LOG_CORE, LOG_DEBUG, LOG_DOMAIN, "[HCF]", "%{public}s", buf) +#define HCF_LOG_INFO(buf) HiLogPrint(LOG_CORE, LOG_INFO, LOG_DOMAIN, "[HCF]", "%{public}s", buf) +#define HCF_LOG_WARN(buf) HiLogPrint(LOG_CORE, LOG_WARN, LOG_DOMAIN, "[HCF]", "%{public}s", buf) +#define HCF_LOG_ERROR(buf) HiLogPrint(LOG_CORE, LOG_ERROR, LOG_DOMAIN, "[HCF]", "%{public}s", buf) + +#else + +#include +#include + +#define LOGD(fmt, ...) printf("[HCF][D][%s]: " fmt "\n", __FUNCTION__, ##__VA_ARGS__) +#define LOGI(fmt, ...) printf("[HCF][I][%s]: " fmt "\n", __FUNCTION__, ##__VA_ARGS__) +#define LOGW(fmt, ...) printf("[HCF][W][%s]: " fmt "\n", __FUNCTION__, ##__VA_ARGS__) +#define LOGE(fmt, ...) printf("[HCF][E][%s]: " fmt "\n", __FUNCTION__, ##__VA_ARGS__) + +#endif +#endif diff --git a/common/inc/memory.h b/common/inc/memory.h new file mode 100644 index 0000000..31bca35 --- /dev/null +++ b/common/inc/memory.h @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2022 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_MEMORY_H +#define HCF_MEMORY_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +void* HcfMalloc(uint32_t size, char val); +void HcfFree(void* addr); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/common/inc/params_parser.h b/common/inc/params_parser.h new file mode 100644 index 0000000..92e53d5 --- /dev/null +++ b/common/inc/params_parser.h @@ -0,0 +1,142 @@ +/* +* Copyright (C) 2021 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_PARAMS_PARSER_H +#define HCF_PARAMS_PARSER_H + +#include +#include "result.h" + +typedef enum { + HCF_ALG_TYPE = 1, + HCF_ALG_KEY_TYPE, + HCF_ALG_MODE, + HCF_ALG_PADDING_TYPE, + HCF_ALG_PRIMES, + HCF_ALG_DIGEST, + HCF_ALG_MGF1_DIGEST, +} HCF_ALG_PARA_TYPE; + +typedef enum { + HCF_ALG_AES = 1, + HCF_ALG_DES, + HCF_ALG_RSA, + HCF_ALG_ECC, +} HCF_ALG_VALUE; + +typedef enum { + HCF_ALG_ECC_224 = 1, + HCF_ALG_ECC_256, + HCF_ALG_ECC_384, + HCF_ALG_ECC_512, + + HCF_ALG_AES_128, + HCF_ALG_AES_192, + HCF_ALG_AES_256, + HCF_ALG_3DES_192, + + HCF_ALG_MODE_NONE, + HCF_ALG_MODE_ECB, + HCF_ALG_MODE_CBC, + HCF_ALG_MODE_CTR, + HCF_ALG_MODE_OFB, + HCF_ALG_MODE_CFB, + HCF_ALG_MODE_CFB1, + HCF_ALG_MODE_CFB8, + HCF_ALG_MODE_CFB64, + HCF_ALG_MODE_CFB128, + HCF_ALG_MODE_CCM, + HCF_ALG_MODE_GCM, + + HCF_ALG_NOPADDING, + HCF_ALG_PADDING_PKCS5, + HCF_ALG_PADDING_PKCS7, + + // rsa keysize + HCF_OPENSSL_RSA_512, + HCF_OPENSSL_RSA_768, + HCF_OPENSSL_RSA_1024, + HCF_OPENSSL_RSA_2048, + HCF_OPENSSL_RSA_3072, + HCF_OPENSSL_RSA_4096, + HCF_OPENSSL_RSA_8192, + + // rsa cipher padding, + HCF_OPENSSL_RSA_PKCS1_PADDING, + HCF_OPENSSL_RSA_PKCS1_OAEP_PADDING, + HCF_OPENSSL_RSA_PSS_PADDING, + + // digest + HCF_OPENSSL_DIGEST_NONE, + HCF_OPENSSL_DIGEST_MD5, + HCF_OPENSSL_DIGEST_SHA1, + HCF_OPENSSL_DIGEST_SHA224, + HCF_OPENSSL_DIGEST_SHA256, + HCF_OPENSSL_DIGEST_SHA384, + HCF_OPENSSL_DIGEST_SHA512, + + // primes + HCF_OPENSSL_PRIMES_2, + HCF_OPENSSL_PRIMES_3, + HCF_OPENSSL_PRIMES_4, + HCF_OPENSSL_PRIMES_5, +} HCF_ALG_PARA_VALUE; + +typedef struct { + const char* tag; + HCF_ALG_PARA_TYPE para_type; + HCF_ALG_PARA_VALUE para_value; +} HcfParaConfig; + +typedef struct { + HCF_ALG_VALUE algo; + HCF_ALG_PARA_VALUE keySize; + HCF_ALG_PARA_VALUE mode; + HCF_ALG_PARA_VALUE paddingMode; + HCF_ALG_PARA_VALUE md; + HCF_ALG_PARA_VALUE mgf1md; +} CipherAttr; + +typedef struct { + HCF_ALG_VALUE algo; // algType + int32_t bits; // keyLen + int32_t primes; // number of primes +} HcfAsyKeyGenParams; + +typedef struct { + HCF_ALG_VALUE algo; // algType + HCF_ALG_PARA_VALUE keyLen; + HCF_ALG_PARA_VALUE padding; + HCF_ALG_PARA_VALUE md; + HCF_ALG_PARA_VALUE mgf1md; +} HcfSignatureParams; + +typedef struct { + HCF_ALG_VALUE algo; + HCF_ALG_PARA_VALUE keyLen; +} HcfKeyAgreementParams; + +typedef HcfResult (*SetParameterFunc) (const HcfParaConfig* config, void *params); + +#ifdef __cplusplus +extern "C" { +#endif + +HcfResult ParseAndSetParameter(const char* paramsStr, void *params, SetParameterFunc setFunc); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/common/inc/utils.h b/common/inc/utils.h new file mode 100644 index 0000000..3aae360 --- /dev/null +++ b/common/inc/utils.h @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2022 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_UTILS_H +#define HCF_UTILS_H + +#include +#include +#include "blob.h" +#include "object_base.h" + +#ifdef __cplusplus +extern "C" { +#endif + +bool IsStrValid(const char *str, uint32_t maxLen); +bool IsBlobValid(const HcfBlob *blob); +bool IsClassMatch(const HcfObjectBase *obj, const char *className); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/common/src/blob.c b/common/src/blob.c new file mode 100644 index 0000000..47056f3 --- /dev/null +++ b/common/src/blob.c @@ -0,0 +1,68 @@ +/* + * Copyright (C) 2022 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 "blob.h" + +#include +#include "memory.h" +#include "log.h" + +void HcfBlobDataFree(HcfBlob *blob) +{ + if ((blob == NULL) || (blob->data == NULL)) { + return; + } + HcfFree(blob->data); + blob->data = NULL; + blob->len = 0; +} + +void HcfBlobDataClearAndFree(HcfBlob *blob) +{ + if ((blob == NULL) || (blob->data == NULL)) { + LOGD("The input blob is null, no need to free."); + return; + } + (void)memset_s(blob->data, blob->len, 0, blob->len); + HcfFree(blob->data); + blob->data = NULL; + blob->len = 0; +} + +void HcfEncodingBlobDataFree(HcfEncodingBlob *encodingBlob) +{ + if ((encodingBlob == NULL) || (encodingBlob->data == NULL)) { + LOGD("The input encodingBlob is null, no need to free."); + return; + } + HcfFree(encodingBlob->data); + encodingBlob->data = NULL; + encodingBlob->len = 0; +} + +void HcfArrayDataClearAndFree(HcfArray *array) +{ + if (array == NULL) { + LOGD("The input array is null, no need to free."); + return; + } + for (uint32_t i = 0; i < array->count; ++i) { + HcfFree(array->data[i].data); + array->data[i].data = NULL; + array->data[i].len = 0; + } + HcfFree(array->data); + array->data = NULL; +} diff --git a/common/src/hcf_parcel.c b/common/src/hcf_parcel.c new file mode 100644 index 0000000..1da4eba --- /dev/null +++ b/common/src/hcf_parcel.c @@ -0,0 +1,539 @@ +/* +* Copyright (C) 2021 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 "hcf_parcel.h" +#include "securec.h" +#include "memory.h" + +const int PARCEL_DEFAULT_INCREASE_STEP = 16; +const uint32_t PARCEL_UINT_MAX = 0xffffffffU; +const int HALF_LEN = 2; + +HcParcel CreateParcel(uint32_t size, uint32_t allocUnit) +{ + HcParcel parcel; + (void)memset_s(&parcel, sizeof(parcel), 0, sizeof(parcel)); + parcel.allocUnit = allocUnit; + if (parcel.allocUnit == 0) { + parcel.allocUnit = PARCEL_DEFAULT_INCREASE_STEP; + } + if (size > 0) { + parcel.data = (char *)HcfMalloc(size, 0); + if (parcel.data != NULL) { + parcel.length = size; + } + } + return parcel; +} + +void DeleteParcel(HcParcel *parcel) +{ + if (parcel == NULL) { + return; + } + + if (parcel->data != NULL) { + HcfFree(parcel->data); + parcel->data = 0; + } + parcel->length = 0; + parcel->beginPos = 0; + parcel->endPos = 0; +} + +void ClearParcel(HcParcel *parcel) +{ + if (parcel != NULL) { + parcel->beginPos = 0; + parcel->endPos = 0; + } +} + +void ResetParcel(HcParcel *parcel, uint32_t size, uint32_t allocUnit) +{ + if (parcel != NULL) { + DeleteParcel(parcel); + HcParcel newParcel = CreateParcel(size, allocUnit); + (void)memcpy_s(parcel, sizeof(HcParcel), &newParcel, sizeof(HcParcel)); + } +} + +uint32_t GetParcelDataSize(const HcParcel *parcel) +{ + if (parcel == NULL) { + return 0; + } + if (parcel->endPos >= parcel->beginPos) { + return parcel->endPos - parcel->beginPos; + } + return 0; +} + +const char *GetParcelData(const HcParcel *parcel) +{ + if (parcel == NULL) { + return NULL; + } + return parcel->data + parcel->beginPos; +} + +const char *GetParcelLastChar(const HcParcel *parcel) +{ + if (parcel == NULL || GetParcelDataSize(parcel) == 0) { + return NULL; + } + return parcel->data + parcel->endPos - 1; +} + +bool ParcelReadWithoutPopData(HcParcel *parcel, void *dst, uint32_t dataSize) +{ +#ifdef IS_BIG_ENDIAN + bool ret = ParcelReadRevert(parcel, dst, dataSize); +#else + bool ret = ParcelRead(parcel, dst, dataSize); +#endif + if (ret == true) { + parcel->beginPos -= dataSize; + } + return ret; +} + +bool ParcelRead(HcParcel *parcel, void *dst, uint32_t dataSize) +{ + errno_t rc; + if (parcel == NULL || dst == NULL || dataSize == 0) { + return false; + } + if (parcel->beginPos > PARCEL_UINT_MAX - dataSize) { + return false; + } + if (parcel->beginPos + dataSize > parcel->endPos) { + return false; + } + rc = memmove_s(dst, dataSize, parcel->data + parcel->beginPos, dataSize); + if (rc != EOK) { + return false; + } + parcel->beginPos += dataSize; + return true; +} + +bool ParcelEraseBlock(HcParcel *parcel, uint32_t start, uint32_t dataSize, void *dst) +{ + errno_t rc; + if (parcel == NULL || dst == NULL || dataSize == 0) { + return false; + } + if (start > PARCEL_UINT_MAX - dataSize) { + return false; + } + uint32_t parcelSizeOrg = GetParcelDataSize(parcel); + if (parcelSizeOrg < start + dataSize) { + return false; + } + char *beginCopy = parcel->data + parcel->beginPos + start; + uint32_t copySize = parcelSizeOrg - start - dataSize; + + rc = memmove_s(dst, dataSize, beginCopy, dataSize); + if (rc != EOK) { + return false; + } + if (copySize != 0) { + rc = memmove_s(beginCopy, copySize, beginCopy + dataSize, copySize); + if (rc != EOK) { + return false; + } + } + parcel->endPos -= dataSize; + return true; +} + +bool ParcelReadRevert(HcParcel *parcel, void *dst, uint32_t dataSize) +{ + if (ParcelRead(parcel, dst, dataSize)) { + DataRevert(dst, dataSize); + return true; + } else { + return false; + } +} + +bool ParcelWriteRevert(HcParcel *parcel, const void *src, uint32_t dataSize) +{ + errno_t rc; + void *srcCopy = HcfMalloc(dataSize, 0); + if (srcCopy == NULL) { + return false; + } + rc = memmove_s(srcCopy, dataSize, src, dataSize); + if (rc != EOK) { + HcfFree(srcCopy); + return false; + } + DataRevert(srcCopy, dataSize); + bool ret = ParcelWrite(parcel, srcCopy, dataSize); + HcfFree(srcCopy); + return ret; +} + +bool ParcelReadInt32(HcParcel *parcel, int *dst) +{ + return ParcelRead(parcel, dst, sizeof(int)); +} + +bool ParcelReadUint32(HcParcel *parcel, uint32_t *dst) +{ + return ParcelRead(parcel, dst, sizeof(uint32_t)); +} + +bool ParcelReadInt16(HcParcel *parcel, short *dst) +{ + return ParcelRead(parcel, dst, sizeof(short)); +} + +bool ParcelReadUint16(HcParcel *parcel, uint16_t *dst) +{ + return ParcelRead(parcel, dst, sizeof(uint16_t)); +} + +bool ParcelReadInt8(HcParcel *parcel, char *dst) +{ + return ParcelRead(parcel, dst, sizeof(char)); +} + +bool ParcelReadUint8(HcParcel *parcel, uint8_t *dst) +{ + return ParcelRead(parcel, dst, sizeof(uint8_t)); +} + +bool ParcelReadUint64(HcParcel *parcel, uint64_t *dst) +{ + return ParcelRead(parcel, dst, sizeof(uint64_t)); +} + +bool ParcelReadInt64(HcParcel *parcel, int64_t *dst) +{ + return ParcelRead(parcel, dst, sizeof(int64_t)); +} + +static bool ParcelRealloc(HcParcel *parcel, uint32_t size) +{ + if (parcel->length >= size) { + return false; + } + char *newData = (char *)HcfMalloc(size, 0); + if (newData == NULL) { + return false; + } + if (memcpy_s(newData, size, parcel->data, parcel->length) != EOK) { + HcfFree(newData); + return false; + } + HcfFree(parcel->data); + parcel->data = newData; + parcel->length = size; + return true; +} + +static bool ParcelIncrease(HcParcel *parcel, uint32_t size) +{ + if (parcel == NULL || size == 0) { + return false; + } + if (parcel->data == NULL) { + if (parcel->length != 0) { + return false; + } + *parcel = CreateParcel(size, parcel->allocUnit); + if (parcel->data == NULL) { + return false; + } else { + return true; + } + } else { + return ParcelRealloc(parcel, size); + } +} + +static void ParcelRecycle(HcParcel *parcel) +{ + if (parcel == NULL) { + return; + } + if (parcel->data == NULL || parcel->beginPos < parcel->allocUnit) { + return; + } + + 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) { + } + } + parcel->beginPos = 0; + parcel->endPos = contentSize; +} + +static uint32_t GetParcelIncreaseSize(HcParcel *parcel, uint32_t newSize) +{ + if (parcel == NULL || parcel->allocUnit == 0) { + return 0; + } + if (newSize % parcel->allocUnit) { + return (newSize / parcel->allocUnit + 1) * parcel->allocUnit; + } else { + return (newSize / parcel->allocUnit) * parcel->allocUnit; + } +} + +bool ParcelWrite(HcParcel *parcel, const void *src, uint32_t dataSize) +{ + errno_t rc; + if (parcel == NULL || src == NULL || dataSize == 0) { + return false; + } + if (parcel->endPos > PARCEL_UINT_MAX - dataSize) { + return false; + } + if (parcel->endPos + dataSize > parcel->length) { + ParcelRecycle(parcel); + if (parcel->endPos + dataSize > parcel->length) { + uint32_t newSize = GetParcelIncreaseSize(parcel, parcel->endPos + dataSize); + if (!ParcelIncrease(parcel, newSize)) { + return false; + } + } + } + rc = memmove_s(parcel->data + parcel->endPos, dataSize, src, dataSize); + if (rc != EOK) { + return false; + } + parcel->endPos += dataSize; + return true; +} + +bool ParcelWriteInt32(HcParcel *parcel, int src) +{ + return ParcelWrite(parcel, &src, sizeof(src)); +} + +bool ParcelWriteUint32(HcParcel *parcel, uint32_t src) +{ + return ParcelWrite(parcel, &src, sizeof(src)); +} + +bool ParcelWriteInt16(HcParcel *parcel, short src) +{ + return ParcelWrite(parcel, &src, sizeof(src)); +} + +bool ParcelWriteUint16(HcParcel *parcel, uint16_t src) +{ + return ParcelWrite(parcel, &src, sizeof(src)); +} + +bool ParcelWriteInt8(HcParcel *parcel, char src) +{ + return ParcelWrite(parcel, &src, sizeof(src)); +} + +bool ParcelWriteUint8(HcParcel *parcel, uint8_t src) +{ + return ParcelWrite(parcel, &src, sizeof(src)); +} + +bool ParcelWriteUint64(HcParcel *parcel, uint64_t src) +{ + return ParcelWrite(parcel, &src, sizeof(src)); +} + +bool ParcelWriteInt64(HcParcel *parcel, int64_t src) +{ + return ParcelWrite(parcel, &src, sizeof(src)); +} + +bool ParcelReadParcel(HcParcel *src, HcParcel *dst, uint32_t size, bool copy) +{ + if (src == NULL || dst == NULL) { + return false; + } + if (GetParcelDataSize(src) < size) { + return false; + } + if (!ParcelWrite(dst, (void *)GetParcelData(src), size)) { + return false; + } + + if (!copy) { + src->beginPos += size; + } + return true; +} + +bool ParcelCopy(HcParcel *src, HcParcel *dst) +{ + if (src == NULL || dst == NULL) { + return false; + } + if (GetParcelDataSize(src) == 0) { + return true; + } + return ParcelReadParcel(src, dst, GetParcelDataSize(src), true); +} + +void DataRevert(void *data, uint32_t length) +{ + if (data != NULL) { + uint8_t *pc = (uint8_t *)data; + uint32_t i = 0; + for (; i < length / HALF_LEN; ++i) { /* half of the length */ + /* swap p[i] and p[length-i-1] */ + pc[i] ^= pc[length - i - 1]; + pc[length - i - 1] ^= pc[i]; + pc[i] ^= pc[length - i - 1]; + } + } +} + +bool ParcelReadInt32Revert(HcParcel *parcel, int32_t *dst) +{ + bool ret = ParcelRead(parcel, dst, sizeof(int)); + if (ret) { + DataRevert(dst, sizeof(int)); + } + return ret; +} + +bool ParcelReadUint32Revert(HcParcel *parcel, uint32_t *dst) +{ + bool ret = ParcelRead(parcel, dst, sizeof(uint32_t)); + if (ret) { + DataRevert(dst, sizeof(uint32_t)); + } + return ret; +} + +bool ParcelReadInt16Revert(HcParcel *parcel, short *dst) +{ + bool ret = ParcelRead(parcel, dst, sizeof(short)); + if (ret) { + DataRevert(dst, sizeof(short)); + } + return ret; +} + +bool ParcelReadUint16Revert(HcParcel *parcel, uint16_t *dst) +{ + if (parcel == NULL || dst == NULL) { + return false; + } + bool ret = ParcelRead(parcel, dst, sizeof(uint16_t)); + if (ret) { + DataRevert(dst, sizeof(uint16_t)); + } + return ret; +} + +bool ParcelReadInt8Revert(HcParcel *parcel, char *dst) +{ + return ParcelRead(parcel, dst, sizeof(char)); +} + +bool ParcelReadUint8Revert(HcParcel *parcel, uint8_t *dst) +{ + return ParcelRead(parcel, dst, sizeof(uint8_t)); +} + +bool ParcelReadUint64Revert(HcParcel *parcel, uint64_t *dst) +{ + bool ret = ParcelRead(parcel, dst, sizeof(uint64_t)); + if (ret) { + DataRevert(dst, sizeof(uint64_t)); + } + return ret; +} + +bool ParcelReadInt64Revert(HcParcel *parcel, int64_t *dst) +{ + bool ret = ParcelRead(parcel, dst, sizeof(int64_t)); + if (ret) { + DataRevert(dst, sizeof(int64_t)); + } + return ret; +} + +bool ParcelWriteInt32Revert(HcParcel *parcel, int src) +{ + DataRevert(&src, sizeof(src)); + return ParcelWriteInt32(parcel, src); +} + +bool ParcelWriteUint32Revert(HcParcel *parcel, uint32_t src) +{ + DataRevert(&src, sizeof(src)); + return ParcelWriteUint32(parcel, src); +} + +bool ParcelWriteInt16Revert(HcParcel *parcel, short src) +{ + DataRevert(&src, sizeof(src)); + return ParcelWriteInt16(parcel, src); +} + +bool ParcelWriteUint16Revert(HcParcel *parcel, uint16_t src) +{ + DataRevert(&src, sizeof(src)); + return ParcelWriteUint16(parcel, src); +} + +bool ParcelWriteInt8Revert(HcParcel *parcel, char src) +{ + return ParcelWriteInt8(parcel, src); +} + +bool ParcelWriteUint8Revert(HcParcel *parcel, uint8_t src) +{ + return ParcelWriteUint8(parcel, src); +} + +bool ParcelWriteUint64Revert(HcParcel *parcel, uint64_t src) +{ + DataRevert(&src, sizeof(src)); + return ParcelWriteUint64(parcel, src); +} + +bool ParcelWriteInt64Revert(HcParcel *parcel, int64_t src) +{ + DataRevert(&src, sizeof(src)); + return ParcelWriteInt64(parcel, src); +} + +bool ParcelPopBack(HcParcel *parcel, uint32_t size) +{ + if (parcel != NULL && size > 0 && GetParcelDataSize(parcel) >= size) { + parcel->endPos -= size; + return true; + } + return false; +} + +bool ParcelPopFront(HcParcel *parcel, uint32_t size) +{ + if ((parcel != NULL) && (size > 0) && (GetParcelDataSize(parcel) >= size)) { + parcel->beginPos += size; + return true; + } + return false; +} diff --git a/common/src/hcf_string.c b/common/src/hcf_string.c new file mode 100644 index 0000000..8ed5c62 --- /dev/null +++ b/common/src/hcf_string.c @@ -0,0 +1,291 @@ +/* +* Copyright (C) 2021 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 "hcf_string.h" + +const uint32_t STRING_ALLOC_SIZE = 10; +const uint32_t STRING_END_CHAR_LENGTH = 1; +const char STRING_END_CHAR = '\0'; +#define MAX_INT 0x7FFFFFFF +#define MAX_UINT 0xFFFFFFFF + +/* +* Append a HcString +* Notice: It will add '\0' automatically. +* @param self: self pointer. +* @param str: append string. +* @return true (ok), false (error) +*/ +bool StringAppend(HcString *self, HcString str) +{ + uint32_t length = GetParcelDataSize(&str.parcel); + if (self != NULL && length > 0) { + // remove '\0' + ParcelPopBack(&self->parcel, STRING_END_CHAR_LENGTH); + // append string(include '\0') + return StringAppendPointer(self, GetParcelData(&str.parcel)); + } + + return false; +} + +/* +* Append string pointer +* Notice: It will add '\0' automatically. +* @param self: self pointer. +* @param str: string pointer. +* @return true (ok), false (error) +*/ +bool StringAppendPointer(HcString *self, const char *str) +{ + if (self != NULL && str != NULL) { + // remove '\0' + ParcelPopBack(&self->parcel, STRING_END_CHAR_LENGTH); + // append string (include '\0') + return ParcelWrite(&self->parcel, (void *)str, strlen(str) + 1); + } + + return false; +} + +/* +* Append a char +* Notice: It will add '\0' automatically. +* @param self: self pointer. +* @param str: char. +* @return true (ok), false (error) +*/ +bool StringAppendChar(HcString *self, char c) +{ + if (self != NULL && c != STRING_END_CHAR) { + // remove '\0' + ParcelPopBack(&self->parcel, STRING_END_CHAR_LENGTH); + + if (ParcelWriteInt8(&self->parcel, c)) { + return ParcelWriteInt8(&self->parcel, (uint32_t)STRING_END_CHAR); + } + } + + return false; +} + +/* +* Assign a value to the HcString +* Notice: It will add '\0' automatically. +* @param self: self pointer. +* @param str: assign value of ta_sting. +* @return true (ok), false (error) +*/ +bool StringSet(HcString *self, HcString str) +{ + if (self != NULL) { + DeleteParcel(&self->parcel); + return StringAppend(self, str); + } + + return false; +} + +/* +* Assign a value to the HcString +* Notice: It will add '\0' automatically. +* @param self: self pointer. +* @param str: assign value of string pointer. +* @return true (ok), false (error) +*/ +bool StringSetPointer(HcString *self, const char *str) +{ + if (self != NULL) { + DeleteParcel(&self->parcel); + return StringAppendPointer(self, str); + } + + return false; +} + +/* +* Assign a value to the HcString with fixed length +* Notice: It will add '\0' automatically. +* @param self: self pointer. +* @param str: assign value of string pointer. +* @param len: the length of string. +* @return true (ok), false (error) +*/ +bool StringSetPointerWithLength(HcString* self, const char *str, uint32_t len) +{ + if (self == NULL || str == NULL) { + return false; + } + uint32_t strLen = strlen(str); + if (strLen < len) { + return false; + } + DeleteParcel(&self->parcel); + if (len > 0) { + if (false == ParcelWrite(&self->parcel, str, len)) { + return false; + } + } + return ParcelWriteInt8(&self->parcel, (uint32_t)STRING_END_CHAR); +} + +/* +* Get the string pointer data +* @param self: self pointer. +* @return the pointer data of the string +*/ +const char *StringGet(const HcString *self) +{ + if (self == NULL) { + return NULL; + } + + return GetParcelData(&self->parcel); +} + +/* +* Get the length of the string +* @param self: self pointer. +* @return the length of the string +*/ +uint32_t StringLength(const HcString *self) +{ + if (self == NULL) { + return 0; + } else { + uint32_t length = GetParcelDataSize(&self->parcel); + if (length > 0) { + return length - STRING_END_CHAR_LENGTH; + } else { + return 0; + } + } +} + +/* +* Find a char from string +* @param self: self pointer. +* @param c: the char you want find +* @param begin: the position find from +* @return the position of the char +*/ +int StringFind(const HcString *self, char c, uint32_t begin) +{ + if (self == NULL) { + return -1; + } + + // because the return value is int + // so the string length cannot bigger than MAX_INT + uint32_t strLen = StringLength(self); + if (strLen >= MAX_INT) { + return -1; + } + + const char* curChar = StringGet(self); + while (begin < strLen) { + if (*(curChar + begin) == c) { + return begin; + } + ++begin; + } + return -1; +} + +/* +* Get sub string from a string. +* @param self: self pointer. +* @param begin: the begin position of the sub string. +* @param len: the length of the sub string. +* @param dst: the string pointer which saved the sub string content. +* @return the operation result. +*/ +bool StringSubString(const HcString *self, uint32_t begin, uint32_t len, HcString* dst) +{ + if (self == NULL || dst == NULL) { + return false; + } + if (MAX_UINT - len <= begin) { + return false; + } + const char* beingPointer = StringGet(self) + begin; + return StringSetPointerWithLength(dst, beingPointer, len); +} + +/* +* Compare the string with another string. +* @param self: self pointer. +* @param dst: the pointer of another string. +* @return the compare result. +* -1: self is smaller than dst +* 0: self is equal with dst +* 1: self is bigger than dst +*/ +int StringCompare(const HcString *self, const char* dst) +{ + if (self == NULL || dst == NULL) { + return 0; + } + + const char* src = StringGet(self); + if (src == NULL) { + return -1; + } + + do { + if ((*src) > (*dst)) { + return 1; + } else if ((*src) < (*dst)) { + return -1; + } else { + if ((*src) == '\0') { + return 0; + } + ++src; + ++dst; + } + } while (1); + // should never be here + return 0; +} + +/* +* Create a string. +* Notice: You should delete_string when you don't need the string anymore. +* @return return the created string. +*/ +HcString CreateString(void) +{ + HcString str; + str.parcel = CreateParcel(0, STRING_ALLOC_SIZE); + ParcelWriteInt8(&str.parcel, STRING_END_CHAR); + return str; +} + +/* +* Delete a string. In fact it will not destroy the string, +* but only free the allocate memory of the string and reset the member's value +* of the string. +* You can continue to use the string if you want. +* Notice: You should delete the string when you don't need it any more to avoid memory leak. +* @param str: The string you want to delete. +*/ +void DeleteString(HcString *str) +{ + if (str != NULL) { + DeleteParcel(&str->parcel); + } +} diff --git a/common/src/log.c b/common/src/log.c new file mode 100644 index 0000000..96b2139 --- /dev/null +++ b/common/src/log.c @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2021 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 "log.h" + +#include +#include "config.h" +#include "securec.h" + +static void HcfOutPrint(const char *buf, HcfLogLevel level) +{ + switch (level) { + case HCF_LOG_LEVEL_DEBUG: + HCF_LOG_DEBUG(buf); + break; + case HCF_LOG_LEVEL_INFO: + HCF_LOG_INFO(buf); + break; + case HCF_LOG_LEVEL_WARN: + HCF_LOG_WARN(buf); + break; + case HCF_LOG_LEVEL_ERROR: + HCF_LOG_ERROR(buf); + break; + default: + break; + } +} + +void HcfLogPrint(HcfLogLevel level, const char *funName, const char *fmt, ...) +{ + int32_t ulPos = 0; + char outStr[LOG_PRINT_MAX_LEN] = {0}; + int32_t ret = sprintf_s(outStr, sizeof(outStr), "%s: ", funName); + if (ret < 0) { + return; + } + ulPos = strlen(outStr); + va_list arg; + va_start(arg, fmt); + ret = vsprintf_s(&outStr[ulPos], sizeof(outStr) - ulPos, fmt, arg); + va_end(arg); + if (ret < 0) { + return; + } + HcfOutPrint(outStr, level); +} diff --git a/common/src/memory.c b/common/src/memory.c new file mode 100644 index 0000000..aec3736 --- /dev/null +++ b/common/src/memory.c @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2022 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 "memory.h" + +#include "log.h" +#include "securec.h" + +void *HcfMalloc(uint32_t size, char val) +{ + if (size == 0) { + LOGE("malloc size is invalid"); + return NULL; + } + void *addr = malloc(size); + if (addr != NULL) { + (void)memset_s(addr, size, val, size); + } + return addr; +} + +void HcfFree(void *addr) +{ + if (addr != NULL) { + free(addr); + } +} diff --git a/common/src/params_parser.c b/common/src/params_parser.c new file mode 100644 index 0000000..d373ea9 --- /dev/null +++ b/common/src/params_parser.c @@ -0,0 +1,140 @@ +/* + * Copyright (C) 2022 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 "params_parser.h" + +#include +#include +#include "hcf_string.h" +#include "log.h" + +const HcfParaConfig gConfig[] = { + {"ECC224", HCF_ALG_KEY_TYPE, HCF_ALG_ECC_224}, + {"ECC256", HCF_ALG_KEY_TYPE, HCF_ALG_ECC_256}, + {"ECC384", HCF_ALG_KEY_TYPE, HCF_ALG_ECC_384}, + {"ECC512", HCF_ALG_KEY_TYPE, HCF_ALG_ECC_512}, + + {"AES128", HCF_ALG_KEY_TYPE, HCF_ALG_AES_128}, + {"AES192", HCF_ALG_KEY_TYPE, HCF_ALG_AES_192}, + {"AES256", HCF_ALG_KEY_TYPE, HCF_ALG_AES_256}, + {"3DES192", HCF_ALG_KEY_TYPE, HCF_ALG_3DES_192}, + + {"ECB", HCF_ALG_MODE, HCF_ALG_MODE_ECB}, + {"CBC", HCF_ALG_MODE, HCF_ALG_MODE_CBC}, + {"CTR", HCF_ALG_MODE, HCF_ALG_MODE_CTR}, + {"OFB", HCF_ALG_MODE, HCF_ALG_MODE_OFB}, + {"CFB", HCF_ALG_MODE, HCF_ALG_MODE_CFB}, + {"CFB1", HCF_ALG_MODE, HCF_ALG_MODE_CFB1}, + {"CFB8", HCF_ALG_MODE, HCF_ALG_MODE_CFB8}, + {"CFB64", HCF_ALG_MODE, HCF_ALG_MODE_CFB64}, + {"CFB128", HCF_ALG_MODE, HCF_ALG_MODE_CFB128}, + {"CCM", HCF_ALG_MODE, HCF_ALG_MODE_CCM}, + {"GCM", HCF_ALG_MODE, HCF_ALG_MODE_GCM}, + + {"NoPadding", HCF_ALG_PADDING_TYPE, HCF_ALG_NOPADDING}, + {"PKCS5", HCF_ALG_PADDING_TYPE, HCF_ALG_PADDING_PKCS5}, + {"PKCS7", HCF_ALG_PADDING_TYPE, HCF_ALG_PADDING_PKCS7}, + + {"RSA512", HCF_ALG_KEY_TYPE, HCF_OPENSSL_RSA_512}, + {"RSA768", HCF_ALG_KEY_TYPE, HCF_OPENSSL_RSA_768}, + {"RSA1024", HCF_ALG_KEY_TYPE, HCF_OPENSSL_RSA_1024}, + {"RSA2048", HCF_ALG_KEY_TYPE, HCF_OPENSSL_RSA_2048}, + {"RSA3072", HCF_ALG_KEY_TYPE, HCF_OPENSSL_RSA_3072}, + {"RSA4096", HCF_ALG_KEY_TYPE, HCF_OPENSSL_RSA_4096}, + {"RSA8192", HCF_ALG_KEY_TYPE, HCF_OPENSSL_RSA_8192}, + + {"PKCS1", HCF_ALG_PADDING_TYPE, HCF_OPENSSL_RSA_PKCS1_PADDING}, + {"PKCS1_OAEP", HCF_ALG_PADDING_TYPE, HCF_OPENSSL_RSA_PKCS1_OAEP_PADDING}, + {"PSS", HCF_ALG_PADDING_TYPE, HCF_OPENSSL_RSA_PSS_PADDING}, + + {"MD5", HCF_ALG_DIGEST, HCF_OPENSSL_DIGEST_MD5}, + {"SHA1", HCF_ALG_DIGEST, HCF_OPENSSL_DIGEST_SHA1}, + {"SHA224", HCF_ALG_DIGEST, HCF_OPENSSL_DIGEST_SHA224}, + {"SHA256", HCF_ALG_DIGEST, HCF_OPENSSL_DIGEST_SHA256}, + {"SHA384", HCF_ALG_DIGEST, HCF_OPENSSL_DIGEST_SHA384}, + {"SHA512", HCF_ALG_DIGEST, HCF_OPENSSL_DIGEST_SHA512}, + + {"MGF1_MD5", HCF_ALG_MGF1_DIGEST, HCF_OPENSSL_DIGEST_MD5}, + {"MGF1_SHA1", HCF_ALG_MGF1_DIGEST, HCF_OPENSSL_DIGEST_SHA1}, + {"MGF1_SHA224", HCF_ALG_MGF1_DIGEST, HCF_OPENSSL_DIGEST_SHA224}, + {"MGF1_SHA256", HCF_ALG_MGF1_DIGEST, HCF_OPENSSL_DIGEST_SHA256}, + {"MGF1_SHA384", HCF_ALG_MGF1_DIGEST, HCF_OPENSSL_DIGEST_SHA384}, + {"MGF1_SHA512", HCF_ALG_MGF1_DIGEST, HCF_OPENSSL_DIGEST_SHA512}, + + {"PRIMES_2", HCF_ALG_PRIMES, HCF_OPENSSL_PRIMES_2}, + {"PRIMES_3", HCF_ALG_PRIMES, HCF_OPENSSL_PRIMES_3}, + {"PRIMES_4", HCF_ALG_PRIMES, HCF_OPENSSL_PRIMES_4}, + {"PRIMES_5", HCF_ALG_PRIMES, HCF_OPENSSL_PRIMES_5}, + +}; + +const HcfParaConfig* findConfig(const HcString* tag) +{ + if (tag == NULL) { + return NULL; + } + + for (uint32_t i = 0; i < sizeof(gConfig) / sizeof(HcfParaConfig); ++i) { + if (StringCompare(tag, gConfig[i].tag) == 0) { + return &gConfig[i]; + } + } + return NULL; +} + +HcfResult ParseAndSetParameter(const char* paramsStr, void *params, SetParameterFunc setFunc) +{ + if (paramsStr == NULL || setFunc == NULL) { + return HCF_INVALID_PARAMS; + } + HcString str = CreateString(); + HcString subStr = CreateString(); + if (!StringSetPointer(&str, paramsStr)) { + DeleteString(&subStr); + DeleteString(&str); + return HCF_INVALID_PARAMS; + } + HcfResult ret = HCF_INVALID_PARAMS; + uint32_t pos = 0; + do { + int findPos = StringFind(&str, '|', pos); + if (findPos >= 0) { + if (!StringSubString(&str, pos, findPos - pos, &subStr)) { + LOGE("StringSubString failed!"); + break; + } + ret = (*setFunc)(findConfig(&subStr), params); + if (ret != HCF_SUCCESS) { + break; + } + pos = findPos + 1; + } else { + uint32_t strLen = StringLength(&str); + if (strLen < pos) { + break; + } + if (!StringSubString(&str, pos, strLen - pos, &subStr)) { + LOGE("get last string failed!"); + break; + } + ret = (*setFunc)(findConfig(&subStr), params); + break; + } + } while (true); + + DeleteString(&subStr); + DeleteString(&str); + return ret; +} diff --git a/common/src/utils.c b/common/src/utils.c new file mode 100644 index 0000000..e4f10b2 --- /dev/null +++ b/common/src/utils.c @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2022 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 "utils.h" + +#include +#include "log.h" + +bool IsStrValid(const char *str, uint32_t maxLen) +{ + if (str == NULL) { + LOGE("input string is NULL ptr"); + return false; + } + // One byte must be reserved for the terminator. + if (strnlen(str, maxLen) >= maxLen) { + LOGE("input string is beyond max length"); + return false; + } + return true; +} + +bool IsBlobValid(const HcfBlob *blob) +{ + return ((blob != NULL) && (blob->data != NULL) && (blob->len > 0)); +} + +bool IsClassMatch(const HcfObjectBase *obj, const char *className) +{ + if ((obj == NULL) || (obj->getClass() == NULL) || (className == NULL)) { + return false; + } + if (strcmp(obj->getClass(), className) == 0) { + return true; + } else { + LOGE("class is not match. except class: %s, input class: %s", className, obj->getClass()); + return false; + } +} diff --git a/frameworks/BUILD.gn b/frameworks/BUILD.gn new file mode 100644 index 0000000..bcdbaf9 --- /dev/null +++ b/frameworks/BUILD.gn @@ -0,0 +1,101 @@ +# Copyright (C) 2022 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("//build/ohos.gni") +import("//base/security/crypto_framework/frameworks/frameworks.gni") +import("//base/security/crypto_framework/common/common.gni") + +config("framework_config") { + include_dirs = [ + "//base/security/crypto_framework/interfaces/innerkits/algorithm_parameter", + "//base/security/crypto_framework/interfaces/innerkits/certificate", + "//base/security/crypto_framework/interfaces/innerkits/common", + "//base/security/crypto_framework/interfaces/innerkits/crypto_operation", + "//base/security/crypto_framework/interfaces/innerkits/key", + "//base/security/crypto_framework/interfaces/innerkits/rand", + ] +} + +ohos_shared_library("crypto_framework_lib") { + subsystem_name = "security" + part_name = "crypto_framework" + public_configs = [ ":framework_config" ] + include_dirs = [ + "//utils/native/base/include", + ] + include_dirs += framework_inc_path + crypto_framwork_common_inc_path + + sources = framework_files + + cflags = [ + "-fPIC", + "-Wall", + ] + + deps = [ + "//utils/native/base:utils", + "//third_party/openssl:libcrypto_shared", + "//base/security/crypto_framework:crypto_openssl_plugin_lib", + "//base/security/crypto_framework/common:crypto_plugin_common", + ] +} + +ohos_shared_library("cryptoframework_napi") { + subsystem_name = "security" + part_name = "crypto_framework" + relative_install_dir = "module/security" + include_dirs = [ + "//base/security/crypto_framework/interfaces/kits/js", + "//third_party/bounds_checking_function/include", + "//utils/native/base/include", + "//base/security/crypto_framework/frameworks/js/napi/inc", + ] + include_dirs += framework_inc_path + + cflags = [ + "-fPIC", + "-g3", + ] + + sources = [ + "js/napi/src/napi_init.cpp", + "js/napi/src/napi_utils.cpp", + "js/napi/src/napi_key_pair.cpp", + "js/napi/src/napi_pri_key.cpp", + "js/napi/src/napi_pub_key.cpp", + "js/napi/src/napi_asy_key_generator.cpp", + "js/napi/src/napi_sign.cpp", + "js/napi/src/napi_verify.cpp", + "js/napi/src/napi_key_agreement.cpp", + "js/napi/src/napi_x509_certificate.cpp", + "js/napi/src/napi_mac.cpp", + "js/napi/src/napi_md.cpp", + "js/napi/src/napi_rand.cpp", + "js/napi/src/napi_x509_crl.cpp", + "js/napi/src/napi_x509_crl_entry.cpp", + "js/napi/src/napi_sym_key_generator.cpp", + "js/napi/src/napi_cipher.cpp", + "js/napi/src/napi_key.cpp", + "js/napi/src/napi_sym_key.cpp", + "js/napi/src/napi_cert_chain_validator.cpp", + ] + + deps = [ + "//base/security/crypto_framework/frameworks:crypto_framework_lib", + "//third_party/bounds_checking_function:libsec_static", + ] + + external_deps = [ + "napi:ace_napi", + ] +} diff --git a/frameworks/certificate/cert_chain_validator.c b/frameworks/certificate/cert_chain_validator.c new file mode 100644 index 0000000..d10427a --- /dev/null +++ b/frameworks/certificate/cert_chain_validator.c @@ -0,0 +1,217 @@ +/* + * Copyright (C) 2022 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 "cert_chain_validator.h" + +#include + +#include "blob.h" +#include "cert_chain_validator_spi.h" +#include "config.h" +#include "result.h" +#include "log.h" +#include "memory.h" +#include "result.h" +#include "utils.h" +#include "x509_cert_chain_validator_openssl.h" + +#define LV_LENGTH_LEN sizeof(uint16_t) +#define MAX_CERT_PATH_DATA_LEM 8192 + +typedef HcfResult (*CertChainValidatorSpiCreateFunc)(HcfCertChainValidatorSpi **); + +typedef struct { + HcfCertChainValidator base; + HcfCertChainValidatorSpi *spiObj; + char *algorithm; +} CertChainValidatorImpl; + +typedef struct { + CertChainValidatorSpiCreateFunc createFunc; +} HcfCertChainValidatorFuncSet; + +typedef struct { + const char *algorithm; + HcfCertChainValidatorFuncSet funcSet; +} HcfCertChainValidatorAbility; + +static const HcfCertChainValidatorAbility CERT_PATH_VALIDATOR_ABILITY_SET[] = { + { "PKIX", { HcfCertChainValidatorSpiCreate } } +}; + +static const HcfCertChainValidatorFuncSet *FindAbility(const char *algorithm) +{ + for (uint32_t i = 0; i < sizeof(CERT_PATH_VALIDATOR_ABILITY_SET); i++) { + if (strcmp(CERT_PATH_VALIDATOR_ABILITY_SET[i].algorithm, algorithm) == 0) { + return &(CERT_PATH_VALIDATOR_ABILITY_SET[i].funcSet); + } + } + LOGE("Algorithm for certChain validator is not support! [algorithm]: %s", algorithm); + return NULL; +} + +static const char *GetCertChainValidatorClass() +{ + return "HcfCertChainValidator"; +} + +static void DestroyCertChainValidator(HcfObjectBase *self) +{ + if (self == NULL) { + LOGE("Invalid input parameter."); + } + if (!IsClassMatch(self, GetCertChainValidatorClass())) { + LOGE("Class is not match."); + return; + } + CertChainValidatorImpl *validatorImpl = (CertChainValidatorImpl *)self; + OH_HCF_ObjDestroy(validatorImpl->spiObj); + HcfFree(validatorImpl->algorithm); + validatorImpl->algorithm = NULL; + HcfFree(validatorImpl); +} + +static HcfResult ConvertCertBuffer2List(const HcfCertChainData *certChainData, HcfArray *certsList) +{ + uint8_t *msg = certChainData->data; + const uint8_t *boundary = certChainData->data + certChainData->dataLen; + uint32_t index = 0; + HcfResult res = HCF_SUCCESS; + while (msg < boundary) { + if (index >= certsList->count || (msg + LV_LENGTH_LEN > boundary)) { + LOGE("Invalid index for l-v len!"); + res = HCF_INVALID_PARAMS; + break; + } + uint16_t entryLen = 0; + if (memcpy_s(&entryLen, LV_LENGTH_LEN, msg, LV_LENGTH_LEN) != EOK) { + LOGE("Input data in too long."); + return HCF_ERR_COPY; + } + msg = msg + LV_LENGTH_LEN; + certsList->data[index].data = (uint8_t *)HcfMalloc(entryLen, 0); + if (certsList->data[index].data == NULL) { + LOGE("Failed to malloc data for cert, index = %u.", index); + res = HCF_ERR_MALLOC; + break; + } + if (msg + entryLen > boundary) { + LOGE("Entry len is overflow for boundary!"); + res = HCF_INVALID_PARAMS; + break; + } + if (memcpy_s(certsList->data[index].data, entryLen, msg, entryLen) != EOK) { + res = HCF_ERR_COPY; + break; + } + certsList->data[index].len = entryLen; + msg = msg + entryLen; + index++; + } + return res; +} + +static HcfResult Validate(HcfCertChainValidator *self, const HcfCertChainData *certChainData) +{ + if ((self == NULL) || (certChainData == NULL) || (certChainData->dataLen > MAX_CERT_PATH_DATA_LEM)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetCertChainValidatorClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + CertChainValidatorImpl *impl = (CertChainValidatorImpl *)self; + HcfArray certsList = { NULL, 0 }; + certsList.format = certChainData->format; + certsList.count = certChainData->count; + uint32_t certsLen = sizeof(HcfBlob) * certsList.count; + certsList.data = (HcfBlob *)HcfMalloc(certsLen, 0); + if (certsList.data == NULL) { + LOGE("Failed to new memory for certs."); + return HCF_ERR_MALLOC; + } + HcfResult res = ConvertCertBuffer2List(certChainData, &certsList); + if (res != HCF_SUCCESS) { + LOGE("Failed to convert buffer to lists."); + HcfArrayDataClearAndFree(&certsList); + return res; + } + res = impl->spiObj->engineValidate(impl->spiObj, &certsList); + HcfArrayDataClearAndFree(&certsList); + return res; +} + +static const char *GetAlgorithm(HcfCertChainValidator *self) +{ + if (self == NULL) { + LOGE("Invalid input parameter."); + return NULL; + } + if (!IsClassMatch((HcfObjectBase *)self, GetCertChainValidatorClass())) { + LOGE("Class is not match."); + return NULL; + } + CertChainValidatorImpl *impl = (CertChainValidatorImpl *)self; + const char *algo = (const char *)impl->algorithm; + return algo; +} + +HcfResult HcfCertChainValidatorCreate(const char *algorithm, HcfCertChainValidator **pathValidator) +{ + if (!IsStrValid(algorithm, HCF_MAX_STR_LEN) || (pathValidator == NULL)) { + return HCF_INVALID_PARAMS; + } + const HcfCertChainValidatorFuncSet *func = FindAbility(algorithm); + if (func == NULL) { + LOGE("Func is null!"); + return HCF_NOT_SUPPORT; + } + + HcfCertChainValidatorSpi *spiObj = NULL; + HcfResult res = func->createFunc(&spiObj); + if (res != HCF_SUCCESS) { + LOGE("Failed to create certChain validator spi object!"); + return res; + } + CertChainValidatorImpl *returnValidator = (CertChainValidatorImpl *)HcfMalloc(sizeof(CertChainValidatorImpl), 0); + if (returnValidator == NULL) { + LOGE("Failed to allocate returnValidator memory!"); + return HCF_ERR_MALLOC; + } + returnValidator->base.validate = Validate; + returnValidator->base.getAlgorithm = GetAlgorithm; + returnValidator->base.base.destroy = DestroyCertChainValidator; + returnValidator->base.base.getClass = GetCertChainValidatorClass; + returnValidator->spiObj = spiObj; + uint32_t algoNameLen = strlen(algorithm) + 1; + returnValidator->algorithm = (char *)HcfMalloc(algoNameLen, 0); + if (returnValidator->algorithm == NULL) { + LOGE("Failed to allocate algorithm memory!"); + HcfFree(returnValidator); + return HCF_ERR_MALLOC; + } + if (memcpy_s(returnValidator->algorithm, algoNameLen, algorithm, algoNameLen) != HCF_SUCCESS) { + LOGE("Failed to copy for validator algorithm!"); + HcfFree(returnValidator->algorithm); + returnValidator->algorithm = NULL; + HcfFree(returnValidator); + returnValidator = NULL; + return HCF_ERR_COPY; + } + + *pathValidator = (HcfCertChainValidator *)returnValidator; + return HCF_SUCCESS; +} \ No newline at end of file diff --git a/frameworks/certificate/x509_certificate.c b/frameworks/certificate/x509_certificate.c new file mode 100644 index 0000000..3499662 --- /dev/null +++ b/frameworks/certificate/x509_certificate.c @@ -0,0 +1,389 @@ +/* + * Copyright (C) 2022 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 "x509_certificate.h" + +#include + +#include "config.h" +#include "fwk_class.h" +#include "x509_certificate_openssl.h" +#include "log.h" +#include "memory.h" +#include "utils.h" + +typedef HcfResult (*HcfX509CertificateSpiCreateFunc)(const HcfEncodingBlob *, HcfX509CertificateSpi **); + +typedef struct { + HcfX509CertificateSpiCreateFunc createFunc; +} HcfX509CertificateFuncSet; + +typedef struct { + char *certType; + HcfX509CertificateFuncSet funcSet; +} HcfCCertFactoryAbility; + +static const char *GetX509CertificateClass(void) +{ + return HCF_X509_CERTIFICATE_CLASS; +} + +static const HcfCCertFactoryAbility X509_CERTIFICATE_ABILITY_SET[] = { + { "X509", { OpensslX509CertSpiCreate, } } +}; + +static const HcfX509CertificateFuncSet *FindAbility(const char *certType) +{ + if (certType == NULL) { + LOGE("CertType is null!"); + return NULL; + } + for (uint32_t i = 0; i < sizeof(X509_CERTIFICATE_ABILITY_SET); i++) { + if (strcmp(X509_CERTIFICATE_ABILITY_SET[i].certType, certType) == 0) { + return &(X509_CERTIFICATE_ABILITY_SET[i].funcSet); + } + } + LOGE("Cert not support! [cert]: %s", certType); + return NULL; +} + +static void DestroyX509Certificate(HcfObjectBase *self) +{ + if (self == NULL) { + LOGE("Invalid input parameter."); + return; + } + if (!IsClassMatch(self, GetX509CertificateClass())) { + LOGE("Class is not match."); + return; + } + HcfX509CertificateImpl *impl = (HcfX509CertificateImpl *)self; + OH_HCF_ObjDestroy(impl->spiObj); + HcfFree(impl); +} + +static HcfResult Verify(HcfCertificate *self, HcfPubKey *key) +{ + if ((self == NULL) || (key == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertificateClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfX509CertificateImpl *)self)->spiObj->engineVerify( + ((HcfX509CertificateImpl *)self)->spiObj, key); +} + +static HcfResult GetEncoded(HcfCertificate *self, HcfEncodingBlob *encodedByte) +{ + if ((self == NULL) || (encodedByte == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertificateClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfX509CertificateImpl *)self)->spiObj->engineGetEncoded( + ((HcfX509CertificateImpl *)self)->spiObj, encodedByte); +} + +static HcfResult GetPublicKey(HcfCertificate *self, HcfPubKey **keyOut) +{ + if ((self == NULL) || (keyOut == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertificateClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfX509CertificateImpl *)self)->spiObj->engineGetPublicKey( + ((HcfX509CertificateImpl *)self)->spiObj, keyOut); +} + +static HcfResult CheckValidityWithDate(HcfX509Certificate *self, const char *date) +{ + if ((self == NULL) || (date == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertificateClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfX509CertificateImpl *)self)->spiObj->engineCheckValidityWithDate( + ((HcfX509CertificateImpl *)self)->spiObj, date); +} + +long GetVersion(HcfX509Certificate *self) +{ + if (self == NULL) { + LOGE("Invalid input parameter."); + return -1; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertificateClass())) { + LOGE("Class is not match."); + return -1; + } + return ((HcfX509CertificateImpl *)self)->spiObj->engineGetVersion( + ((HcfX509CertificateImpl *)self)->spiObj); +} + +long GetSerialNumber(HcfX509Certificate *self) +{ + if (self == NULL) { + LOGE("Invalid input parameter."); + return -1; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertificateClass())) { + LOGE("Class is not match."); + return -1; + } + return ((HcfX509CertificateImpl *)self)->spiObj->engineGetSerialNumber( + ((HcfX509CertificateImpl *)self)->spiObj); +} + +static HcfResult GetIssuerName(HcfX509Certificate *self, HcfBlob *out) +{ + if ((self == NULL) || (out == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertificateClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfX509CertificateImpl *)self)->spiObj->engineGetIssuerName( + ((HcfX509CertificateImpl *)self)->spiObj, out); +} + +static HcfResult GetSubjectName(HcfX509Certificate *self, HcfBlob *out) +{ + if ((self == NULL) || (out == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertificateClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfX509CertificateImpl *)self)->spiObj->engineGetSubjectName( + ((HcfX509CertificateImpl *)self)->spiObj, out); +} + +static HcfResult GetNotBeforeTime(HcfX509Certificate *self, HcfBlob *outDate) +{ + if ((self == NULL) || (outDate == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertificateClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfX509CertificateImpl *)self)->spiObj->engineGetNotBeforeTime( + ((HcfX509CertificateImpl *)self)->spiObj, outDate); +} + +static HcfResult GetNotAfterTime(HcfX509Certificate *self, HcfBlob *outDate) +{ + if ((self == NULL) || (outDate == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertificateClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfX509CertificateImpl *)self)->spiObj->engineGetNotAfterTime( + ((HcfX509CertificateImpl *)self)->spiObj, outDate); +} + +static HcfResult GetSignature(HcfX509Certificate *self, HcfBlob *sigOut) +{ + if ((self == NULL) || (sigOut == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertificateClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfX509CertificateImpl *)self)->spiObj->engineGetSignature( + ((HcfX509CertificateImpl *)self)->spiObj, sigOut); +} + +static HcfResult GetSignatureAlgName(HcfX509Certificate *self, HcfBlob *outName) +{ + if ((self == NULL) || (outName == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertificateClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfX509CertificateImpl *)self)->spiObj->engineGetSignatureAlgName( + ((HcfX509CertificateImpl *)self)->spiObj, outName); +} + +static HcfResult GetSignatureAlgOid(HcfX509Certificate *self, HcfBlob *out) +{ + if ((self == NULL) || (out == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertificateClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfX509CertificateImpl *)self)->spiObj->engineGetSignatureAlgOid( + ((HcfX509CertificateImpl *)self)->spiObj, out); +} + +static HcfResult GetSignatureAlgParams(HcfX509Certificate *self, HcfBlob *sigAlgParamsOut) +{ + if ((self == NULL) || (sigAlgParamsOut == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertificateClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfX509CertificateImpl *)self)->spiObj->engineGetSignatureAlgParams( + ((HcfX509CertificateImpl *)self)->spiObj, sigAlgParamsOut); +} + +static HcfResult GetKeyUsage(HcfX509Certificate *self, HcfBlob *boolArr) +{ + if ((self == NULL) || (boolArr == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertificateClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfX509CertificateImpl *)self)->spiObj->engineGetKeyUsage( + ((HcfX509CertificateImpl *)self)->spiObj, boolArr); +} + +static HcfResult GetExtKeyUsage(HcfX509Certificate *self, HcfArray *keyUsageOut) +{ + if ((self == NULL) || (keyUsageOut == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertificateClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfX509CertificateImpl *)self)->spiObj->engineGetExtKeyUsage( + ((HcfX509CertificateImpl *)self)->spiObj, keyUsageOut); +} + +static int32_t GetBasicConstraints(HcfX509Certificate *self) +{ + if (self == NULL) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertificateClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfX509CertificateImpl *)self)->spiObj->engineGetBasicConstraints( + ((HcfX509CertificateImpl *)self)->spiObj); +} + +static HcfResult GetSubjectAltNames(HcfX509Certificate *self, HcfArray *outName) +{ + if ((self == NULL) || (outName == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertificateClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfX509CertificateImpl *)self)->spiObj->engineGetSubjectAltNames( + ((HcfX509CertificateImpl *)self)->spiObj, outName); +} + +static HcfResult GetIssuerAltNames(HcfX509Certificate *self, HcfArray *outName) +{ + if ((self == NULL) || (outName == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertificateClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfX509CertificateImpl *)self)->spiObj->engineGetIssuerAltNames( + ((HcfX509CertificateImpl *)self)->spiObj, outName); +} + +HcfResult HcfX509CertificateCreate(const HcfEncodingBlob *inStream, HcfX509Certificate **returnObj) +{ + if ((inStream == NULL) || (inStream->len > HCF_MAX_BUFFER_LEN) || (returnObj == NULL)) { + return HCF_INVALID_PARAMS; + } + const HcfX509CertificateFuncSet *funcSet = FindAbility("X509"); + if (funcSet == NULL) { + LOGE("FuncSet is null!"); + return HCF_NOT_SUPPORT; + } + HcfX509CertificateSpi *spiObj = NULL; + HcfResult res = funcSet->createFunc(inStream, &spiObj); + if (res != HCF_SUCCESS) { + LOGE("Failed to create spi object!"); + return res; + } + HcfX509CertificateImpl *x509CertImpl = (HcfX509CertificateImpl *)HcfMalloc(sizeof(HcfX509CertificateImpl), 0); + if (x509CertImpl == NULL) { + LOGE("Failed to allocate x509CertImpl memory!"); + return HCF_ERR_MALLOC; + } + x509CertImpl->base.base.base.getClass = GetX509CertificateClass; + x509CertImpl->base.base.base.destroy = DestroyX509Certificate; + x509CertImpl->base.base.verify = Verify; + x509CertImpl->base.base.getEncoded = GetEncoded; + x509CertImpl->base.base.getPublicKey = GetPublicKey; + x509CertImpl->base.checkValidityWithDate = CheckValidityWithDate; + x509CertImpl->base.getVersion = GetVersion; + x509CertImpl->base.getSerialNumber = GetSerialNumber; + x509CertImpl->base.getIssuerName = GetIssuerName; + x509CertImpl->base.getSubjectName = GetSubjectName; + x509CertImpl->base.getNotBeforeTime = GetNotBeforeTime; + x509CertImpl->base.getNotAfterTime = GetNotAfterTime; + x509CertImpl->base.getSignature = GetSignature; + x509CertImpl->base.getSignatureAlgName = GetSignatureAlgName; + x509CertImpl->base.getSignatureAlgOid = GetSignatureAlgOid; + x509CertImpl->base.getSignatureAlgParams = GetSignatureAlgParams; + x509CertImpl->base.getKeyUsage = GetKeyUsage; + x509CertImpl->base.getExtKeyUsage = GetExtKeyUsage; + x509CertImpl->base.getBasicConstraints = GetBasicConstraints; + x509CertImpl->base.getSubjectAltNames = GetSubjectAltNames; + x509CertImpl->base.getIssuerAltNames = GetIssuerAltNames; + + x509CertImpl->spiObj = spiObj; + *returnObj = (HcfX509Certificate *)x509CertImpl; + return HCF_SUCCESS; +} \ No newline at end of file diff --git a/frameworks/certificate/x509_crl.c b/frameworks/certificate/x509_crl.c new file mode 100644 index 0000000..9044065 --- /dev/null +++ b/frameworks/certificate/x509_crl.c @@ -0,0 +1,354 @@ +/* + * Copyright (C) 2022 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 "x509_crl.h" + +#include "securec.h" + +#include "config.h" +#include "log.h" +#include "memory.h" +#include "utils.h" +#include "x509_crl.h" +#include "x509_crl_openssl.h" +#include "x509_crl_spi.h" + +#define HCF_X509_CRL_CLASS "HcfX509Crl" +#define OPENSSL_INVALID_VERSION (-1) + +typedef HcfResult (*HcfX509CrlSpiCreateFunc)(const HcfEncodingBlob *, HcfX509CrlSpi **); + +typedef struct { + HcfX509Crl base; + HcfX509CrlSpi *spiObj; + const char *certType; +} HcfX509CrlImpl; + +typedef struct { + HcfX509CrlSpiCreateFunc createFunc; +} HcfX509CrlFuncSet; + +typedef struct { + char *certType; + HcfX509CrlFuncSet funcSet; +} HcfCCertFactoryAbility; + +static const char *GetX509CrlClass(void) +{ + return HCF_X509_CRL_CLASS; +} + +static const HcfCCertFactoryAbility X509_CRL_ABILITY_SET[] = { + { "X509", { HcfCX509CrlSpiCreate, } } +}; + +static const HcfX509CrlFuncSet *FindAbility(const char *certType) +{ + if (certType == NULL) { + LOGE("CertType is null!"); + return NULL; + } + for (uint32_t i = 0; i < sizeof(X509_CRL_ABILITY_SET); i++) { + if (strcmp(X509_CRL_ABILITY_SET[i].certType, certType) == 0) { + return &(X509_CRL_ABILITY_SET[i].funcSet); + } + } + LOGE("Cert not support! [cert]: %s", certType); + return NULL; +} + +static void DestroyX509Crl(HcfObjectBase *self) +{ + if (self == NULL) { + LOGE("Invalid input parameter."); + return; + } + if (!IsClassMatch(self, GetX509CrlClass())) { + LOGE("Class is not match."); + return; + } + HcfX509CrlImpl *impl = (HcfX509CrlImpl *)self; + OH_HCF_ObjDestroy(impl->spiObj); + HcfFree(impl); +} + +static const char *GetType(HcfCrl *self) +{ + if (self == NULL) { + LOGE("Invalid input parameter."); + return NULL; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CrlClass())) { + LOGE("Class is not match."); + return NULL; + } + return ((HcfX509CrlImpl *)self)->spiObj->engineGetType( + ((HcfX509CrlImpl *)self)->spiObj); +} + +static bool IsRevoked(HcfCrl *self, const HcfCertificate *cert) +{ + if ((self == NULL) || (cert == NULL)) { + LOGE("Invalid input parameter."); + return false; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CrlClass())) { + LOGE("Class is not match."); + return false; + } + return ((HcfX509CrlImpl *)self)->spiObj->engineIsRevoked( + ((HcfX509CrlImpl *)self)->spiObj, cert); +} + +static HcfResult Verify(HcfX509Crl *self, HcfPubKey *key) +{ + if ((self == NULL) || (key == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CrlClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfX509CrlImpl *)self)->spiObj->engineVerify( + ((HcfX509CrlImpl *)self)->spiObj, key); +} + +static HcfResult GetEncoded(HcfX509Crl *self, HcfEncodingBlob *encodedByte) +{ + if ((self == NULL) || (encodedByte == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CrlClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfX509CrlImpl *)self)->spiObj->engineGetEncoded( + ((HcfX509CrlImpl *)self)->spiObj, encodedByte); +} + +static long GetVersion(HcfX509Crl *self) +{ + if (self == NULL) { + LOGE("Invalid input parameter."); + return OPENSSL_INVALID_VERSION; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CrlClass())) { + LOGE("Class is not match."); + return OPENSSL_INVALID_VERSION; + } + return ((HcfX509CrlImpl *)self)->spiObj->engineGetVersion( + ((HcfX509CrlImpl *)self)->spiObj); +} + +static HcfResult GetIssuerName(HcfX509Crl *self, HcfBlob *out) +{ + if ((self == NULL) || (out == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CrlClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfX509CrlImpl *)self)->spiObj->engineGetIssuerName( + ((HcfX509CrlImpl *)self)->spiObj, out); +} + +static HcfResult GetLastUpdate(HcfX509Crl *self, HcfBlob *out) +{ + if ((self == NULL) || (out == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CrlClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfX509CrlImpl *)self)->spiObj->engineGetLastUpdate( + ((HcfX509CrlImpl *)self)->spiObj, out); +} + +static HcfResult GetNextUpdate(HcfX509Crl *self, HcfBlob *out) +{ + if ((self == NULL) || (out == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CrlClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfX509CrlImpl *)self)->spiObj->engineGetNextUpdate( + ((HcfX509CrlImpl *)self)->spiObj, out); +} + +static HcfResult GetRevokedCert(HcfX509Crl *self, long serialNumber, HcfX509CrlEntry **entryOut) +{ + if (self == NULL || entryOut == NULL) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CrlClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfX509CrlImpl *)self)->spiObj->engineGetRevokedCert( + ((HcfX509CrlImpl *)self)->spiObj, serialNumber, entryOut); +} + +static HcfResult GetRevokedCertWithCert(HcfX509Crl *self, HcfX509Certificate *cert, HcfX509CrlEntry **entryOut) +{ + if ((self == NULL) || (cert == NULL) || (entryOut == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CrlClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfX509CrlImpl *)self)->spiObj->engineGetRevokedCertWithCert( + ((HcfX509CrlImpl *)self)->spiObj, cert, entryOut); +} + +static HcfResult GetRevokedCerts(HcfX509Crl *self, HcfArray *entrysOut) +{ + if ((self == NULL) || (entrysOut == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CrlClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfX509CrlImpl *)self)->spiObj->engineGetRevokedCerts( + ((HcfX509CrlImpl *)self)->spiObj, entrysOut); +} + +static HcfResult GetTbsInfo(HcfX509Crl *self, HcfBlob *tbsCertListOut) +{ + if ((self == NULL) || (tbsCertListOut == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CrlClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfX509CrlImpl *)self)->spiObj->engineGetTbsInfo( + ((HcfX509CrlImpl *)self)->spiObj, tbsCertListOut); +} + +static HcfResult GetSignature(HcfX509Crl *self, HcfBlob *signature) +{ + if ((self == NULL) || (signature == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CrlClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfX509CrlImpl *)self)->spiObj->engineGetSignature( + ((HcfX509CrlImpl *)self)->spiObj, signature); +} + +static HcfResult GetSignatureAlgName(HcfX509Crl *self, HcfBlob *out) +{ + if ((self == NULL) || (out == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CrlClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfX509CrlImpl *)self)->spiObj->engineGetSignatureAlgName( + ((HcfX509CrlImpl *)self)->spiObj, out); +} + +static HcfResult GetSignatureAlgOid(HcfX509Crl *self, HcfBlob *out) +{ + if ((self == NULL) || (out == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CrlClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfX509CrlImpl *)self)->spiObj->engineGetSignatureAlgOid( + ((HcfX509CrlImpl *)self)->spiObj, out); +} + +static HcfResult GetSignatureAlgParams(HcfX509Crl *self, HcfBlob *sigAlgParamOut) +{ + if ((self == NULL) || (sigAlgParamOut == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CrlClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfX509CrlImpl *)self)->spiObj->engineGetSignatureAlgParams( + ((HcfX509CrlImpl *)self)->spiObj, sigAlgParamOut); +} + +HcfResult HcfX509CrlCreate(const HcfEncodingBlob *inStream, HcfX509Crl **returnObj) +{ + if ((inStream == NULL) || (inStream->data == NULL) || (inStream->len > HCF_MAX_BUFFER_LEN) || (returnObj == NULL)) { + LOGE("FuncSet is null!"); + return HCF_INVALID_PARAMS; + } + const HcfX509CrlFuncSet *funcSet = FindAbility("X509"); + if (funcSet == NULL) { + LOGE("FuncSet is null!"); + return HCF_NOT_SUPPORT; + } + HcfX509CrlSpi *spiObj = NULL; + HcfResult res = funcSet->createFunc(inStream, &spiObj); + if (res != HCF_SUCCESS) { + LOGE("Failed to create spi object!"); + return res; + } + HcfX509CrlImpl *x509CertImpl = (HcfX509CrlImpl *)HcfMalloc(sizeof(HcfX509CrlImpl), 0); + if (x509CertImpl == NULL) { + LOGE("Failed to allocate x509CertImpl memory!"); + return HCF_ERR_MALLOC; + } + x509CertImpl->base.base.base.getClass = GetX509CrlClass; + x509CertImpl->base.base.base.destroy = DestroyX509Crl; + x509CertImpl->base.base.getType = GetType; + x509CertImpl->base.base.isRevoked = IsRevoked; + x509CertImpl->base.verify = Verify; + x509CertImpl->base.getEncoded = GetEncoded; + x509CertImpl->base.getVersion = GetVersion; + x509CertImpl->base.getIssuerName = GetIssuerName; + x509CertImpl->base.getLastUpdate = GetLastUpdate; + x509CertImpl->base.getNextUpdate = GetNextUpdate; + x509CertImpl->base.getRevokedCert = GetRevokedCert; + x509CertImpl->base.getRevokedCertWithCert = GetRevokedCertWithCert; + x509CertImpl->base.getRevokedCerts = GetRevokedCerts; + x509CertImpl->base.getTbsInfo = GetTbsInfo; + x509CertImpl->base.getSignature = GetSignature; + x509CertImpl->base.getSignatureAlgName = GetSignatureAlgName; + x509CertImpl->base.getSignatureAlgOid = GetSignatureAlgOid; + x509CertImpl->base.getSignatureAlgParams = GetSignatureAlgParams; + x509CertImpl->spiObj = spiObj; + *returnObj = (HcfX509Crl *)x509CertImpl; + return HCF_SUCCESS; +} \ No newline at end of file diff --git a/frameworks/crypto_operation/cipher.c b/frameworks/crypto_operation/cipher.c new file mode 100644 index 0000000..50cd65e --- /dev/null +++ b/frameworks/crypto_operation/cipher.c @@ -0,0 +1,272 @@ +/* + * Copyright (C) 2022 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.h" +#include "aes_openssl.h" +#include "config.h" +#include "aes_openssl_common.h" +#include "securec.h" +#include "result.h" +#include "string.h" +#include "log.h" +#include "memory.h" +#include "cipher_rsa_openssl.h" +#include "utils.h" + +typedef HcfResult (*HcfCipherGeneratorSpiCreateFunc)(CipherAttr *, OH_HCF_CipherGeneratorSpi **); + +typedef struct { + HcfCipher super; + OH_HCF_CipherGeneratorSpi *spiObj; + char algoName[HCF_MAX_ALGO_NAME_LEN]; +} CipherGenImpl; + +typedef struct { + HcfCipherGeneratorSpiCreateFunc createFunc; +} HcfCipherGenFuncSet; + +typedef struct { + HCF_ALG_VALUE algo; + HcfCipherGenFuncSet funcSet; +} HcfCipherGenAbility; + +static const HcfCipherGenAbility CIPHER_ABILITY_SET[] = { + { HCF_ALG_RSA, { HcfCipherRsaCipherSpiCreate } }, + { HCF_ALG_AES, { HcfCipherAesGeneratorSpiCreate } }, + { HCF_ALG_DES, { HcfCipherDesGeneratorSpiCreate } } +}; + +static void SetKeyLength(HCF_ALG_PARA_VALUE value, void *cipher) +{ + CipherAttr *cipherAttr = (CipherAttr *)cipher; + + cipherAttr->keySize = value; + + switch (value) { + case HCF_ALG_AES_128: + case HCF_ALG_AES_192: + case HCF_ALG_AES_256: + cipherAttr->algo = HCF_ALG_AES; + break; + case HCF_ALG_3DES_192: + cipherAttr->algo = HCF_ALG_DES; + break; + case HCF_OPENSSL_RSA_512: + case HCF_OPENSSL_RSA_768: + case HCF_OPENSSL_RSA_1024: + case HCF_OPENSSL_RSA_2048: + case HCF_OPENSSL_RSA_3072: + case HCF_OPENSSL_RSA_4096: + case HCF_OPENSSL_RSA_8192: + cipherAttr->algo = HCF_ALG_RSA; + break; + default: + LOGE("Invalid algo %u.", value); + break; + } +} + +static void SetMode(HCF_ALG_PARA_VALUE value, void *cipher) +{ + CipherAttr *cipherAttr = (CipherAttr *)cipher; + cipherAttr->mode = value ; +} + +static void SetPadding(HCF_ALG_PARA_VALUE value, void *cipher) +{ + CipherAttr *cipherAttr = (CipherAttr *)cipher; + cipherAttr->paddingMode = value; +} + +static void SetDigest(HCF_ALG_PARA_VALUE value, CipherAttr *cipher) +{ + cipher->md = value; +} + +static void SetMgf1Digest(HCF_ALG_PARA_VALUE value, CipherAttr *cipher) +{ + cipher->mgf1md = value; +} + +static HcfResult OnSetParameter(const HcfParaConfig *config, void *cipher) +{ + if ((config == NULL) || (cipher == NULL)) { + return HCF_INVALID_PARAMS; + } + HcfResult ret = HCF_SUCCESS; + LOGD("Set Parameter:%s", config->tag); + switch (config->para_type) { + case HCF_ALG_TYPE: + case HCF_ALG_KEY_TYPE: + SetKeyLength(config->para_value, cipher); + break; + case HCF_ALG_MODE: + SetMode(config->para_value, cipher); + break; + case HCF_ALG_PADDING_TYPE: + SetPadding(config->para_value, cipher); + break; + case HCF_ALG_DIGEST: + SetDigest(config->para_value, cipher); + break; + case HCF_ALG_MGF1_DIGEST: + SetMgf1Digest(config->para_value, cipher); + break; + default: + ret = HCF_INVALID_PARAMS; + break; + } + return ret; +} + +static const char *GetCipherGeneratorClass() +{ + return "OH_HCF_CipherGenerator"; +} + +const char *GetAlogrithm(HcfCipher *self) +{ + if (self == NULL) { + LOGE("The input self ptr is NULL!"); + return NULL; + } + if (!IsClassMatch((HcfObjectBase *)self, GetCipherGeneratorClass())) { + LOGE("Class is not match."); + return NULL; + } + return ((CipherGenImpl *)self)->algoName; +} + +static void CipherDestroy(HcfObjectBase *self) +{ + if (self == NULL) { + return; + } + if (!IsClassMatch(self, GetCipherGeneratorClass())) { + LOGE("Class not match."); + return; + } + CipherGenImpl *impl = (CipherGenImpl *)self; + OH_HCF_ObjDestroy(impl->spiObj); + HcfFree(impl); +} + +static HcfResult CipherInit(HcfCipher *self, enum HcfCryptoMode opMode, + HcfKey *key, HcfParamsSpec *params) +{ + if (self == NULL || key == NULL) { /* params maybe is NULL */ + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetCipherGeneratorClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + CipherGenImpl *impl = (CipherGenImpl *)self; + return impl->spiObj->init(impl->spiObj, opMode, key, params); +} + +static HcfResult CipherUpdate(HcfCipher *self, HcfBlob *input, HcfBlob *output) +{ + if ((self == NULL) || (input == NULL) || (output == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetCipherGeneratorClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + CipherGenImpl *impl = (CipherGenImpl *)self; + return impl->spiObj->update(impl->spiObj, input, output); +} + +static HcfResult CipherFinal(HcfCipher *self, HcfBlob *input, HcfBlob *output) +{ + if ((self == NULL) || (output == NULL)) { + LOGE("Invalid input parameter!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetCipherGeneratorClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + CipherGenImpl *impl = (CipherGenImpl *)self; + return impl->spiObj->doFinal(impl->spiObj, input, output); +} + +static void InitCipher(OH_HCF_CipherGeneratorSpi *spiObj, CipherGenImpl *cipher) +{ + cipher->super.init = CipherInit; + cipher->super.update = CipherUpdate; + cipher->super.doFinal = CipherFinal; + cipher->super.getAlgorithm = GetAlogrithm; + cipher->super.base.destroy = CipherDestroy; + cipher->super.base.getClass = GetCipherGeneratorClass; +} + +static const HcfCipherGenFuncSet *FindAbility(CipherAttr *attr) +{ + if (attr == NULL) { + return NULL; + } + for (uint32_t i = 0; i < sizeof(CIPHER_ABILITY_SET) / sizeof(HcfCipherGenAbility); i++) { + if (CIPHER_ABILITY_SET[i].algo == attr->algo) { + return &(CIPHER_ABILITY_SET[i].funcSet); + } + } + LOGE("Algo not support! [Algo]: %d", attr->algo); + return NULL; +} + +HcfResult HcfCipherCreate(const char *transformation, HcfCipher **cipher) +{ + CipherAttr attr = {0}; + if (!IsStrValid(transformation, HCF_MAX_ALGO_NAME_LEN) || (cipher == NULL)) { + LOGE("Invalid input params while creating cipher!"); + return HCF_INVALID_PARAMS; + } + if (ParseAndSetParameter(transformation, (void *)&attr, OnSetParameter) != HCF_SUCCESS) { + LOGE("ParseAndSetParameter failed!"); + return HCF_NOT_SUPPORT; + } + + const HcfCipherGenFuncSet *funcSet = FindAbility(&attr); + if (funcSet == NULL) { + LOGE("FindAbility failed!"); + return HCF_NOT_SUPPORT; + } + CipherGenImpl *returnGenerator = (CipherGenImpl *)HcfMalloc(sizeof(CipherGenImpl), 0); + if (returnGenerator == NULL) { + LOGE("failed to allocate returnGenerator memory!"); + return HCF_ERR_MALLOC; + } + if (strcpy_s(returnGenerator->algoName, HCF_MAX_ALGO_NAME_LEN, transformation) != EOK) { + LOGE("Failed to copy algoName!"); + HcfFree(returnGenerator); + return HCF_ERR_COPY; + } + OH_HCF_CipherGeneratorSpi *spiObj = NULL; + HcfResult res = funcSet->createFunc(&attr, &spiObj); + if (res != HCF_SUCCESS) { + LOGE("Failed to create spi object!"); + HcfFree(returnGenerator); + return res; + } + returnGenerator->spiObj = spiObj; + InitCipher(spiObj, returnGenerator); + + *cipher = (HcfCipher *)returnGenerator; + return res; +} diff --git a/frameworks/crypto_operation/key_agreement.c b/frameworks/crypto_operation/key_agreement.c new file mode 100644 index 0000000..13b92ed --- /dev/null +++ b/frameworks/crypto_operation/key_agreement.c @@ -0,0 +1,182 @@ +/* + * Copyright (C) 2022 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.h" + +#include + +#include "key_agreement_spi.h" +#include "config.h" +#include "ecdh_openssl.h" +#include "log.h" +#include "memory.h" +#include "params_parser.h" +#include "utils.h" + +typedef HcfResult (*HcfKeyAgreementSpiCreateFunc)(HcfKeyAgreementParams *, HcfKeyAgreementSpi **); + +typedef struct { + HcfKeyAgreement base; + + HcfKeyAgreementSpi *spiObj; + + char algoName[HCF_MAX_ALGO_NAME_LEN]; +} HcfKeyAgreementImpl; + +typedef struct { + HCF_ALG_VALUE algo; + + HcfKeyAgreementSpiCreateFunc createSpifunc; +} HcfKeyAgreementGenAbility; + +static const HcfKeyAgreementGenAbility KEY_AGREEMENT_GEN_ABILITY_SET[] = { + { HCF_ALG_ECC, HcfKeyAgreementSpiEcdhCreate } +}; + +static HcfKeyAgreementSpiCreateFunc FindAbility(HcfKeyAgreementParams *params) +{ + for (uint32_t i = 0; i < sizeof(KEY_AGREEMENT_GEN_ABILITY_SET) / sizeof(KEY_AGREEMENT_GEN_ABILITY_SET[0]); i++) { + if (KEY_AGREEMENT_GEN_ABILITY_SET[i].algo == params->algo) { + return KEY_AGREEMENT_GEN_ABILITY_SET[i].createSpifunc; + } + } + LOGE("Algo not support! [Algo]: %d", params->algo); + return NULL; +} + +static void SetKeyType(HCF_ALG_PARA_VALUE value, HcfKeyAgreementParams *paramsObj) +{ + switch (value) { + case HCF_ALG_ECC_224: + case HCF_ALG_ECC_256: + case HCF_ALG_ECC_384: + case HCF_ALG_ECC_512: + paramsObj->keyLen = value; + paramsObj->algo = HCF_ALG_ECC; + break; + default: + break; + } +} + +static HcfResult ParseKeyAgreementParams(const HcfParaConfig* config, void *params) +{ + if (config == NULL || params == NULL) { + return HCF_INVALID_PARAMS; + } + HcfResult ret = HCF_SUCCESS; + HcfKeyAgreementParams *paramsObj = (HcfKeyAgreementParams *)params; + LOGI("Set Parameter: %s", config->tag); + switch (config->para_type) { + case HCF_ALG_KEY_TYPE: + SetKeyType(config->para_value, paramsObj); + break; + default: + ret = HCF_INVALID_PARAMS; + break; + } + return ret; +} + +// export interfaces +static const char *GetKeyAgreementClass(void) +{ + return "HcfKeyAgreement"; +} + +static const char *GetAlgoName(HcfKeyAgreement *self) +{ + if (self == NULL) { + LOGE("The input self ptr is NULL!"); + return NULL; + } + if (!IsClassMatch((HcfObjectBase *)self, GetKeyAgreementClass())) { + return NULL; + } + return ((HcfKeyAgreementImpl *)self)->algoName; +} + +static HcfResult GenerateSecret(HcfKeyAgreement *self, HcfPriKey *priKey, + HcfPubKey *pubKey, HcfBlob *returnSecret) +{ + if (self == NULL) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetKeyAgreementClass())) { + return HCF_INVALID_PARAMS; + } + + return ((HcfKeyAgreementImpl *)self)->spiObj->engineGenerateSecret( + ((HcfKeyAgreementImpl *)self)->spiObj, priKey, pubKey, returnSecret); +} + +static void DestroyKeyAgreement(HcfObjectBase *self) +{ + if (self == NULL) { + return; + } + if (!IsClassMatch((HcfObjectBase *)self, GetKeyAgreementClass())) { + return; + } + HcfKeyAgreementImpl *impl = (HcfKeyAgreementImpl *)self; + OH_HCF_ObjDestroy(impl->spiObj); + impl->spiObj = NULL; + HcfFree(impl); +} + +HcfResult HcfKeyAgreementCreate(const char *algoName, HcfKeyAgreement **returnObj) +{ + if ((!IsStrValid(algoName, HCF_MAX_ALGO_NAME_LEN)) || (returnObj == NULL)) { + return HCF_INVALID_PARAMS; + } + + HcfKeyAgreementParams params = { 0 }; + if (ParseAndSetParameter(algoName, ¶ms, ParseKeyAgreementParams) != HCF_SUCCESS) { + LOGE("Failed to parser parmas!"); + return HCF_INVALID_PARAMS; + } + + HcfKeyAgreementSpiCreateFunc createSpifunc = FindAbility(¶ms); + if (createSpifunc == NULL) { + return HCF_NOT_SUPPORT; + } + + HcfKeyAgreementImpl *returnGenerator = (HcfKeyAgreementImpl *)HcfMalloc(sizeof(HcfKeyAgreementImpl), 0); + if (returnGenerator == NULL) { + LOGE("Failed to allocate returnGenerator memory!"); + return HCF_ERR_MALLOC; + } + if (strcpy_s(returnGenerator->algoName, HCF_MAX_ALGO_NAME_LEN, algoName) != EOK) { + LOGE("Failed to copy algoName!"); + HcfFree(returnGenerator); + return HCF_ERR_COPY; + } + HcfKeyAgreementSpi *spiObj = NULL; + int32_t res = createSpifunc(¶ms, &spiObj); + if (res != HCF_SUCCESS) { + LOGE("Failed to create spi object!"); + HcfFree(returnGenerator); + return res; + } + returnGenerator->base.base.destroy = DestroyKeyAgreement; + returnGenerator->base.base.getClass = GetKeyAgreementClass; + returnGenerator->base.generateSecret = GenerateSecret; + returnGenerator->base.getAlgoName = GetAlgoName; + returnGenerator->spiObj = spiObj; + + *returnObj = (HcfKeyAgreement *)returnGenerator; + return HCF_SUCCESS; +} diff --git a/frameworks/crypto_operation/mac.c b/frameworks/crypto_operation/mac.c new file mode 100644 index 0000000..2de911d --- /dev/null +++ b/frameworks/crypto_operation/mac.c @@ -0,0 +1,190 @@ +/* + * Copyright (C) 2022 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.h" + +#include + +#include "mac_spi.h" +#include "mac_openssl.h" + +#include "log.h" +#include "config.h" +#include "memory.h" +#include "utils.h" + +typedef HcfResult (*HcfMacSpiCreateFunc)(const char *, HcfMacSpi **); + +typedef struct { + HcfMac base; + + HcfMacSpi *spiObj; + + char algoName[HCF_MAX_ALGO_NAME_LEN]; +} HcfMacImpl; + +typedef struct { + char *algoName; + + HcfMacSpiCreateFunc createSpifunc; +} HcfMacAbility; + +static const HcfMacAbility MAC_ABILITY_SET[] = { + { "SHA1", OpensslMacSpiCreate }, + { "SHA224", OpensslMacSpiCreate }, + { "SHA256", OpensslMacSpiCreate }, + { "SHA384", OpensslMacSpiCreate }, + { "SHA512", OpensslMacSpiCreate }, +}; + +static const char *GetMacClass(void) +{ + return "HMAC"; +} + +static HcfMacSpiCreateFunc FindAbility(const char *algoName) +{ + for (uint32_t i = 0; i < (sizeof(MAC_ABILITY_SET) / sizeof(MAC_ABILITY_SET[0])); i++) { + if (strcmp(MAC_ABILITY_SET[i].algoName, algoName) == 0) { + return MAC_ABILITY_SET[i].createSpifunc; + } + } + LOGE("Algo not support! [Algo]: %s", algoName); + return NULL; +} + +static HcfResult Init(HcfMac *self, const HcfSymKey *key) +{ + if ((self == NULL) || (key == NULL)) { + LOGE("The input self ptr or key is NULL!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetMacClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfMacImpl *)self)->spiObj->engineInitMac( + ((HcfMacImpl *)self)->spiObj, key); +} + +static HcfResult Update(HcfMac *self, HcfBlob *input) +{ + if ((self == NULL) || (!IsBlobValid(input))) { + LOGE("The input self ptr or dataBlob is NULL!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetMacClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfMacImpl *)self)->spiObj->engineUpdateMac( + ((HcfMacImpl *)self)->spiObj, input); +} + +static HcfResult DoFinal(HcfMac *self, HcfBlob *output) +{ + if ((self == NULL) || (output == NULL)) { + LOGE("The input self ptr or dataBlob is NULL!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetMacClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfMacImpl *)self)->spiObj->engineDoFinalMac( + ((HcfMacImpl *)self)->spiObj, output); +} + +static uint32_t GetMacLength(HcfMac *self) +{ + if (self == NULL) { + LOGE("The input self ptr is NULL!"); + return 0; + } + if (!IsClassMatch((HcfObjectBase *)self, GetMacClass())) { + LOGE("Class is not match."); + return 0; + } + return ((HcfMacImpl *)self)->spiObj->engineGetMacLength( + ((HcfMacImpl *)self)->spiObj); +} + +static const char *GetAlgoName(HcfMac *self) +{ + if (self == NULL) { + LOGE("The input self ptr is NULL!"); + return NULL; + } + if (!IsClassMatch((HcfObjectBase *)self, GetMacClass())) { + LOGE("Class is not match."); + return NULL; + } + return ((HcfMacImpl *)self)->algoName; +} + +static void MacDestroy(HcfObjectBase *self) +{ + if (self == NULL) { + LOGE("The input self ptr is NULL!"); + return; + } + if (!IsClassMatch((HcfObjectBase *)self, GetMacClass())) { + LOGE("Class is not match."); + return; + } + HcfMacImpl *impl = (HcfMacImpl *)self; + OH_HCF_ObjDestroy(impl->spiObj); + HcfFree(impl); +} + +HcfResult HcfMacCreate(const char *algoName, HcfMac **macApi) +{ + if (!IsStrValid(algoName, HCF_MAX_ALGO_NAME_LEN) || (macApi == NULL)) { + LOGE("Invalid input params while creating mac!"); + return HCF_INVALID_PARAMS; + } + HcfMacSpiCreateFunc createSpifunc = FindAbility(algoName); + if (createSpifunc == NULL) { + LOGE("Algo not supported!"); + return HCF_NOT_SUPPORT; + } + HcfMacImpl *returnMacApi = (HcfMacImpl *)HcfMalloc(sizeof(HcfMacImpl), 0); + if (returnMacApi == NULL) { + LOGE("Failed to allocate Mac Obj memory!"); + return HCF_ERR_MALLOC; + } + if (strcpy_s(returnMacApi->algoName, HCF_MAX_ALGO_NAME_LEN, algoName) != EOK) { + LOGE("Failed to copy algoName!"); + HcfFree(returnMacApi); + return HCF_ERR_COPY; + } + HcfMacSpi *spiObj = NULL; + HcfResult res = createSpifunc(algoName, &spiObj); + if (res != HCF_SUCCESS) { + LOGE("Failed to create spi object!"); + HcfFree(returnMacApi); + return res; + } + returnMacApi->base.base.getClass = GetMacClass; + returnMacApi->base.base.destroy = MacDestroy; + returnMacApi->base.init = Init; + returnMacApi->base.update = Update; + returnMacApi->base.doFinal = DoFinal; + returnMacApi->base.getMacLength = GetMacLength; + returnMacApi->base.getAlgoName = GetAlgoName; + returnMacApi->spiObj = spiObj; + *macApi = (HcfMac *)returnMacApi; + return HCF_SUCCESS; +} \ No newline at end of file diff --git a/frameworks/crypto_operation/md.c b/frameworks/crypto_operation/md.c new file mode 100644 index 0000000..e45aaff --- /dev/null +++ b/frameworks/crypto_operation/md.c @@ -0,0 +1,177 @@ +/* + * Copyright (C) 2022 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.h" + +#include + +#include "sym_key.h" +#include "md_spi.h" +#include "md_openssl.h" + +#include "log.h" +#include "config.h" +#include "memory.h" +#include "utils.h" + +typedef HcfResult (*HcfMdSpiCreateFunc)(const char *, HcfMdSpi **); + +typedef struct { + HcfMd base; + + HcfMdSpi *spiObj; + + char algoName[HCF_MAX_ALGO_NAME_LEN]; +} HcfMdImpl; + +typedef struct { + char *algoName; + + HcfMdSpiCreateFunc createSpifunc; +} HcfMdAbility; + +static const HcfMdAbility MD_ABILITY_SET[] = { + { "SHA1", OpensslMdSpiCreate }, + { "SHA224", OpensslMdSpiCreate }, + { "SHA256", OpensslMdSpiCreate }, + { "SHA384", OpensslMdSpiCreate }, + { "SHA512", OpensslMdSpiCreate }, + { "MD5", OpensslMdSpiCreate }, +}; + +static const char *GetMdClass(void) +{ + return "Md"; +} + +static HcfMdSpiCreateFunc FindAbility(const char *algoName) +{ + for (uint32_t i = 0; i < (sizeof(MD_ABILITY_SET) / sizeof(MD_ABILITY_SET[0])); i++) { + if (strcmp(MD_ABILITY_SET[i].algoName, algoName) == 0) { + return MD_ABILITY_SET[i].createSpifunc; + } + } + LOGE("Algo not support! [Algo]: %s", algoName); + return NULL; +} + +static HcfResult Update(HcfMd *self, HcfBlob *input) +{ + if ((self == NULL) || (!IsBlobValid(input))) { + LOGE("The input self ptr or dataBlob is NULL!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetMdClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfMdImpl *)self)->spiObj->engineUpdateMd( + ((HcfMdImpl *)self)->spiObj, input); +} + +static HcfResult DoFinal(HcfMd *self, HcfBlob *output) +{ + if ((self == NULL) || (output == NULL)) { + LOGE("The input self ptr or dataBlob is NULL!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetMdClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfMdImpl *)self)->spiObj->engineDoFinalMd( + ((HcfMdImpl *)self)->spiObj, output); +} + +static uint32_t GetMdLength(HcfMd *self) +{ + if (self == NULL) { + LOGE("The input self ptr is NULL!"); + return 0; + } + if (!IsClassMatch((HcfObjectBase *)self, GetMdClass())) { + LOGE("Class is not match."); + return 0; + } + return ((HcfMdImpl *)self)->spiObj->engineGetMdLength( + ((HcfMdImpl *)self)->spiObj); +} + +static const char *GetAlgoName(HcfMd *self) +{ + if (self == NULL) { + LOGE("The input self ptr is NULL!"); + return NULL; + } + if (!IsClassMatch((HcfObjectBase *)self, GetMdClass())) { + LOGE("Class is not match."); + return NULL; + } + return ((HcfMdImpl *)self)->algoName; +} + +static void MdDestroy(HcfObjectBase *self) +{ + if (self == NULL) { + LOGE("The input self ptr is NULL!"); + return; + } + if (!IsClassMatch((HcfObjectBase *)self, GetMdClass())) { + LOGE("Class is not match."); + return; + } + HcfMdImpl *impl = (HcfMdImpl *)self; + OH_HCF_ObjDestroy(impl->spiObj); + HcfFree(impl); +} + +HcfResult HcfMdCreate(const char *algoName, HcfMd **mdApi) +{ + if (!IsStrValid(algoName, HCF_MAX_ALGO_NAME_LEN) || (mdApi == NULL)) { + LOGE("Invalid input params while creating md!"); + return HCF_INVALID_PARAMS; + } + HcfMdSpiCreateFunc createSpifunc = FindAbility(algoName); + if (createSpifunc == NULL) { + LOGE("Algo not supported!"); + return HCF_NOT_SUPPORT; + } + HcfMdImpl *returnMdApi = (HcfMdImpl *)HcfMalloc(sizeof(HcfMdImpl), 0); + if (returnMdApi == NULL) { + LOGE("Failed to allocate Md Obj memory!"); + return HCF_ERR_MALLOC; + } + if (strcpy_s(returnMdApi->algoName, HCF_MAX_ALGO_NAME_LEN, algoName) != EOK) { + LOGE("Failed to copy algoName!"); + HcfFree(returnMdApi); + return HCF_ERR_COPY; + } + HcfMdSpi *spiObj = NULL; + HcfResult res = createSpifunc(algoName, &spiObj); + if (res != HCF_SUCCESS) { + LOGE("Failed to create spi object!"); + HcfFree(returnMdApi); + return res; + } + returnMdApi->base.base.getClass = GetMdClass; + returnMdApi->base.base.destroy = MdDestroy; + returnMdApi->base.update = Update; + returnMdApi->base.doFinal = DoFinal; + returnMdApi->base.getMdLength = GetMdLength; + returnMdApi->base.getAlgoName = GetAlgoName; + returnMdApi->spiObj = spiObj; + *mdApi = (HcfMd *)returnMdApi; + return HCF_SUCCESS; +} \ No newline at end of file diff --git a/frameworks/crypto_operation/signature.c b/frameworks/crypto_operation/signature.c new file mode 100644 index 0000000..711a3a1 --- /dev/null +++ b/frameworks/crypto_operation/signature.c @@ -0,0 +1,387 @@ +/* + * Copyright (C) 2022 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 "signature.h" + +#include + +#include "config.h" +#include "ecdsa_openssl.h" +#include "log.h" +#include "memory.h" +#include "params_parser.h" +#include "signature_spi.h" +#include "signature_rsa_openssl.h" +#include "utils.h" + +typedef HcfResult (*HcfSignSpiCreateFunc)(HcfSignatureParams *, HcfSignSpi **); +typedef HcfResult (*HcfVerifySpiCreateFunc)(HcfSignatureParams *, HcfVerifySpi **); + +typedef struct { + HcfSign base; + + HcfSignSpi *spiObj; + + char algoName[HCF_MAX_ALGO_NAME_LEN]; +} HcfSignImpl; + +typedef struct { + HcfVerify base; + + HcfVerifySpi *spiObj; + + char algoName[HCF_MAX_ALGO_NAME_LEN]; +} HcfVerifyImpl; + +typedef struct { + const char *algoType; + + uint32_t digestAlg; + + int32_t keyLen; + + int32_t padding; +} HcfEcdsaParams; + +typedef struct { + HCF_ALG_VALUE algo; + + HcfSignSpiCreateFunc createFunc; +} HcfSignGenAbility; + +typedef struct { + HCF_ALG_VALUE algo; + + HcfVerifySpiCreateFunc createFunc; +} HcfVerifyGenAbility; + +static const HcfSignGenAbility SIGN_GEN_ABILITY_SET[] = { + { HCF_ALG_ECC, HcfSignSpiEcdsaCreate }, + { HCF_ALG_RSA, HcfSignSpiRsaCreate } +}; + +static const HcfVerifyGenAbility VERIFY_GEN_ABILITY_SET[] = { + { HCF_ALG_ECC, HcfVerifySpiEcdsaCreate }, + { HCF_ALG_RSA, HcfVerifySpiRsaCreate } +}; + +static HcfSignSpiCreateFunc FindSignAbility(HcfSignatureParams *params) +{ + for (uint32_t i = 0; i < sizeof(SIGN_GEN_ABILITY_SET) / sizeof(SIGN_GEN_ABILITY_SET[0]); i++) { + if (SIGN_GEN_ABILITY_SET[i].algo == params->algo) { + return SIGN_GEN_ABILITY_SET[i].createFunc; + } + } + LOGE("Algo not support! [Algo]: %d", params->algo); + return NULL; +} + +static HcfVerifySpiCreateFunc FindVerifyAbility(HcfSignatureParams *params) +{ + for (uint32_t i = 0; i < sizeof(VERIFY_GEN_ABILITY_SET) / sizeof(VERIFY_GEN_ABILITY_SET[0]); i++) { + if (VERIFY_GEN_ABILITY_SET[i].algo == params->algo) { + return VERIFY_GEN_ABILITY_SET[i].createFunc; + } + } + LOGE("Algo not support! [Algo]: %d", params->algo); + return NULL; +} + +static void SetKeyType(HCF_ALG_PARA_VALUE value, HcfSignatureParams *paramsObj) +{ + switch (value) { + case HCF_ALG_ECC_224: + case HCF_ALG_ECC_256: + case HCF_ALG_ECC_384: + case HCF_ALG_ECC_512: + paramsObj->keyLen = value; + paramsObj->algo = HCF_ALG_ECC; + break; + case HCF_OPENSSL_RSA_512: + case HCF_OPENSSL_RSA_768: + case HCF_OPENSSL_RSA_1024: + case HCF_OPENSSL_RSA_2048: + case HCF_OPENSSL_RSA_3072: + case HCF_OPENSSL_RSA_4096: + case HCF_OPENSSL_RSA_8192: + paramsObj->algo = HCF_ALG_RSA; + break; + default: + LOGE("there is not matched algorithm."); + break; + } +} + +static HcfResult ParseSignatureParams(const HcfParaConfig* config, void *params) +{ + if (config == NULL || params == NULL) { + return HCF_INVALID_PARAMS; + } + HcfResult ret = HCF_SUCCESS; + HcfSignatureParams *paramsObj = (HcfSignatureParams *)params; + LOGI("Set Parameter: %s", config->tag); + switch (config->para_type) { + case HCF_ALG_KEY_TYPE: + SetKeyType(config->para_value, paramsObj); + break; + case HCF_ALG_DIGEST: + paramsObj->md = config->para_value; + break; + case HCF_ALG_PADDING_TYPE: + paramsObj->padding = config->para_value; + break; + case HCF_ALG_MGF1_DIGEST: + paramsObj->mgf1md = config->para_value; + break; + default: + ret = HCF_INVALID_PARAMS; + break; + } + return ret; +} + +static const char *GetSignClass(void) +{ + return "HcfSign"; +} + +static const char *GetVerifyClass(void) +{ + return "HcfVerify"; +} + +static const char *GetSignAlgoName(HcfSign *self) +{ + if (self == NULL) { + LOGE("The input self ptr is NULL!"); + return NULL; + } + if (!IsClassMatch((HcfObjectBase *)self, GetSignClass())) { + return NULL; + } + return ((HcfSignImpl *)self)->algoName; +} + +static const char *GetVerifyAlgoName(HcfVerify *self) +{ + if (self == NULL) { + LOGE("The input self ptr is NULL!"); + return NULL; + } + if (!IsClassMatch((HcfObjectBase *)self, GetVerifyClass())) { + return NULL; + } + return ((HcfVerifyImpl *)self)->algoName; +} + +static void DestroySign(HcfObjectBase *self) +{ + if (self == NULL) { + return; + } + if (!IsClassMatch(self, GetSignClass())) { + return; + } + HcfSignImpl *impl = (HcfSignImpl *)self; + OH_HCF_ObjDestroy(impl->spiObj); + impl->spiObj = NULL; + HcfFree(impl); +} + +static void DestroyVerify(HcfObjectBase *self) +{ + if (self == NULL) { + return; + } + if (!IsClassMatch(self, GetVerifyClass())) { + return; + } + HcfVerifyImpl *impl = (HcfVerifyImpl *)self; + OH_HCF_ObjDestroy(impl->spiObj); + impl->spiObj = NULL; + HcfFree(impl); +} + +static HcfResult SignInit(HcfSign *self, HcfParamsSpec *params, HcfPriKey *privateKey) +{ + if (self == NULL) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + + if (!IsClassMatch((HcfObjectBase *)self, GetSignClass())) { + return HCF_INVALID_PARAMS; + } + return ((HcfSignImpl *)self)->spiObj->engineInit(((HcfSignImpl *)self)->spiObj, params, privateKey); +} + +static HcfResult SignUpdate(HcfSign *self, HcfBlob *data) +{ + if (self == NULL) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + + if (!IsClassMatch((HcfObjectBase *)self, GetSignClass())) { + return HCF_INVALID_PARAMS; + } + return ((HcfSignImpl *)self)->spiObj->engineUpdate(((HcfSignImpl *)self)->spiObj, data); +} + +static HcfResult SignDoFinal(HcfSign *self, HcfBlob *data, HcfBlob *returnSignatureData) +{ + if (self == NULL) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + + if (!IsClassMatch((HcfObjectBase *)self, GetSignClass())) { + return HCF_INVALID_PARAMS; + } + return ((HcfSignImpl *)self)->spiObj->engineSign(((HcfSignImpl *)self)->spiObj, data, returnSignatureData); +} + +static HcfResult VerifyInit(HcfVerify *self, HcfParamsSpec *params, HcfPubKey *publicKey) +{ + if (self == NULL) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + + if (!IsClassMatch((HcfObjectBase *)self, GetVerifyClass())) { + return HCF_INVALID_PARAMS; + } + return ((HcfVerifyImpl *)self)->spiObj->engineInit(((HcfVerifyImpl *)self)->spiObj, params, publicKey); +} + +static HcfResult VerifyUpdate(HcfVerify *self, HcfBlob *data) +{ + if (self == NULL) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + + if (!IsClassMatch((HcfObjectBase *)self, GetVerifyClass())) { + return HCF_INVALID_PARAMS; + } + return ((HcfVerifyImpl *)self)->spiObj->engineUpdate(((HcfVerifyImpl *)self)->spiObj, data); +} + +static bool VerifyDoFinal(HcfVerify *self, HcfBlob *data, HcfBlob *signatureData) +{ + if (self == NULL) { + LOGE("Invalid input parameter."); + return false; + } + if (!IsClassMatch((HcfObjectBase *)self, GetVerifyClass())) { + return false; + } + return ((HcfVerifyImpl *)self)->spiObj->engineVerify(((HcfVerifyImpl *)self)->spiObj, data, signatureData); +} + +HcfResult HcfSignCreate(const char *algoName, HcfSign **returnObj) +{ + LOGI("HcfSignCreate start"); + if ((!IsStrValid(algoName, HCF_MAX_ALGO_NAME_LEN)) || (returnObj == NULL)) { + return HCF_INVALID_PARAMS; + } + + HcfSignatureParams params = { 0 }; + if (ParseAndSetParameter(algoName, ¶ms, ParseSignatureParams) != HCF_SUCCESS) { + LOGE("Failed to parser parmas!"); + return HCF_INVALID_PARAMS; + } + + HcfSignSpiCreateFunc createSpifunc = FindSignAbility(¶ms); + if (createSpifunc == NULL) { + LOGE("Can not find ability."); + return HCF_NOT_SUPPORT; + } + + HcfSignImpl *returnSign = (HcfSignImpl *)HcfMalloc(sizeof(HcfSignImpl), 0); + if (returnSign == NULL) { + LOGE("Failed to allocate returnSign memory!"); + return HCF_ERR_MALLOC; + } + if (strcpy_s(returnSign->algoName, HCF_MAX_ALGO_NAME_LEN, algoName) != EOK) { + LOGE("Failed to copy algoName!"); + HcfFree(returnSign); + return HCF_ERR_COPY; + } + HcfSignSpi *spiObj = NULL; + int32_t res = createSpifunc(¶ms, &spiObj); + if (res != HCF_SUCCESS) { + LOGE("Failed to create spi object!"); + HcfFree(returnSign); + return res; + } + returnSign->base.base.destroy = DestroySign; + returnSign->base.base.getClass = GetSignClass; + returnSign->base.getAlgoName = GetSignAlgoName; + returnSign->base.init = SignInit; + returnSign->base.update = SignUpdate; + returnSign->base.sign = SignDoFinal; + returnSign->spiObj = spiObj; + + *returnObj = (HcfSign *)returnSign; + LOGI("HcfSignCreate end"); + return HCF_SUCCESS; +} + +HcfResult HcfVerifyCreate(const char *algoName, HcfVerify **returnObj) +{ + LOGI("HcfVerifyCreate start"); + if ((!IsStrValid(algoName, HCF_MAX_ALGO_NAME_LEN)) || (returnObj == NULL)) { + return HCF_INVALID_PARAMS; + } + HcfSignatureParams params = {0}; + if (ParseAndSetParameter(algoName, ¶ms, ParseSignatureParams) != HCF_SUCCESS) { + LOGE("Failed to parser parmas!"); + return HCF_INVALID_PARAMS; + } + + HcfVerifySpiCreateFunc createSpifunc = FindVerifyAbility(¶ms); + if (createSpifunc == NULL) { + return HCF_NOT_SUPPORT; + } + + HcfVerifyImpl *returnVerify = (HcfVerifyImpl *)HcfMalloc(sizeof(HcfVerifyImpl), 0); + if (returnVerify == NULL) { + LOGE("Failed to allocate returnVerify memory!"); + return HCF_ERR_MALLOC; + } + if (strcpy_s(returnVerify->algoName, HCF_MAX_ALGO_NAME_LEN, algoName) != EOK) { + LOGE("Failed to copy algoName!"); + HcfFree(returnVerify); + return HCF_ERR_COPY; + } + HcfVerifySpi *spiObj = NULL; + int32_t res = createSpifunc(¶ms, &spiObj); + if (res != HCF_SUCCESS) { + LOGE("Failed to create spi object!"); + HcfFree(returnVerify); + return res; + } + returnVerify->base.base.destroy = DestroyVerify; + returnVerify->base.base.getClass = GetVerifyClass; + returnVerify->base.getAlgoName = GetVerifyAlgoName; + returnVerify->base.init = VerifyInit; + returnVerify->base.update = VerifyUpdate; + returnVerify->base.verify = VerifyDoFinal; + returnVerify->spiObj = spiObj; + *returnObj = (HcfVerify *)returnVerify; + LOGI("HcfVerifyCreate end"); + return HCF_SUCCESS; +} diff --git a/frameworks/frameworks.gni b/frameworks/frameworks.gni new file mode 100644 index 0000000..5332e62 --- /dev/null +++ b/frameworks/frameworks.gni @@ -0,0 +1,78 @@ +# Copyright (C) 2022 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. + +base_path = "//base/security/crypto_framework" +framework_path = "//base/security/crypto_framework/frameworks" +plugin_path = "//base/security/crypto_framework/plugin" + +framework_inc_path = [ + "${base_path}/interfaces/innerkits/algorithm_parameter", + "${base_path}/interfaces/innerkits/certificate", + "${base_path}/interfaces/innerkits/common", + "${base_path}/interfaces/innerkits/crypto_operation", + "${base_path}/interfaces/innerkits/key", + "${base_path}/interfaces/innerkits/rand", + "${base_path}/common/inc", + "${plugin_path}/openssl_plugin/aes/inc", + "${plugin_path}/openssl_plugin/certificate/inc", + "${plugin_path}/openssl_plugin/crypto_operation/key_agreement/inc", + "${plugin_path}/openssl_plugin/crypto_operation/signature/inc", + "${plugin_path}/openssl_plugin/crypto_operation/aes/inc", + "${plugin_path}/openssl_plugin/key/sym_key_generator/inc", + "${plugin_path}/openssl_plugin/key/asy_key_generator/inc", + "${plugin_path}/openssl_plugin/certificate/inc", + "${plugin_path}/openssl_plugin/crypto_operation/hmac/inc", + "${plugin_path}/openssl_plugin/crypto_operation/md/inc", + "${plugin_path}/openssl_plugin/crypto_operation/rsa/inc", + "${plugin_path}/openssl_plugin/rand/inc", + "${framework_path}/spi", +] + +framework_certificate_files = [ + "${framework_path}/certificate/cert_chain_validator.c", + "${framework_path}/certificate/x509_certificate.c", + "${framework_path}/certificate/x509_crl.c", +] + +framework_cipher_files = [ + "${framework_path}/crypto_operation/cipher.c", +] + +framework_signature_files = [ + "${framework_path}/crypto_operation/signature.c", +] + +framework_key_agreement_files = [ + "${framework_path}/crypto_operation/key_agreement.c", +] + +framework_key_files = [ + "${framework_path}/key/asy_key_generator.c", + "${framework_path}/key/sym_key_generator.c", +] + +framework_mac_files = [ + "${framework_path}/crypto_operation/mac.c", +] + +framework_rand_files = [ + "${framework_path}/rand/rand.c", +] + +framework_md_files = [ + "${framework_path}/crypto_operation/md.c", +] + +framework_files = framework_certificate_files + framework_key_agreement_files + + framework_signature_files + framework_cipher_files + framework_key_files + framework_mac_files + + framework_rand_files + framework_md_files diff --git a/frameworks/js/napi/inc/napi_asy_key_generator.h b/frameworks/js/napi/inc/napi_asy_key_generator.h new file mode 100644 index 0000000..620707d --- /dev/null +++ b/frameworks/js/napi/inc/napi_asy_key_generator.h @@ -0,0 +1,48 @@ +/* + * Copyright (C) 2022 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_NAPI_ASY_KEY_GENERATOR_H +#define HCF_NAPI_ASY_KEY_GENERATOR_H + +#include +#include "asy_key_generator.h" +#include "log.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +namespace OHOS { +namespace CryptoFramework { +class NapiAsyKeyGenerator { +public: + NapiAsyKeyGenerator(HcfAsyKeyGenerator *generator); + ~NapiAsyKeyGenerator(); + + HcfAsyKeyGenerator *GetAsyKeyGenerator(); + + static void DefineAsyKeyGeneratorJSClass(napi_env env, napi_value exports); + static napi_value AsyKeyGeneratorConstructor(napi_env env, napi_callback_info info); + static napi_value CreateJsAsyKeyGenerator(napi_env env, napi_callback_info info); + + static napi_value JsGenerateKeyPair(napi_env env, napi_callback_info info); + static napi_value JsConvertKey(napi_env env, napi_callback_info info); + + static thread_local napi_ref classRef_; + +private: + HcfAsyKeyGenerator *generator_ = nullptr; +}; +} // namespace CryptoFramework +} // namespace OHOS +#endif diff --git a/frameworks/js/napi/inc/napi_cert_chain_validator.h b/frameworks/js/napi/inc/napi_cert_chain_validator.h new file mode 100644 index 0000000..a31fcaa --- /dev/null +++ b/frameworks/js/napi/inc/napi_cert_chain_validator.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2022 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 NAPI_CERT_CHAIN_VALIDATOR_H +#define NAPI_CERT_CHAIN_VALIDATOR_H + +#include + +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "cert_chain_validator.h" + +namespace OHOS { +namespace CryptoFramework { + +class NapiCertChainValidator { +public: + NapiCertChainValidator(HcfCertChainValidator *certChainValidator); + ~NapiCertChainValidator(); + + static void DefineCertChainValidatorJSClass(napi_env env, napi_value exports); + static napi_value CreateCertChainValidator(napi_env env, napi_callback_info info); + + napi_value Validate(napi_env env, napi_callback_info info); + + HcfCertChainValidator *GetCertChainValidator() + { + return certChainValidator_; + } + + static napi_ref classRef_; + +private: + HcfCertChainValidator *certChainValidator_ = nullptr; +}; + +} // namespace CryptoFramework +} // namespace OHOS + +#endif // NAPI_CERT_CHAIN_VALIDATOR_H diff --git a/frameworks/js/napi/inc/napi_cipher.h b/frameworks/js/napi/inc/napi_cipher.h new file mode 100644 index 0000000..3c9952d --- /dev/null +++ b/frameworks/js/napi/inc/napi_cipher.h @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2022 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 NAPI_CIPHER_H +#define NAPI_CIPHER_H + +#include + +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" +#include "cipher.h" + +namespace OHOS { +namespace CryptoFramework { + +class NapiCipher { +public: + NapiCipher(HcfCipher *cipher); + ~NapiCipher(); + + static void DefineCipherJSClass(napi_env env, napi_value exports); + static napi_value CreateCipher(napi_env env, napi_callback_info info); + static napi_value CipherConstructor(napi_env env, napi_callback_info info); + + static napi_value JsCipherInit(napi_env env, napi_callback_info info); + static napi_value JsCipherUpdate(napi_env env, napi_callback_info info); + static napi_value JsCipherDoFinal(napi_env env, napi_callback_info info); + static napi_value JsGetAlgorithm(napi_env env, napi_callback_info info); + HcfCipher *GetCipher(); + + static thread_local napi_ref classRef_; +private: + HcfCipher *cipher_; +}; + +} // namespace CryptoFramework +} // namespace OHOS +#endif diff --git a/frameworks/js/napi/inc/napi_crypto_framework_defines.h b/frameworks/js/napi/inc/napi_crypto_framework_defines.h new file mode 100644 index 0000000..544ce6f --- /dev/null +++ b/frameworks/js/napi/inc/napi_crypto_framework_defines.h @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2022 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 NAPI_CRYPTO_FRAMEWORK_DEFINES_H +#define NAPI_CRYPTO_FRAMEWORK_DEFINES_H + +#include + +namespace OHOS { +namespace CryptoFramework { +constexpr size_t CALLBACK_SIZE = 1; +constexpr size_t ARGS_SIZE_ZERO = 0; +constexpr size_t ARGS_SIZE_ONE = 1; +constexpr size_t ARGS_SIZE_TWO = 2; +constexpr size_t ARGS_SIZE_THREE = 3; +constexpr size_t ARGS_SIZE_FOUR = 4; +constexpr size_t GCM_AUTH_TAG_LEN = 16; +constexpr size_t CCM_AUTH_TAG_LEN = 12; +constexpr int32_t PARAM0 = 0; +constexpr int32_t PARAM1 = 1; +constexpr int32_t PARAM2 = 2; +constexpr uint32_t JS_ERR_DEFAULT_ERR = 0; +constexpr uint32_t JS_ERR_INVALID_PARAMS = 401; +constexpr uint32_t JS_ERR_NOT_SUPPORT = 801; +constexpr uint32_t JS_ERR_OUT_OF_MEMORY = 17620001; +constexpr uint32_t JS_ERR_INTERNAL_ERROR = 17620002; +constexpr uint32_t JS_ERR_CRYPTO_OPERATION = 17630001; +constexpr uint32_t JS_ERR_CERT_SIGNATURE_FAILURE = 17630002; +constexpr uint32_t JS_ERR_CERT_NOT_YET_VALID = 17630003; +constexpr uint32_t JS_ERR_CERT_HAS_EXPIRED = 17630004; +constexpr uint32_t JS_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY = 17630005; +constexpr uint32_t JS_ERR_KEYUSAGE_NO_CERTSIGN = 17630006; +constexpr uint32_t JS_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE = 17630007; +const std::string CRYPTO_TAG_DATA = "data"; +const std::string CRYPTO_TAG_ERR_CODE = "code"; +const std::string CRYPTO_TAG_ERR_MSG = "message"; +const std::string CRYPTO_TAG_COUNT = "count"; +const std::string CRYPTO_TAG_ENCODING_FORMAT = "encodingFormat"; +const std::string CRYPTO_TAG_ALGORITHM = "algorithm"; +const std::string CRYPTO_TAG_ALG_NAME = "algName"; +const std::string CRYPTO_TAG_FORMAT = "format"; +const std::string CRYPTO_TAG_PUB_KEY = "pubKey"; +const std::string CRYPTO_TAG_PRI_KEY = "priKey"; +const std::string IV_PARAMS = "iv"; +const std::string AAD_PARAMS = "aad"; +const std::string AUTHTAG_PARAMS = "authTag"; +const std::string ALGO_PARAMS = "algoName"; +const std::string IV_PARAMS_SPEC = "IvParamsSpec"; +const std::string GCM_PARAMS_SPEC = "GcmParamsSpec"; +const std::string CCM_PARAMS_SPEC = "CcmParamsSpec"; +const std::string COMMON_ERR_MSG = "An exception occurs."; + +enum CfAsyncType { + ASYNC_TYPE_CALLBACK = 1, + ASYNC_TYPE_PROMISE = 2 +}; + +} // namespace CryptoFramework +} // namespace OHOS + +#endif // NAPI_CRYPTO_FRAMEWORK_DEFINES_H diff --git a/frameworks/js/napi/inc/napi_key.h b/frameworks/js/napi/inc/napi_key.h new file mode 100644 index 0000000..4213312 --- /dev/null +++ b/frameworks/js/napi/inc/napi_key.h @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2022 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_NAPI_HCF_KEY_H +#define HCF_NAPI_HCF_KEY_H + +#include +#include "log.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#include "key.h" + +namespace OHOS { +namespace CryptoFramework { +class NapiKey { +public: + NapiKey(HcfKey *symKey); + ~NapiKey(); + HcfKey *GetHcfKey(); + + static void DefineHcfKeyJSClass(napi_env env); + static napi_value CreateHcfKey(napi_env env); + static napi_value KeyConstructor(napi_env env, napi_callback_info info); + + static napi_value JsGetAlgorithm(napi_env env, napi_callback_info info); + static napi_value JsGetEncoded(napi_env env, napi_callback_info info); + static napi_value JsGetFormat(napi_env env, napi_callback_info info); + + static thread_local napi_ref classRef_; +private: + HcfKey *hcfKey_; +}; +} // namespace CryptoFramework +} // namespace OHOS +#endif diff --git a/frameworks/js/napi/inc/napi_key_agreement.h b/frameworks/js/napi/inc/napi_key_agreement.h new file mode 100644 index 0000000..94e2491 --- /dev/null +++ b/frameworks/js/napi/inc/napi_key_agreement.h @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2022 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_NAPI_KEY_AGREEMENT_H +#define HCF_NAPI_KEY_AGREEMENT_H + +#include +#include "log.h" +#include "key_agreement.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +namespace OHOS { +namespace CryptoFramework { +class NapiKeyAgreement { +public: + NapiKeyAgreement(HcfKeyAgreement *keyAgreement); + ~NapiKeyAgreement(); + + HcfKeyAgreement *GetKeyAgreement(); + + static void DefineKeyAgreementJSClass(napi_env env, napi_value exports); + static napi_value KeyAgreementConstructor(napi_env env, napi_callback_info info); + static napi_value CreateJsKeyAgreement(napi_env env, napi_callback_info info); + + static napi_value JsGenerateSecret(napi_env env, napi_callback_info info); + + static thread_local napi_ref classRef_; + +private: + HcfKeyAgreement *keyAgreement_ = nullptr; +}; +} // namespace CryptoFramework +} // namespace OHOS +#endif diff --git a/frameworks/js/napi/inc/napi_key_pair.h b/frameworks/js/napi/inc/napi_key_pair.h new file mode 100644 index 0000000..a08e764 --- /dev/null +++ b/frameworks/js/napi/inc/napi_key_pair.h @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2022 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_NAPI_KEY_PAIR_H +#define HCF_NAPI_KEY_PAIR_H + +#include +#include "log.h" +#include "key_pair.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +namespace OHOS { +namespace CryptoFramework { +class NapiKeyPair { +public: + NapiKeyPair(HcfKeyPair *keyPair); + ~NapiKeyPair(); + + napi_value ConvertToJsKeyPair(napi_env env); + + static void DefineKeyPairJSClass(napi_env env); + static napi_value KeyPairConstructor(napi_env env, napi_callback_info info); + + static thread_local napi_ref classRef_; + +private: + HcfKeyPair *keyPair_ = nullptr; +}; +} // namespace CryptoFramework +} // namespace OHOS +#endif diff --git a/frameworks/js/napi/inc/napi_mac.h b/frameworks/js/napi/inc/napi_mac.h new file mode 100644 index 0000000..10fe060 --- /dev/null +++ b/frameworks/js/napi/inc/napi_mac.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2022 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 NAPI_MAC_H +#define NAPI_MAC_H + +#include + +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" + +#include "mac.h" + +namespace OHOS { +namespace CryptoFramework { + +class NapiMac { +public: + NapiMac(HcfMac *macObj); + ~NapiMac(); + static napi_ref classRef_; + + static void DefineMacJSClass(napi_env env, napi_value exports); + static napi_value CreateMac(napi_env env, napi_callback_info info); + static napi_value MacConstructor(napi_env env, napi_callback_info info); + + napi_value MacInit(napi_env env, napi_callback_info info); + napi_value MacUpdate(napi_env env, napi_callback_info info); + napi_value MacDoFinal(napi_env env, napi_callback_info info); + napi_value GetMacLength(napi_env env, napi_callback_info info); + + HcfMac *GetMac() + { + return macObj_; + } + +private: + HcfMac *macObj_ = nullptr; +}; + +} // namespace CryptoFramework +} // namespace OHOS + +#endif // NAPI_X509_CERTIFICATE_H diff --git a/frameworks/js/napi/inc/napi_md.h b/frameworks/js/napi/inc/napi_md.h new file mode 100644 index 0000000..caec507 --- /dev/null +++ b/frameworks/js/napi/inc/napi_md.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2022 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 NAPI_MD_H +#define NAPI_MD_H + +#include + +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" + +#include "md.h" + +namespace OHOS { +namespace CryptoFramework { + +class NapiMd { +public: + NapiMd(HcfMd *mdObj); + ~NapiMd(); + static napi_ref classRef_; + + static void DefineMdJSClass(napi_env env, napi_value exports); + static napi_value CreateMd(napi_env env, napi_callback_info info); + static napi_value MdConstructor(napi_env env, napi_callback_info info); + + napi_value MdUpdate(napi_env env, napi_callback_info info); + napi_value MdDoFinal(napi_env env, napi_callback_info info); + napi_value GetMdLength(napi_env env, napi_callback_info info); + + HcfMd *GetMd() + { + return mdObj_; + } + +private: + HcfMd *mdObj_ = nullptr; +}; + +} // namespace CryptoFramework +} // namespace OHOS + +#endif // NAPI_X509_CERTIFICATE_H diff --git a/frameworks/js/napi/inc/napi_pri_key.h b/frameworks/js/napi/inc/napi_pri_key.h new file mode 100644 index 0000000..df3447d --- /dev/null +++ b/frameworks/js/napi/inc/napi_pri_key.h @@ -0,0 +1,48 @@ +/* + * Copyright (C) 2022 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_NAPI_PRI_KEY_H +#define HCF_NAPI_PRI_KEY_H + +#include +#include "log.h" +#include "pri_key.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +namespace OHOS { +namespace CryptoFramework { +class NapiPriKey { +public: + NapiPriKey(HcfPriKey *priKey); + ~NapiPriKey(); + + HcfPriKey *GetPriKey(); + napi_value ConvertToJsPriKey(napi_env env); + + static void DefinePriKeyJSClass(napi_env env); + static napi_value PriKeyConstructor(napi_env env, napi_callback_info info); + + static napi_value JsGetEncoded(napi_env env, napi_callback_info info); + static napi_value JsClearMem(napi_env env, napi_callback_info info); + + static thread_local napi_ref classRef_; + +private: + HcfPriKey *priKey_ = nullptr; +}; +} // namespace CryptoFramework +} // namespace OHOS +#endif diff --git a/frameworks/js/napi/inc/napi_pub_key.h b/frameworks/js/napi/inc/napi_pub_key.h new file mode 100644 index 0000000..eee1800 --- /dev/null +++ b/frameworks/js/napi/inc/napi_pub_key.h @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2022 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_NAPI_PUB_KEY_H +#define HCF_NAPI_PUB_KEY_H + +#include +#include "log.h" +#include "pub_key.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +namespace OHOS { +namespace CryptoFramework { +class NapiPubKey { +public: + NapiPubKey(HcfPubKey *pubKey); + ~NapiPubKey(); + + HcfPubKey *GetPubKey(); + napi_value ConvertToJsPubKey(napi_env env); + + static void DefinePubKeyJSClass(napi_env env); + static napi_value PubKeyConstructor(napi_env env, napi_callback_info info); + + static napi_value JsGetEncoded(napi_env env, napi_callback_info info); + + static thread_local napi_ref classRef_; + +private: + HcfPubKey *pubKey_ = nullptr; +}; +} // namespace CryptoFramework +} // namespace OHOS +#endif diff --git a/frameworks/js/napi/inc/napi_rand.h b/frameworks/js/napi/inc/napi_rand.h new file mode 100644 index 0000000..2a0bdfe --- /dev/null +++ b/frameworks/js/napi/inc/napi_rand.h @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2022 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 NAPI_RAND_H +#define NAPI_RAND_H + +#include + +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" + +#include "rand.h" + +namespace OHOS { +namespace CryptoFramework { + +class NapiRand { +public: + NapiRand(HcfRand *randObj); + ~NapiRand(); + static napi_ref classRef_; + + static void DefineRandJSClass(napi_env env, napi_value exports); + static napi_value CreateRand(napi_env env, napi_callback_info info); + static napi_value RandConstructor(napi_env env, napi_callback_info info); + + napi_value GenerateRandom(napi_env env, napi_callback_info info); + napi_value SetSeed(napi_env env, napi_callback_info info); + + HcfRand *GetRand() + { + return randObj_; + } + +private: + HcfRand *randObj_ = nullptr; +}; + +} // namespace CryptoFramework +} // namespace OHOS +#endif diff --git a/frameworks/js/napi/inc/napi_sign.h b/frameworks/js/napi/inc/napi_sign.h new file mode 100644 index 0000000..b1557d1 --- /dev/null +++ b/frameworks/js/napi/inc/napi_sign.h @@ -0,0 +1,49 @@ +/* + * Copyright (C) 2022 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_NAPI_SIGNATURE_H +#define HCF_NAPI_SIGNATURE_H + +#include +#include "log.h" +#include "signature.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +namespace OHOS { +namespace CryptoFramework { +class NapiSign { +public: + NapiSign(HcfSign *sign); + ~NapiSign(); + + HcfSign *GetSign(); + + static void DefineSignJSClass(napi_env env, napi_value exports); + static napi_value SignConstructor(napi_env env, napi_callback_info info); + static napi_value CreateJsSign(napi_env env, napi_callback_info info); + + static napi_value JsInit(napi_env env, napi_callback_info info); + static napi_value JsUpdate(napi_env env, napi_callback_info info); + static napi_value JsSign(napi_env env, napi_callback_info info); + + static thread_local napi_ref classRef_; + +private: + HcfSign *sign_ = nullptr; +}; +} // namespace CryptoFramework +} // namespace OHOS +#endif diff --git a/frameworks/js/napi/inc/napi_sym_key.h b/frameworks/js/napi/inc/napi_sym_key.h new file mode 100644 index 0000000..88c4f98 --- /dev/null +++ b/frameworks/js/napi/inc/napi_sym_key.h @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2022 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_NAPI_SYM_KEY_H +#define HCF_NAPI_SYM_KEY_H + +#include +#include "log.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#include "sym_key.h" + +namespace OHOS { +namespace CryptoFramework { +class NapiSymKey { +public: + NapiSymKey(HcfSymKey *symKey); + ~NapiSymKey(); + HcfSymKey *GetSymKey(); + + static void DefineSymKeyJSClass(napi_env env); + static napi_value CreateSymKey(napi_env env); + static napi_value SymKeyConstructor(napi_env env, napi_callback_info info); + + static napi_value JsGetAlgorithm(napi_env env, napi_callback_info info); + static napi_value JsGetEncoded(napi_env env, napi_callback_info info); + static napi_value JsGetFormat(napi_env env, napi_callback_info info); + + static thread_local napi_ref classRef_; +private: + HcfSymKey *symKey_; +}; +} // namespace CryptoFramework +} // namespace OHOS +#endif diff --git a/frameworks/js/napi/inc/napi_sym_key_generator.h b/frameworks/js/napi/inc/napi_sym_key_generator.h new file mode 100644 index 0000000..68401ee --- /dev/null +++ b/frameworks/js/napi/inc/napi_sym_key_generator.h @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2022 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_NAPI_SYM_KEY_GENERATOR_H +#define HCF_NAPI_SYM_KEY_GENERATOR_H + +#include +#include "log.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#include "sym_key_generator.h" + +namespace OHOS { +namespace CryptoFramework { +class NapiSymKeyGenerator { +public: + NapiSymKeyGenerator(HcfSymKeyGenerator *generator); + ~NapiSymKeyGenerator(); + HcfSymKeyGenerator *GetSymKeyGenerator(); + + static void DefineSymKeyGeneratorJSClass(napi_env env, napi_value exports); + static napi_value CreateSymKeyGenerator(napi_env env, napi_callback_info info); + static napi_value SymKeyGeneratorConstructor(napi_env env, napi_callback_info info); + static napi_value JsGenerateSymKey(napi_env env, napi_callback_info info); + static napi_value JsGetAlgorithm(napi_env env, napi_callback_info info); + static napi_value JsConvertKey(napi_env env, napi_callback_info info); + + static thread_local napi_ref classRef_; +private: + HcfSymKeyGenerator *generator_; +}; +} // namespace CryptoFramework +} // namespace OHOS +#endif diff --git a/frameworks/js/napi/inc/napi_utils.h b/frameworks/js/napi/inc/napi_utils.h new file mode 100644 index 0000000..82b3710 --- /dev/null +++ b/frameworks/js/napi/inc/napi_utils.h @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2022 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_NAPI_UILTS_H +#define HCF_NAPI_UILTS_H + +#include +#include +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#include "blob.h" +#include "cert_chain_validator.h" +#include "algorithm_parameter.h" +#include "cipher.h" + +namespace OHOS { +namespace CryptoFramework { + +#define PARAMS_NUM_ONE 1 +#define PARAMS_NUM_TWO 2 +#define PARAMS_NUM_THREE 3 +#define PARAMS_NUM_FOUR 4 + +enum AsyncType { + ASYNC_CALLBACK = 1, + ASYNC_PROMISE = 2 +}; + +inline void AddUint32Property(napi_env env, napi_value object, const char *name, uint32_t value) +{ + napi_value property = nullptr; + napi_create_uint32(env, value, &property); + napi_set_named_property(env, object, name, property); +} + +HcfBlob *GetBlobFromNapiValue(napi_env env, napi_value arg); +bool GetParamsSpecFormNapiValue(napi_env env, napi_value arg, HcfCryptoMode opMode, HcfParamsSpec **paramsSpec); +napi_value ConvertBlobToNapiValue(napi_env env, HcfBlob *blob); + +bool GetStringFromJSParams(napi_env env, napi_value arg, std::string &returnStr); +bool GetInt32FromJSParams(napi_env env, napi_value arg, int32_t &returnInt); +bool GetUint32FromJSParams(napi_env env, napi_value arg, uint32_t &returnInt); +bool GetCallbackFromJSParams(napi_env env, napi_value arg, napi_ref *returnCb); +bool ParseArrayBuffer(napi_env env, napi_value args, uint8_t **data, size_t &size); +bool GetEncodingBlobFromValue(napi_env env, napi_value object, HcfEncodingBlob **encodingBlob); +bool GetCertChainFromValue(napi_env env, napi_value object, HcfCertChainData **certChainData); +bool CheckArgsCount(napi_env env, size_t argc, size_t expectedCount, bool isSync); +napi_value GetResourceName(napi_env env, const char *name); +napi_value GenerateArrayBuffer(napi_env env, uint8_t *data, uint32_t size); +napi_value NapiGetNull(napi_env env); +napi_value ConvertArrayToNapiValue(napi_env env, HcfArray *array); +napi_value ConvertEncodingBlobToNapiValue(napi_env env, HcfEncodingBlob *encodingBlob); +napi_value GenerateBusinessError(napi_env env, int32_t errCode, const char *errMsg); + +} // namespace CryptoFramework +} // namespace OHOS +#endif diff --git a/frameworks/js/napi/inc/napi_verify.h b/frameworks/js/napi/inc/napi_verify.h new file mode 100644 index 0000000..ac0aec9 --- /dev/null +++ b/frameworks/js/napi/inc/napi_verify.h @@ -0,0 +1,49 @@ +/* + * Copyright (C) 2022 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_NAPI_VERIFY_H +#define HCF_NAPI_VERIFY_H + +#include +#include "log.h" +#include "signature.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +namespace OHOS { +namespace CryptoFramework { +class NapiVerify { +public: + NapiVerify(HcfVerify *verify); + ~NapiVerify(); + + HcfVerify *GetVerify(); + + static void DefineVerifyJSClass(napi_env env, napi_value exports); + static napi_value VerifyConstructor(napi_env env, napi_callback_info info); + static napi_value CreateJsVerify(napi_env env, napi_callback_info info); + + static napi_value JsInit(napi_env env, napi_callback_info info); + static napi_value JsUpdate(napi_env env, napi_callback_info info); + static napi_value JsVerify(napi_env env, napi_callback_info info); + + static thread_local napi_ref classRef_; + +private: + HcfVerify *verify_ = nullptr; +}; +} // namespace CryptoFramework +} // namespace OHOS +#endif diff --git a/frameworks/js/napi/inc/napi_x509_certificate.h b/frameworks/js/napi/inc/napi_x509_certificate.h new file mode 100644 index 0000000..e8b9bb2 --- /dev/null +++ b/frameworks/js/napi/inc/napi_x509_certificate.h @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2022 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 NAPI_X509_CERTIFICATE_H +#define NAPI_X509_CERTIFICATE_H + +#include + +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "x509_certificate.h" + +namespace OHOS { +namespace CryptoFramework { + +class NapiX509Cert { +public: + NapiX509Cert(HcfX509Certificate *x509Cert); + ~NapiX509Cert(); + + static void DefineX509CertJSClass(napi_env env, napi_value exports); + static napi_value NapiCreateX509Cert(napi_env env, napi_callback_info info); + static void CreateX509CertExecute(napi_env env, void *data); + static void CreateX509CertComplete(napi_env env, napi_status status, void *data); + static napi_value CreateX509Cert(napi_env env); + + napi_value Verify(napi_env env, napi_callback_info info); + napi_value GetEncoded(napi_env env, napi_callback_info info); + napi_value GetPublicKey(napi_env env, napi_callback_info info); + napi_value CheckValidityWithDate(napi_env env, napi_callback_info info); + napi_value GetVersion(napi_env env, napi_callback_info info); + napi_value GetSerialNumber(napi_env env, napi_callback_info info); + napi_value GetIssuerName(napi_env env, napi_callback_info info); + napi_value GetSubjectName(napi_env env, napi_callback_info info); + napi_value GetNotBeforeTime(napi_env env, napi_callback_info info); + napi_value GetNotAfterTime(napi_env env, napi_callback_info info); + napi_value GetSignature(napi_env env, napi_callback_info info); + napi_value GetSigAlgName(napi_env env, napi_callback_info info); + napi_value GetSigAlgOID(napi_env env, napi_callback_info info); + napi_value GetSigAlgParams(napi_env env, napi_callback_info info); + napi_value GetIssuerUniqueID(napi_env env, napi_callback_info info); + napi_value GetSubjectUniqueID(napi_env env, napi_callback_info info); + napi_value GetKeyUsage(napi_env env, napi_callback_info info); + napi_value GetExtendedKeyUsage(napi_env env, napi_callback_info info); + napi_value GetBasicConstraints(napi_env env, napi_callback_info info); + napi_value GetSubjectAlternativeNames(napi_env env, napi_callback_info info); + napi_value GetIssuerAlternativeNames(napi_env env, napi_callback_info info); + + HcfX509Certificate *GetX509Cert() + { + return x509Cert_; + } + + static napi_ref classRef_; + +private: + HcfX509Certificate *x509Cert_ = nullptr; +}; + +} // namespace CryptoFramework +} // namespace OHOS + +#endif // NAPI_X509_CERTIFICATE_H diff --git a/frameworks/js/napi/inc/napi_x509_crl.h b/frameworks/js/napi/inc/napi_x509_crl.h new file mode 100644 index 0000000..dceb319 --- /dev/null +++ b/frameworks/js/napi/inc/napi_x509_crl.h @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2022 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 NAPI_X509_CRL_H +#define NAPI_X509_CRL_H + +#include + +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "x509_crl.h" + +namespace OHOS { +namespace CryptoFramework { + +class NapiX509Crl { +public: + NapiX509Crl(HcfX509Crl *x509Crl); + ~NapiX509Crl(); + + static void DefineX509CrlJSClass(napi_env env, napi_value exports); + static napi_value NapiCreateX509Crl(napi_env env, napi_callback_info info); + static void CreateX509CrlExecute(napi_env env, void *data); + static void CreateX509CrlComplete(napi_env env, napi_status status, void *data); + static napi_value CreateX509Crl(napi_env env); + + napi_value IsRevoked(napi_env env, napi_callback_info info); + napi_value GetType(napi_env env, napi_callback_info info); + napi_value GetEncoded(napi_env env, napi_callback_info info); + napi_value Verify(napi_env env, napi_callback_info info); + napi_value GetVersion(napi_env env, napi_callback_info info); + napi_value GetIssuerDN(napi_env env, napi_callback_info info); + napi_value GetThisUpdate(napi_env env, napi_callback_info info); + napi_value GetNextUpdate(napi_env env, napi_callback_info info); + napi_value GetRevokedCertificate(napi_env env, napi_callback_info info); + napi_value GetRevokedCertificateWithCert(napi_env env, napi_callback_info info); + napi_value GetRevokedCertificates(napi_env env, napi_callback_info info); + napi_value GetTBSCertList(napi_env env, napi_callback_info info); + napi_value GetSignature(napi_env env, napi_callback_info info); + napi_value GetSigAlgName(napi_env env, napi_callback_info info); + napi_value GetSigAlgOID(napi_env env, napi_callback_info info); + napi_value GetSigAlgParams(napi_env env, napi_callback_info info); + + HcfX509Crl *GetX509Crl() + { + return x509Crl_; + } + + static napi_ref classRef_; + +private: + HcfX509Crl *x509Crl_ = nullptr; +}; + +} // namespace CryptoFramework +} // namespace OHOS + +#endif // NAPI_X509_CRL_H diff --git a/frameworks/js/napi/inc/napi_x509_crl_entry.h b/frameworks/js/napi/inc/napi_x509_crl_entry.h new file mode 100644 index 0000000..658908f --- /dev/null +++ b/frameworks/js/napi/inc/napi_x509_crl_entry.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2022 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 NAPI_X509_CRL_ENTRY_H +#define NAPI_X509_CRL_ENTRY_H + +#include + +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "x509_crl_entry.h" + +namespace OHOS { +namespace CryptoFramework { + +class NapiX509CrlEntry { +public: + NapiX509CrlEntry(HcfX509CrlEntry *x509CrlEntry); + ~NapiX509CrlEntry(); + + static void DefineX509CrlEntryJSClass(napi_env env); + static napi_value CreateX509CrlEntry(napi_env env); + + napi_value GetEncoded(napi_env env, napi_callback_info info); + napi_value GetSerialNumber(napi_env env, napi_callback_info info); + napi_value GetCertificateIssuer(napi_env env, napi_callback_info info); + napi_value GetRevocationDate(napi_env env, napi_callback_info info); + napi_value GetExtensionValue(napi_env env, napi_callback_info info); + + HcfX509CrlEntry *GetX509CrlEntry() + { + return x509CrlEntry_; + } + + static napi_ref classRef_; + +private: + HcfX509CrlEntry *x509CrlEntry_ = nullptr; +}; + +} // namespace CryptoFramework +} // namespace OHOS + +#endif // NAPI_X509_CRL_ENTRY_H diff --git a/frameworks/js/napi/src/napi_asy_key_generator.cpp b/frameworks/js/napi/src/napi_asy_key_generator.cpp new file mode 100644 index 0000000..32b246b --- /dev/null +++ b/frameworks/js/napi/src/napi_asy_key_generator.cpp @@ -0,0 +1,535 @@ +/* + * Copyright (C) 2022 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 "napi_asy_key_generator.h" + +#include "securec.h" +#include "log.h" +#include "memory.h" + +#include "napi_crypto_framework_defines.h" +#include "napi_utils.h" +#include "napi_key_pair.h" +#include "napi_pri_key.h" +#include "napi_pub_key.h" + +namespace OHOS { +namespace CryptoFramework { + +struct GenKeyPairCtx { + napi_env env = nullptr; + + AsyncType asyncType = ASYNC_CALLBACK; + napi_ref callback = nullptr; + napi_deferred deferred = nullptr; + napi_value promise = nullptr; + napi_async_work asyncWork = nullptr; + + HcfAsyKeyGenerator *generator; + HcfParamsSpec *params; + + HcfResult result; + HcfKeyPair *returnKeyPair; +}; + +struct ConvertKeyCtx { + napi_env env = nullptr; + + AsyncType asyncType = ASYNC_CALLBACK; + napi_ref callback = nullptr; + napi_deferred deferred = nullptr; + napi_value promise = nullptr; + napi_async_work asyncWork = nullptr; + + HcfAsyKeyGenerator *generator; + HcfParamsSpec *params; + HcfBlob *pubKey; + HcfBlob *priKey; + + HcfResult result; + HcfKeyPair *returnKeyPair; +}; + +thread_local napi_ref NapiAsyKeyGenerator::classRef_ = nullptr; + +static void FreeGenKeyPairCtx(napi_env env, GenKeyPairCtx *ctx) +{ + if (ctx == nullptr) { + return; + } + + if (ctx->asyncWork != nullptr) { + napi_delete_async_work(env, ctx->asyncWork); + ctx->asyncWork = nullptr; + } + + if (ctx->callback != nullptr) { + napi_delete_reference(env, ctx->callback); + ctx->callback = nullptr; + } + + HcfFree(ctx); +} + +static void FreeConvertKeyCtx(napi_env env, ConvertKeyCtx *ctx) +{ + if (ctx == nullptr) { + return; + } + + if (ctx->asyncWork != nullptr) { + napi_delete_async_work(env, ctx->asyncWork); + ctx->asyncWork = nullptr; + } + + if (ctx->callback != nullptr) { + napi_delete_reference(env, ctx->callback); + ctx->callback = nullptr; + } + + HcfBlobDataFree(ctx->pubKey); + HcfFree(ctx->pubKey); + HcfBlobDataFree(ctx->priKey); + HcfFree(ctx->priKey); + HcfFree(ctx); +} + +static bool BuildGenKeyPairCtx(napi_env env, napi_callback_info info, GenKeyPairCtx *ctx) +{ + napi_value thisVar = nullptr; + size_t expectedArgc = PARAMS_NUM_ONE; + size_t argc; + napi_value argv[PARAMS_NUM_ONE] = { 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); + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "params num error.")); + return false; + } + ctx->asyncType = (argc == expectedArgc) ? ASYNC_CALLBACK : ASYNC_PROMISE; + + NapiAsyKeyGenerator *napiGenerator; + napi_status status = napi_unwrap(env, thisVar, (void **)(&napiGenerator)); + if (status != napi_ok) { + LOGE("failed to unwrap napi asyKeyGenerator obj."); + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "[Self]: param unwarp error.")); + return false; + } + + ctx->generator = napiGenerator->GetAsyKeyGenerator(); + ctx->params = nullptr; + + if (ctx->asyncType == ASYNC_PROMISE) { + napi_create_promise(env, &ctx->deferred, &ctx->promise); + return true; + } else { + return GetCallbackFromJSParams(env, argv[expectedArgc - 1], &ctx->callback); + } +} + +static bool GetPkAndSkBlobFromNapiValueIfInput(napi_env env, napi_value pkValue, napi_value skValue, + HcfBlob **returnPubKey, HcfBlob **returnPriKey) +{ + napi_valuetype valueType; + napi_typeof(env, pkValue, &valueType); + HcfBlob *pubKey = nullptr; + if (valueType != napi_null) { + pubKey = GetBlobFromNapiValue(env, pkValue); + if (pubKey == nullptr) { + LOGE("failed to get pubKey."); + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "[PubKey]: must be of the DataBlob type.")); + return false; + } + } + + napi_typeof(env, skValue, &valueType); + HcfBlob *priKey = nullptr; + if (valueType != napi_null) { + priKey = GetBlobFromNapiValue(env, skValue); + if (priKey == nullptr) { + LOGE("failed to get priKey."); + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "[PriKey]: must be of the DataBlob type.")); + return false; + } + } + + *returnPubKey = pubKey; + *returnPriKey = priKey; + return true; +} + +static bool BuildConvertKeyCtx(napi_env env, napi_callback_info info, ConvertKeyCtx *ctx) +{ + napi_value thisVar = nullptr; + size_t expectedArgc = PARAMS_NUM_THREE; + size_t argc; + 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); + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "params num error.")); + return false; + } + ctx->asyncType = (argc == expectedArgc) ? ASYNC_CALLBACK : ASYNC_PROMISE; + + NapiAsyKeyGenerator *napiGenerator; + napi_status status = napi_unwrap(env, thisVar, (void **)(&napiGenerator)); + if (status != napi_ok) { + LOGE("failed to unwrap napi asyKeyGenerator obj."); + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "[Self]: param unwarp error.")); + return false; + } + + HcfBlob *pubKey = nullptr; + HcfBlob *priKey = nullptr; + if (!GetPkAndSkBlobFromNapiValueIfInput(env, argv[PARAM0], argv[PARAM1], &pubKey, &priKey)) { + return false; + } + + ctx->generator = napiGenerator->GetAsyKeyGenerator(); + ctx->params = nullptr; + ctx->pubKey = pubKey; + ctx->priKey = priKey; + + if (ctx->asyncType == ASYNC_PROMISE) { + napi_create_promise(env, &ctx->deferred, &ctx->promise); + return true; + } else { + return GetCallbackFromJSParams(env, argv[expectedArgc - 1], &ctx->callback); + } +} + +static void ReturnGenKeyPairCallbackResult(napi_env env, GenKeyPairCtx *ctx, napi_value result) +{ + napi_value businessError = nullptr; + if (ctx->result != HCF_SUCCESS) { + businessError = GenerateBusinessError(env, ctx->result, COMMON_ERR_MSG.c_str()); + } + + napi_value params[ARGS_SIZE_TWO] = { businessError, result }; + + napi_value func = nullptr; + napi_get_reference_value(env, ctx->callback, &func); + + napi_value recv = nullptr; + napi_value callFuncRet = nullptr; + napi_get_undefined(env, &recv); + napi_call_function(env, recv, func, ARGS_SIZE_TWO, params, &callFuncRet); +} + +static void ReturnGenKeyPairPromiseResult(napi_env env, GenKeyPairCtx *ctx, napi_value result) +{ + if (ctx->result == HCF_SUCCESS) { + napi_resolve_deferred(env, ctx->deferred, result); + } else { + napi_reject_deferred(env, ctx->deferred, GenerateBusinessError(env, ctx->result, COMMON_ERR_MSG.c_str())); + } +} + +static void ReturnConvertKeyCallbackResult(napi_env env, ConvertKeyCtx *ctx, napi_value result) +{ + napi_value businessError = nullptr; + if (ctx->result != HCF_SUCCESS) { + businessError = GenerateBusinessError(env, ctx->result, COMMON_ERR_MSG.c_str()); + } + + napi_value params[ARGS_SIZE_TWO] = { businessError, result }; + + napi_value func = nullptr; + napi_get_reference_value(env, ctx->callback, &func); + + napi_value recv = nullptr; + napi_value callFuncRet = nullptr; + napi_get_undefined(env, &recv); + napi_call_function(env, recv, func, ARGS_SIZE_TWO, params, &callFuncRet); +} + +static void ReturnConvertKeyPromiseResult(napi_env env, ConvertKeyCtx *ctx, napi_value result) +{ + if (ctx->result == HCF_SUCCESS) { + napi_resolve_deferred(env, ctx->deferred, result); + } else { + napi_reject_deferred(env, ctx->deferred, GenerateBusinessError(env, ctx->result, COMMON_ERR_MSG.c_str())); + } +} + +static void GenKeyPairAsyncWorkProcess(napi_env env, void *data) +{ + GenKeyPairCtx *ctx = static_cast(data); + + HcfResult res = ctx->generator->generateKeyPair(ctx->generator, ctx->params, &(ctx->returnKeyPair)); + + ctx->result = res; + if (res != HCF_SUCCESS) { + LOGE("generate key pair fail."); + } +} + +static void GenKeyPairAsyncWorkReturn(napi_env env, napi_status status, void *data) +{ + GenKeyPairCtx *ctx = static_cast(data); + + napi_value instance = nullptr; + if (ctx->result == HCF_SUCCESS) { + NapiKeyPair *napiKeyPair = new NapiKeyPair(ctx->returnKeyPair); + instance = napiKeyPair->ConvertToJsKeyPair(env); + + napi_wrap( + env, instance, napiKeyPair, + [](napi_env env, void *data, void *hint) { + NapiKeyPair *keyPair = static_cast(data); + delete keyPair; + return; + }, + nullptr, nullptr); + } + + if (ctx->asyncType == ASYNC_CALLBACK) { + ReturnGenKeyPairCallbackResult(env, ctx, instance); + } else { + ReturnGenKeyPairPromiseResult(env, ctx, instance); + } + FreeGenKeyPairCtx(env, ctx); +} + +static void ConvertKeyAsyncWorkProcess(napi_env env, void *data) +{ + ConvertKeyCtx *ctx = static_cast(data); + + HcfResult res = ctx->generator->convertKey(ctx->generator, ctx->params, + ctx->pubKey, ctx->priKey, &(ctx->returnKeyPair)); + + ctx->result = res; + if (res != HCF_SUCCESS) { + LOGE("convert key fail."); + } +} + +static void ConvertKeyAsyncWorkReturn(napi_env env, napi_status status, void *data) +{ + ConvertKeyCtx *ctx = static_cast(data); + + napi_value instance = nullptr; + if (ctx->result == HCF_SUCCESS) { + NapiKeyPair *napiKeyPair = new NapiKeyPair(ctx->returnKeyPair); + napi_value instance = napiKeyPair->ConvertToJsKeyPair(env); + + napi_wrap( + env, instance, napiKeyPair, + [](napi_env env, void *data, void *hint) { + NapiKeyPair *keyPair = static_cast(data); + delete keyPair; + return; + }, + nullptr, nullptr); + } + + if (ctx->asyncType == ASYNC_CALLBACK) { + ReturnConvertKeyCallbackResult(env, ctx, instance); + } else { + ReturnConvertKeyPromiseResult(env, ctx, instance); + } + FreeConvertKeyCtx(env, ctx); +} + +static napi_value NewGenKeyPairAsyncWork(napi_env env, GenKeyPairCtx *ctx) +{ + napi_value resourceName = nullptr; + napi_create_string_utf8(env, "generatorKeyPair", NAPI_AUTO_LENGTH, &resourceName); + + napi_create_async_work( + env, nullptr, resourceName, + [](napi_env env, void *data) { + GenKeyPairAsyncWorkProcess(env, data); + return; + }, + [](napi_env env, napi_status status, void *data) { + GenKeyPairAsyncWorkReturn(env, status, data); + return; + }, + (void *)ctx, + &ctx->asyncWork); + + napi_queue_async_work(env, ctx->asyncWork); + if (ctx->asyncType == ASYNC_PROMISE) { + return ctx->promise; + } else { + napi_value result = nullptr; + napi_get_null(env, &result); + return result; + } +} + +static napi_value NewConvertKeyAsyncWork(napi_env env, ConvertKeyCtx *ctx) +{ + napi_value resourceName = nullptr; + napi_create_string_utf8(env, "convertKey", NAPI_AUTO_LENGTH, &resourceName); + + napi_create_async_work( + env, nullptr, resourceName, + [](napi_env env, void *data) { + ConvertKeyAsyncWorkProcess(env, data); + return; + }, + [](napi_env env, napi_status status, void *data) { + ConvertKeyAsyncWorkReturn(env, status, data); + return; + }, + (void *)ctx, + &ctx->asyncWork); + + napi_queue_async_work(env, ctx->asyncWork); + if (ctx->asyncType == ASYNC_PROMISE) { + return ctx->promise; + } else { + napi_value result = nullptr; + napi_get_null(env, &result); + return result; + } +} + +NapiAsyKeyGenerator::NapiAsyKeyGenerator(HcfAsyKeyGenerator *generator) +{ + this->generator_ = generator; +} + +NapiAsyKeyGenerator::~NapiAsyKeyGenerator() +{ + OH_HCF_ObjDestroy(this->generator_); +} + +HcfAsyKeyGenerator *NapiAsyKeyGenerator::GetAsyKeyGenerator() +{ + return this->generator_; +} + +napi_value NapiAsyKeyGenerator::JsGenerateKeyPair(napi_env env, napi_callback_info info) +{ + LOGI("enter ..."); + GenKeyPairCtx *ctx = (GenKeyPairCtx *)HcfMalloc(sizeof(GenKeyPairCtx), 0); + if (ctx == NULL) { + LOGE("create context fail."); + napi_throw(env, GenerateBusinessError(env, HCF_ERR_MALLOC, "malloc ctx fail.")); + return NULL; + } + + if (!BuildGenKeyPairCtx(env, info, ctx)) { + LOGE("build context fail."); + FreeGenKeyPairCtx(env, ctx); + return nullptr; + } + + return NewGenKeyPairAsyncWork(env, ctx); +} + +napi_value NapiAsyKeyGenerator::JsConvertKey(napi_env env, napi_callback_info info) +{ + LOGI("enter ..."); + ConvertKeyCtx *ctx = (ConvertKeyCtx *)HcfMalloc(sizeof(ConvertKeyCtx), 0); + if (ctx == NULL) { + LOGE("create context fail."); + return NULL; + } + + if (!BuildConvertKeyCtx(env, info, ctx)) { + LOGE("build context fail."); + FreeConvertKeyCtx(env, ctx); + return nullptr; + } + + return NewConvertKeyAsyncWork(env, ctx); +} + +napi_value NapiAsyKeyGenerator::AsyKeyGeneratorConstructor(napi_env env, napi_callback_info info) +{ + LOGI("enter ..."); + + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + + LOGI("out ..."); + return thisVar; +} + +napi_value NapiAsyKeyGenerator::CreateJsAsyKeyGenerator(napi_env env, napi_callback_info info) +{ + LOGI("enter ..."); + size_t exceptedArgc = PARAMS_NUM_ONE; + size_t argc; + napi_value argv[PARAMS_NUM_ONE] = { nullptr }; + napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); + + if (argc != exceptedArgc) { + LOGE("The input args num is invalid."); + return NapiGetNull(env); + } + + napi_value instance; + napi_value constructor = nullptr; + napi_get_reference_value(env, classRef_, &constructor); + napi_new_instance(env, constructor, argc, argv, &instance); + + std::string algName; + if (!GetStringFromJSParams(env, argv[0], algName)) { + LOGE("failed to get algoName."); + return NapiGetNull(env); + } + + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate(algName.c_str(), &generator); + if (res != HCF_SUCCESS) { + LOGE("create c generator fail."); + return NapiGetNull(env); + } + + NapiAsyKeyGenerator *napiAsyKeyGenerator = new NapiAsyKeyGenerator(generator); + + napi_wrap( + env, instance, napiAsyKeyGenerator, + [](napi_env env, void *data, void *hint) { + NapiAsyKeyGenerator *napiAsyKeyGenerator = (NapiAsyKeyGenerator *)(data); + delete napiAsyKeyGenerator; + return; + }, + nullptr, + nullptr); + + napi_value napiAlgName = nullptr; + napi_create_string_utf8(env, algName.c_str(), NAPI_AUTO_LENGTH, &napiAlgName); + napi_set_named_property(env, instance, CRYPTO_TAG_ALG_NAME.c_str(), napiAlgName); + + LOGI("out ..."); + return instance; +} + +void NapiAsyKeyGenerator::DefineAsyKeyGeneratorJSClass(napi_env env, napi_value exports) +{ + napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("createAsyKeyGenerator", NapiAsyKeyGenerator::CreateJsAsyKeyGenerator), + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); + + napi_property_descriptor classDesc[] = { + DECLARE_NAPI_FUNCTION("generateKeyPair", NapiAsyKeyGenerator::JsGenerateKeyPair), + DECLARE_NAPI_FUNCTION("convertKey", NapiAsyKeyGenerator::JsConvertKey), + }; + napi_value constructor = nullptr; + napi_define_class(env, "AsyKeyGenerator", NAPI_AUTO_LENGTH, NapiAsyKeyGenerator::AsyKeyGeneratorConstructor, + nullptr, sizeof(classDesc) / sizeof(classDesc[0]), classDesc, &constructor); + napi_create_reference(env, constructor, 1, &classRef_); +} + +} // CryptoFramework +} // OHOS diff --git a/frameworks/js/napi/src/napi_cert_chain_validator.cpp b/frameworks/js/napi/src/napi_cert_chain_validator.cpp new file mode 100644 index 0000000..e1c58f7 --- /dev/null +++ b/frameworks/js/napi/src/napi_cert_chain_validator.cpp @@ -0,0 +1,267 @@ +/* + * Copyright (c) 2022 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 "napi_cert_chain_validator.h" + +#include "napi/native_node_api.h" +#include "napi/native_api.h" +#include "log.h" +#include "memory.h" +#include "utils.h" +#include "result.h" +#include "object_base.h" +#include "napi_crypto_framework_defines.h" +#include "napi_utils.h" + +namespace OHOS { +namespace CryptoFramework { + +napi_ref NapiCertChainValidator::classRef_ = nullptr; + +struct CfCtx { + CfAsyncType asyncType = ASYNC_TYPE_CALLBACK; + napi_ref callback = nullptr; + napi_deferred deferred = nullptr; + napi_async_work asyncWork = nullptr; + + NapiCertChainValidator *ccvClass = nullptr; + HcfCertChainData *certChainData = nullptr; + + int32_t errCode = 0; + const char *errMsg = nullptr; +}; + +NapiCertChainValidator::NapiCertChainValidator(HcfCertChainValidator *certChainValidator) +{ + this->certChainValidator_ = certChainValidator; +} + +NapiCertChainValidator::~NapiCertChainValidator() +{ + OH_HCF_ObjDestroy(this->certChainValidator_); +} + +static void FreeCryptoFwkCtx(napi_env env, CfCtx *context) +{ + if (context == nullptr) { + return; + } + + if (context->asyncWork != nullptr) { + napi_delete_async_work(env, context->asyncWork); + } + + if (context->callback != nullptr) { + napi_delete_reference(env, context->callback); + } + + if (context->certChainData != nullptr) { + HcfFree(context->certChainData->data); + context->certChainData->data = nullptr; + HcfFree(context->certChainData); + context->certChainData = nullptr; + } + + HcfFree(context); + context = nullptr; +} + +static void ReturnCallbackResult(napi_env env, CfCtx *context, napi_value result) +{ + napi_value businessError = nullptr; + if (context->errCode != HCF_SUCCESS) { + businessError = GenerateBusinessError(env, context->errCode, context->errMsg); + } + napi_value params[ARGS_SIZE_TWO] = { businessError, result }; + + napi_value func = nullptr; + napi_get_reference_value(env, context->callback, &func); + + napi_value recv = nullptr; + napi_value callFuncRet = nullptr; + napi_get_undefined(env, &recv); + napi_call_function(env, recv, func, ARGS_SIZE_TWO, params, &callFuncRet); +} + +static void ReturnPromiseResult(napi_env env, CfCtx *context, napi_value result) +{ + if (context->errCode == HCF_SUCCESS) { + napi_resolve_deferred(env, context->deferred, result); + } else { + napi_reject_deferred(env, context->deferred, GenerateBusinessError(env, context->errCode, context->errMsg)); + } +} + +static void ReturnResult(napi_env env, CfCtx *context, napi_value result) +{ + if (context->asyncType == ASYNC_TYPE_CALLBACK) { + ReturnCallbackResult(env, context, result); + } else { + ReturnPromiseResult(env, context, result); + } +} + +static void ValidateExecute(napi_env env, void *data) +{ + CfCtx *context = static_cast(data); + HcfCertChainValidator *validator = context->ccvClass->GetCertChainValidator(); + context->errCode = validator->validate(validator, context->certChainData); + if (context->errCode != HCF_SUCCESS) { + LOGE("validate cert chain failed!"); + context->errMsg = "validate cert chain failed"; + } +} + +static void ValidateComplete(napi_env env, napi_status status, void *data) +{ + CfCtx *context = static_cast(data); + ReturnResult(env, context, NapiGetNull(env)); + FreeCryptoFwkCtx(env, context); +} + +napi_value NapiCertChainValidator::Validate(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_TWO; + napi_value argv[ARGS_SIZE_TWO] = { 0 }; + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_TWO, false)) { + return nullptr; + } + CfCtx *context = (CfCtx *)HcfMalloc(sizeof(CfCtx), 0); + if (context == nullptr) { + LOGE("malloc context failed!"); + return nullptr; + } + context->ccvClass = this; + + context->asyncType = (argc == ARGS_SIZE_TWO) ? ASYNC_TYPE_CALLBACK : ASYNC_TYPE_PROMISE; + if (!GetCertChainFromValue(env, argv[PARAM0], &context->certChainData)) { + LOGE("get cert chain data from napi value failed!"); + FreeCryptoFwkCtx(env, context); + return nullptr; + } + napi_value promise = nullptr; + if (context->asyncType == ASYNC_TYPE_CALLBACK) { + if (!GetCallbackFromJSParams(env, argv[PARAM1], &context->callback)) { + LOGE("get callback failed!"); + FreeCryptoFwkCtx(env, context); + return nullptr; + } + } else { + napi_create_promise(env, &context->deferred, &promise); + } + + napi_create_async_work( + env, nullptr, GetResourceName(env, "Validate"), + ValidateExecute, + ValidateComplete, + (void *)context, + &context->asyncWork); + + napi_queue_async_work(env, context->asyncWork); + if (context->asyncType == ASYNC_TYPE_PROMISE) { + return promise; + } else { + return NapiGetNull(env); + } +} + +static napi_value NapiValidate(napi_env env, napi_callback_info info) +{ + LOGI("start to validate cert chain."); + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiCertChainValidator *certChainValidator = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&certChainValidator)); + if (certChainValidator == nullptr) { + LOGE("certChainValidator is nullptr!"); + return nullptr; + } + return certChainValidator->Validate(env, info); +} + +static napi_value CertChainValidatorConstructor(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + return thisVar; +} + +napi_value NapiCertChainValidator::CreateCertChainValidator(napi_env env, napi_callback_info info) +{ + LOGI("start to create cert chain validator."); + napi_value thisVar = nullptr; + size_t argc = ARGS_SIZE_ONE; + napi_value argv[ARGS_SIZE_ONE] = { 0 }; + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + + if (argc != ARGS_SIZE_ONE) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "invalid params count")); + LOGE("invalid params count!"); + return nullptr; + } + + std::string algorithm; + if (!GetStringFromJSParams(env, argv[PARAM0], algorithm)) { + LOGE("Failed to get algorithm."); + return nullptr; + } + HcfCertChainValidator *certChainValidator = nullptr; + HcfResult res = HcfCertChainValidatorCreate(algorithm.c_str(), &certChainValidator); + if (res != HCF_SUCCESS) { + napi_throw(env, GenerateBusinessError(env, res, "create cert chain validator failed")); + LOGE("Failed to create c cert chain validator."); + return nullptr; + } + const char *returnAlgorithm = certChainValidator->getAlgorithm(certChainValidator); + napi_value algValue = nullptr; + napi_create_string_utf8(env, returnAlgorithm, NAPI_AUTO_LENGTH, &algValue); + napi_value constructor = nullptr; + napi_value validatorInstance = nullptr; + napi_get_reference_value(env, classRef_, &constructor); + napi_new_instance(env, constructor, 0, nullptr, &validatorInstance); + napi_set_named_property(env, validatorInstance, CRYPTO_TAG_ALGORITHM.c_str(), algValue); + NapiCertChainValidator *ccvClass = new NapiCertChainValidator(certChainValidator); + napi_wrap( + env, validatorInstance, ccvClass, + [](napi_env env, void* data, void *hint) { + NapiCertChainValidator *ccv = (NapiCertChainValidator *)data; + delete ccv; + }, + nullptr, + nullptr); + + return validatorInstance; +} + +void NapiCertChainValidator::DefineCertChainValidatorJSClass(napi_env env, napi_value exports) +{ + napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("createCertChainValidator", CreateCertChainValidator), + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); + + napi_property_descriptor validatorDesc[] = { + DECLARE_NAPI_FUNCTION("validate", NapiValidate), + }; + napi_value constructor = nullptr; + napi_define_class(env, "CertChainValidator", NAPI_AUTO_LENGTH, CertChainValidatorConstructor, nullptr, + sizeof(validatorDesc) / sizeof(validatorDesc[0]), validatorDesc, &constructor); + napi_create_reference(env, constructor, 1, &classRef_); +} + +} // namespace CryptoFramework +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/js/napi/src/napi_cipher.cpp b/frameworks/js/napi/src/napi_cipher.cpp new file mode 100644 index 0000000..54af734 --- /dev/null +++ b/frameworks/js/napi/src/napi_cipher.cpp @@ -0,0 +1,672 @@ +/* + * Copyright (C) 2022 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 "napi_cipher.h" +#include "napi_key.h" +#include "securec.h" +#include "log.h" +#include "memory.h" + +#include "cipher.h" +#include "napi_utils.h" +#include "napi_crypto_framework_defines.h" +#include "detailed_iv_params.h" +#include "detailed_gcm_params.h" +#include "detailed_ccm_params.h" + +namespace OHOS { +namespace CryptoFramework { + +thread_local napi_ref NapiCipher::classRef_ = nullptr; + +struct CipherFwkCtxT { + napi_env env = nullptr; + + AsyncType asyncType = ASYNC_CALLBACK; + napi_ref callback = nullptr; + napi_deferred deferred = nullptr; + napi_value promise = nullptr; + napi_async_work asyncWork = nullptr; + + HcfCipher *cipher = nullptr; + HcfKey *key = nullptr; + HcfParamsSpec *paramsSpec = nullptr; + + HcfBlob input = { 0 }; + HcfBlob output = { 0 }; + enum HcfCryptoMode opMode = ENCRYPT_MODE; + int32_t errCode = 0; +}; + +using CipherFwkCtx = CipherFwkCtxT *; + +static void FreeParamsSpec(HcfParamsSpec *paramsSpec) +{ + if (paramsSpec != nullptr) { + return; + } + if (IV_PARAMS_SPEC.compare(paramsSpec->getType()) == 0) { + HcfIvParamsSpec *iv = (HcfIvParamsSpec *)paramsSpec; + HcfFree(iv->iv.data); + iv->iv.data = nullptr; + iv->iv.len = 0; + } + if (GCM_PARAMS_SPEC.compare(paramsSpec->getType()) == 0) { + HcfGcmParamsSpec *gcm = (HcfGcmParamsSpec *)paramsSpec; + HcfFree(gcm->iv.data); + HcfFree(gcm->aad.data); + HcfFree(gcm->tag.data); + gcm->iv.len = 0; + gcm->aad.len = 0; + gcm->tag.len = 0; + gcm->iv.data = nullptr; + gcm->aad.data = nullptr; + gcm->tag.data = nullptr; + } + if (CCM_PARAMS_SPEC.compare(paramsSpec->getType()) == 0) { + HcfCcmParamsSpec *ccm = (HcfCcmParamsSpec *)paramsSpec; + HcfFree(ccm->iv.data); + HcfFree(ccm->aad.data); + HcfFree(ccm->tag.data); + ccm->iv.len = 0; + ccm->aad.len = 0; + ccm->tag.len = 0; + ccm->iv.data = nullptr; + ccm->aad.data = nullptr; + ccm->tag.data = nullptr; + } + HcfFree(paramsSpec); +} + +static void FreeCipherFwkCtx(napi_env env, CipherFwkCtx &context) +{ + if (context == nullptr) { + return; + } + + if (context->asyncWork != nullptr) { + napi_delete_async_work(env, context->asyncWork); + context->asyncWork = nullptr; + } + + if (context->callback != nullptr) { + napi_delete_reference(env, context->callback); + context->callback = nullptr; + } + if (context->input.data != nullptr) { + HcfFree(context->input.data); + context->input.data = nullptr; + context->input.len = 0; + } + if (context->output.data != nullptr) { + HcfFree(context->output.data); + context->output.data = nullptr; + context->output.len = 0; + } + FreeParamsSpec(context->paramsSpec); + context->paramsSpec = nullptr; + + context->cipher = nullptr; + context->key = nullptr; + HcfFree(context); + context = nullptr; +} + +bool BuildContextForInit(napi_env env, napi_callback_info info, CipherFwkCtx context) +{ + napi_value thisVar = nullptr; + NapiCipher *napiCipher = nullptr; + NapiKey *napiKey = nullptr; + size_t expectedArgc = ARGS_SIZE_FOUR; + size_t argc = ARGS_SIZE_FOUR; + napi_value argv[ARGS_SIZE_FOUR] = { nullptr }; + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + if (argc != expectedArgc && argc != expectedArgc - 1) { + LOGE("wrong argument num. require 3 or 4 arguments. [Argc]: %zu!", argc); + return false; + } + context->asyncType = (argc == expectedArgc) ? ASYNC_CALLBACK : ASYNC_PROMISE; + + napi_status status = napi_unwrap(env, thisVar, (void **)&napiCipher); + if (status != napi_ok) { + LOGE("failed to unwrap napi napiCipher obj!"); + return false; + } + + context->cipher = napiCipher->GetCipher(); + // get opMode, type is object + size_t index = 0; + if (napi_get_value_uint32(env, argv[index++], (uint32_t *)&(context->opMode)) != napi_ok) { + LOGE("get opMode failed!"); + return false; + } + + // get key, unwrap from JS + status = napi_unwrap(env, argv[index++], (void **)&napiKey); + if (status != napi_ok) { + LOGE("failed to unwrap napi napiSymKey obj!"); + return false; + } + + context->key = napiKey->GetHcfKey(); + + // get paramsSpec, unwrap from JS + napi_valuetype valueType; + napi_typeof(env, argv[index], &valueType); + if (valueType != napi_null) { + if (!GetParamsSpecFormNapiValue(env, argv[index], context->opMode, &context->paramsSpec)) { + LOGE("GetParamsSpecFormNapiValue failed!"); + return false; + } + } + index++; + + if (context->asyncType == ASYNC_PROMISE) { + napi_create_promise(env, &context->deferred, &context->promise); + return true; + } else { + return GetCallbackFromJSParams(env, argv[index], &context->callback); + } +} + +bool BuildContextForUpdate(napi_env env, napi_callback_info info, CipherFwkCtx context) +{ + napi_value thisVar = nullptr; + NapiCipher *napiCipher = nullptr; + size_t expectedArgc = ARGS_SIZE_TWO; + size_t argc = ARGS_SIZE_TWO; + napi_value argv[ARGS_SIZE_TWO] = { nullptr }; + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + if (argc != expectedArgc && argc != expectedArgc - 1) { + LOGE("wrong argument num. require 1 or 2 arguments. [Argc]: %zu!", argc); + return false; + } + context->asyncType = (argc == expectedArgc) ? ASYNC_CALLBACK : ASYNC_PROMISE; + + napi_status status = napi_unwrap(env, thisVar, (void **)&napiCipher); + if (status != napi_ok) { + LOGE("failed to unwrap napi napiCipher obj!"); + return false; + } + context->cipher = napiCipher->GetCipher(); + // get input, type is blob + size_t index = 0; + HcfBlob *input = nullptr; + input = GetBlobFromNapiValue(env, argv[index++]); + if (input == nullptr) { + LOGE("GetBlobFromNapiValue failed!"); + return false; + } + context->input.data = input->data; + context->input.len = input->len; + HcfFree(input); + if (context->asyncType == ASYNC_PROMISE) { + napi_create_promise(env, &context->deferred, &context->promise); + return true; + } else { + return GetCallbackFromJSParams(env, argv[index], &context->callback); + } +} + +bool BuildContextForFinal(napi_env env, napi_callback_info info, CipherFwkCtx context) +{ + napi_value thisVar = nullptr; + NapiCipher *napiCipher = nullptr; + size_t expectedArgc = ARGS_SIZE_TWO; + size_t argc = ARGS_SIZE_TWO; + napi_value argv[ARGS_SIZE_TWO] = { nullptr }; + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + if (argc != expectedArgc && argc != expectedArgc - 1) { + LOGE("wrong argument num. require 1 or 2 arguments. [Argc]: %zu!", argc); + return false; + } + context->asyncType = (argc == expectedArgc) ? ASYNC_CALLBACK : ASYNC_PROMISE; + + napi_status status = napi_unwrap(env, thisVar, (void **)&napiCipher); + if (status != napi_ok) { + LOGE("failed to unwrap napi napiCipher obj!"); + return false; + } + context->cipher = napiCipher->GetCipher(); + + // get input, type is blob + size_t index = 0; + napi_valuetype valueType; + napi_typeof(env, argv[index], &valueType); + if (valueType != napi_null) { + HcfBlob *input = nullptr; + input = GetBlobFromNapiValue(env, argv[index]); + if (input == nullptr) { + LOGE("GetBlobFromNapiValue failed!"); + return false; + } + context->input.data = input->data; + context->input.len = input->len; + HcfFree(input); + } + index++; + if (context->asyncType == ASYNC_PROMISE) { + napi_create_promise(env, &context->deferred, &context->promise); + return true; + } else { + return GetCallbackFromJSParams(env, argv[index], &context->callback); + } +} + +static napi_value GenerateBusinessError(napi_env env, int32_t errorCode) +{ + napi_value businessError = nullptr; + napi_create_object(env, &businessError); + + napi_value code = nullptr; + napi_create_int32(env, errorCode, &code); + napi_set_named_property(env, businessError, "code", code); + + return businessError; +} + +static void ReturnCallbackResult(napi_env env, CipherFwkCtx context, napi_value result) +{ + napi_value businessError = GenerateBusinessError(env, context->errCode); + napi_value params[ARGS_SIZE_TWO] = { businessError, result }; + + napi_value func = nullptr; + napi_get_reference_value(env, context->callback, &func); + + napi_value recv = nullptr; + napi_value callFuncRet = nullptr; + napi_get_undefined(env, &recv); + napi_call_function(env, recv, func, ARGS_SIZE_TWO, params, &callFuncRet); +} + +static void ReturnPromiseResult(napi_env env, CipherFwkCtx context, napi_value result) +{ + if (context->errCode == HCF_SUCCESS) { + napi_resolve_deferred(env, context->deferred, result); + } else { + napi_reject_deferred(env, context->deferred, result); + } +} + +// init execute +void AsyncInitProcess(napi_env env, void *data) +{ + if (data == nullptr) { + return; + } + CipherFwkCtx context = static_cast(data); + HcfCipher *cipher = context->cipher; + HcfParamsSpec *params = context->paramsSpec; + HcfKey *key = context->key; + + HcfResult res = cipher->init(cipher, context->opMode, key, params); + if (res != HCF_SUCCESS) { + LOGE("init ret:%d", (int32_t)res); + context->errCode = res; + return; + } + context->errCode = HCF_SUCCESS; +} + +// update execute +void AsyncUpdateProcess(napi_env env, void *data) +{ + if (data == nullptr) { + return; + } + CipherFwkCtx context = static_cast(data); + HcfCipher *cipher = context->cipher; + HcfResult res = cipher->update(cipher, &context->input, &context->output); + if (res != HCF_SUCCESS) { + LOGE("Update ret:%d!", (int32_t)res); + context->errCode = res; + return; + } + context->errCode = HCF_SUCCESS; +} + +void AsyncDoFinalProcess(napi_env env, void *data) +{ + if (data == nullptr) { + return; + } + CipherFwkCtx context = static_cast(data); + HcfCipher *cipher = context->cipher; + + HcfResult res = cipher->doFinal(cipher, &context->input, &context->output); + if (res != HCF_SUCCESS) { + LOGE("doFinal ret:%d!", (int32_t)res); + context->errCode = res; + return; + } + context->errCode = HCF_SUCCESS; +} + +napi_value GetNapiNull(napi_env env) +{ + napi_value output = nullptr; + napi_status status = napi_get_null(env, &output); + if (status != napi_ok) { + LOGE("create null napi value failed"); + } + return output; +} + +void AsyncInitReturn(napi_env env, napi_status status, void *data) +{ + CipherFwkCtx context = static_cast(data); + napi_value result = GetNapiNull(env); + + if (context->asyncType == ASYNC_CALLBACK) { + ReturnCallbackResult(env, context, result); + } else { + ReturnPromiseResult(env, context, result); + } + FreeCipherFwkCtx(env, context); +} + +void AsyncUpdateReturn(napi_env env, napi_status status, void *data) +{ + CipherFwkCtx context = static_cast(data); + napi_value instance = ConvertBlobToNapiValue(env, &context->output); + if (instance == nullptr) { + LOGE("May be nullptr!"); + instance = GetNapiNull(env); + } + + if (context->asyncType == ASYNC_CALLBACK) { + ReturnCallbackResult(env, context, instance); + } else { + ReturnPromiseResult(env, context, instance); + } + FreeCipherFwkCtx(env, context); +} + +void AsyncDoFinalReturn(napi_env env, napi_status status, void *data) +{ + CipherFwkCtx context = static_cast(data); + napi_value instance = ConvertBlobToNapiValue(env, &context->output); + if (instance == nullptr) { + LOGE("Maybe in decrypt mode, or CCM crypto maybe occur!"); + instance = GetNapiNull(env); + } + + if (context->asyncType == ASYNC_CALLBACK) { + ReturnCallbackResult(env, context, instance); + } else { + ReturnPromiseResult(env, context, instance); + } + FreeCipherFwkCtx(env, context); +} + +napi_value NewAsyncInit(napi_env env, CipherFwkCtx context) +{ + napi_value resourceName = nullptr; + napi_create_string_utf8(env, "init", NAPI_AUTO_LENGTH, &resourceName); + + napi_create_async_work( + env, nullptr, resourceName, + [](napi_env env, void *data) { + AsyncInitProcess(env, data); + return; + }, + [](napi_env env, napi_status status, void *data) { + AsyncInitReturn(env, status, data); + return; + }, + (void *)context, + &context->asyncWork); + + napi_queue_async_work(env, context->asyncWork); + if (context->asyncType == ASYNC_PROMISE) { + return context->promise; + } else { + napi_value result = nullptr; + napi_get_null(env, &result); + return result; + } +} + +napi_value NewAsyncUpdate(napi_env env, CipherFwkCtx context) +{ + napi_value resourceName = nullptr; + napi_create_string_utf8(env, "update", NAPI_AUTO_LENGTH, &resourceName); + + napi_create_async_work( + env, nullptr, resourceName, + [](napi_env env, void *data) { + AsyncUpdateProcess(env, data); + return; + }, + [](napi_env env, napi_status status, void *data) { + AsyncUpdateReturn(env, status, data); + return; + }, + (void *)context, + &context->asyncWork); + + napi_queue_async_work(env, context->asyncWork); + if (context->asyncType == ASYNC_PROMISE) { + return context->promise; + } else { + napi_value result = nullptr; + napi_get_null(env, &result); + return result; + } +} + +napi_value NewAsyncDoFinal(napi_env env, CipherFwkCtx context) +{ + napi_value resourceName = nullptr; + napi_create_string_utf8(env, "DoFinal", NAPI_AUTO_LENGTH, &resourceName); + + napi_create_async_work( + env, nullptr, resourceName, + [](napi_env env, void *data) { + AsyncDoFinalProcess(env, data); + return; + }, + [](napi_env env, napi_status status, void *data) { + AsyncDoFinalReturn(env, status, data); + return; + }, + (void *)context, + &context->asyncWork); + + napi_queue_async_work(env, context->asyncWork); + if (context->asyncType == ASYNC_PROMISE) { + return context->promise; + } else { + napi_value result = nullptr; + napi_get_null(env, &result); + return result; + } +} + +NapiCipher::NapiCipher(HcfCipher *cipher) +{ + this->cipher_ = cipher; +} + +NapiCipher::~NapiCipher() +{ + OH_HCF_ObjDestroy(this->cipher_); +} + +HcfCipher *NapiCipher::GetCipher() +{ + return this->cipher_; +} + +napi_value NapiCipher::JsCipherInit(napi_env env, napi_callback_info info) +{ + CipherFwkCtx context = (CipherFwkCtx)HcfMalloc(sizeof(CipherFwkCtxT), 0); + if (context == nullptr) { + LOGE("create context fail!"); + return nullptr; + } + + if (!BuildContextForInit(env, info, context)) { + LOGE("build context for init fail!"); + FreeCipherFwkCtx(env, context); + return nullptr; + } + + return NewAsyncInit(env, context); +} + +napi_value NapiCipher::JsCipherUpdate(napi_env env, napi_callback_info info) +{ + CipherFwkCtx context = (CipherFwkCtx)HcfMalloc(sizeof(CipherFwkCtxT), 0); + if (context == nullptr) { + LOGE("create context fail!"); + return nullptr; + } + + if (!BuildContextForUpdate(env, info, context)) { + LOGE("build context for update fail!"); + FreeCipherFwkCtx(env, context); + return nullptr; + } + + return NewAsyncUpdate(env, context); +} + +napi_value NapiCipher::JsCipherDoFinal(napi_env env, napi_callback_info info) +{ + CipherFwkCtx context = (CipherFwkCtx)HcfMalloc(sizeof(CipherFwkCtxT), 0); + if (context == NULL) { + LOGE("create context fail!"); + return nullptr; + } + + if (!BuildContextForFinal(env, info, context)) { + LOGE("build context for final fail!"); + FreeCipherFwkCtx(env, context); + return nullptr; + } + return NewAsyncDoFinal(env, context); +} + +napi_value NapiCipher::JsGetAlgorithm(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + NapiCipher *napiCipher = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); + + // get HcfSymKeyGenerator pointer + napi_status status = napi_unwrap(env, thisVar, (void **)&napiCipher); + if (status != napi_ok) { + LOGE("failed to unwrap napiCipher obj!"); + return nullptr; + } + + HcfCipher *cipher = napiCipher->GetCipher(); + if (cipher == nullptr) { + LOGE("failed to get cipher obj!"); + return nullptr; + } + + // execute C function + const char *algo = cipher->getAlgorithm(cipher); + napi_value instance = nullptr; + napi_create_string_utf8(env, (const char *)algo, NAPI_AUTO_LENGTH, &instance); + return instance; +} + +napi_value NapiCipher::CipherConstructor(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); + + return thisVar; +} + +napi_value NapiCipher::CreateCipher(napi_env env, napi_callback_info info) +{ + size_t exceptedArgc = 1; + size_t argc; + napi_value argv[1] = { nullptr }; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); + + if (argc != exceptedArgc) { + LOGE("The input args num is invalid."); + return nullptr; + } + + // create instance according to input js object + napi_value instance; + napi_value constructor = nullptr; + NAPI_CALL(env, napi_get_reference_value(env, classRef_, &constructor)); + NAPI_CALL(env, napi_new_instance(env, constructor, argc, argv, &instance)); + + // parse input string + std::string algoName; + if (!GetStringFromJSParams(env, argv[0], algoName)) { + LOGE("GetStringFromJSParams failed!"); + return nullptr; + } + + // execute C function, generate C object + HcfCipher *cipher = NULL; + HcfResult res = HcfCipherCreate(algoName.c_str(), &cipher); + if (res != HCF_SUCCESS) { + LOGE("create c cipher fail!"); + return nullptr; + } + NapiCipher *napiCipher = new NapiCipher(cipher); + if (napiCipher == nullptr) { + LOGE("new napiCipher failed!"); + return nullptr; + } + + napi_status status = napi_wrap(env, instance, napiCipher, + [](napi_env env, void *data, void *hint) { + NapiCipher *napiCipher = static_cast(data); + delete napiCipher; + return; + }, + nullptr, + nullptr); + if (status != napi_ok) { + LOGE("failed to wrap napiCipher obj!"); + delete napiCipher; + return nullptr; + } + return instance; +} + +void NapiCipher::DefineCipherJSClass(napi_env env, napi_value exports) +{ + napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("createCipher", CreateCipher), + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); + + napi_property_descriptor classDesc[] = { + DECLARE_NAPI_FUNCTION("init", NapiCipher::JsCipherInit), + DECLARE_NAPI_FUNCTION("update", NapiCipher::JsCipherUpdate), + DECLARE_NAPI_FUNCTION("doFinal", NapiCipher::JsCipherDoFinal), + { .utf8name = "algName", .getter = NapiCipher::JsGetAlgorithm }, + }; + napi_value constructor = nullptr; + napi_define_class(env, "Cipher", NAPI_AUTO_LENGTH, NapiCipher::CipherConstructor, nullptr, + sizeof(classDesc) / sizeof(classDesc[0]), classDesc, &constructor); + napi_create_reference(env, constructor, 1, &classRef_); +} + +} // CryptoFramework +} // OHOS diff --git a/frameworks/js/napi/src/napi_init.cpp b/frameworks/js/napi/src/napi_init.cpp new file mode 100644 index 0000000..09836fc --- /dev/null +++ b/frameworks/js/napi/src/napi_init.cpp @@ -0,0 +1,161 @@ +/* + * Copyright (C) 2022 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 "securec.h" +#include "log.h" +#include "math.h" +#include "memory.h" + +#include "napi_x509_certificate.h" +#include "napi_asy_key_generator.h" +#include "napi_sym_key_generator.h" +#include "napi_cipher.h" +#include "napi_cert_chain_validator.h" +#include "napi_key_pair.h" +#include "napi_pri_key.h" +#include "napi_pub_key.h" +#include "napi_sign.h" +#include "napi_verify.h" +#include "napi_key_agreement.h" +#include "napi_mac.h" +#include "napi_md.h" +#include "napi_rand.h" +#include "napi_sym_key.h" +#include "napi_key.h" +#include "napi_utils.h" +#include "napi_x509_crl_entry.h" +#include "napi_x509_crl.h" +#include "napi_crypto_framework_defines.h" + +namespace OHOS { +namespace CryptoFramework { +static napi_value CreateEncodingFormat(napi_env env) +{ + napi_value encodingFormat = nullptr; + napi_create_object(env, &encodingFormat); + + AddUint32Property(env, encodingFormat, "FORMAT_DER", HCF_FORMAT_DER); + AddUint32Property(env, encodingFormat, "FORMAT_PEM", HCF_FORMAT_PEM); + + return encodingFormat; +} + +static void DefineEncodingFormatProperties(napi_env env, napi_value exports) +{ + napi_property_descriptor desc[] = { + DECLARE_NAPI_PROPERTY("EncodingFormat", CreateEncodingFormat(env)), + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); +} + +static napi_value CreateCryptoMode(napi_env env) +{ + napi_value cryptoMode = nullptr; + napi_create_object(env, &cryptoMode); + + AddUint32Property(env, cryptoMode, "ENCRYPT_MODE", ENCRYPT_MODE); + AddUint32Property(env, cryptoMode, "DECRYPT_MODE", DECRYPT_MODE); + return cryptoMode; +} + +static void DefineCryptoModeProperties(napi_env env, napi_value exports) +{ + napi_property_descriptor desc[] = { + DECLARE_NAPI_PROPERTY("CryptoMode", CreateCryptoMode(env)), + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); +} + +static napi_value CreateResultCode(napi_env env) +{ + napi_value resultCode = nullptr; + napi_create_object(env, &resultCode); + + AddUint32Property(env, resultCode, "INVALID_PARAMS", JS_ERR_INVALID_PARAMS); + AddUint32Property(env, resultCode, "NOT_SUPPORT", JS_ERR_NOT_SUPPORT); + AddUint32Property(env, resultCode, "ERR_OUT_OF_MEMORY", JS_ERR_OUT_OF_MEMORY); + AddUint32Property(env, resultCode, "ERR_INTERNAL_ERROR", JS_ERR_INTERNAL_ERROR); + AddUint32Property(env, resultCode, "ERR_CRYPTO_OPERATION", JS_ERR_CRYPTO_OPERATION); + AddUint32Property(env, resultCode, "ERR_CERT_SIGNATURE_FAILURE", JS_ERR_CERT_SIGNATURE_FAILURE); + AddUint32Property(env, resultCode, "ERR_CERT_NOT_YET_VALID", JS_ERR_CERT_NOT_YET_VALID); + AddUint32Property(env, resultCode, "ERR_CERT_HAS_EXPIRED", JS_ERR_CERT_HAS_EXPIRED); + AddUint32Property(env, resultCode, "ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY", + JS_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY); + AddUint32Property(env, resultCode, "ERR_KEYUSAGE_NO_CERTSIGN", JS_ERR_KEYUSAGE_NO_CERTSIGN); + AddUint32Property(env, resultCode, "ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE", JS_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE); + + return resultCode; +} + +static void DefineResultCodeProperties(napi_env env, napi_value exports) +{ + napi_property_descriptor desc[] = { + DECLARE_NAPI_PROPERTY("Result", CreateResultCode(env)), + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); +} + +/*********************************************** + * Module export and register + ***********************************************/ +static napi_value ModuleExport(napi_env env, napi_value exports) +{ + LOGI("module init start."); + + DefineEncodingFormatProperties(env, exports); + DefineCryptoModeProperties(env, exports); + DefineResultCodeProperties(env, exports); + NapiAsyKeyGenerator::DefineAsyKeyGeneratorJSClass(env, exports); + NapiKeyPair::DefineKeyPairJSClass(env); + NapiPubKey::DefinePubKeyJSClass(env); + NapiPriKey::DefinePriKeyJSClass(env); + + NapiSign::DefineSignJSClass(env, exports); + NapiVerify::DefineVerifyJSClass(env, exports); + NapiKeyAgreement::DefineKeyAgreementJSClass(env, exports); + // NapiCertFactory::DefineCertFactoryJSClass(env, exports); + NapiCertChainValidator::DefineCertChainValidatorJSClass(env, exports); + NapiMac::DefineMacJSClass(env, exports); + NapiMd::DefineMdJSClass(env, exports); + NapiPubKey::DefinePubKeyJSClass(env); + NapiRand::DefineRandJSClass(env, exports); + NapiSymKeyGenerator::DefineSymKeyGeneratorJSClass(env, exports); + NapiCipher::DefineCipherJSClass(env, exports); + NapiSymKey::DefineSymKeyJSClass(env); + NapiKey::DefineHcfKeyJSClass(env); + NapiX509Cert::DefineX509CertJSClass(env, exports); + NapiX509CrlEntry::DefineX509CrlEntryJSClass(env); + NapiX509Crl::DefineX509CrlJSClass(env, exports); + LOGI("module init end."); + return exports; +} + +static napi_module cryptoFrameworkModule = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = ModuleExport, + .nm_modname = "security.cryptoFramework", + .nm_priv = ((void*)0), + .reserved = { 0 }, +}; + +extern "C" __attribute__((constructor)) void RegisterModule(void) +{ + napi_module_register(&cryptoFrameworkModule); +} + +} // namespace CryptoFramework +} // namespace OHOS diff --git a/frameworks/js/napi/src/napi_key.cpp b/frameworks/js/napi/src/napi_key.cpp new file mode 100644 index 0000000..f4fdeec --- /dev/null +++ b/frameworks/js/napi/src/napi_key.cpp @@ -0,0 +1,125 @@ +/* + * Copyright (C) 2022 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 "napi_key.h" + +#include "securec.h" +#include "log.h" +#include "memory.h" + +#include "napi_utils.h" +#include "napi_crypto_framework_defines.h" + +namespace OHOS { +namespace CryptoFramework { + +thread_local napi_ref NapiKey::classRef_ = nullptr; + +NapiKey::NapiKey(HcfKey *hcfKey) +{ + this->hcfKey_ = hcfKey; +} + +NapiKey::~NapiKey() +{ + OH_HCF_ObjDestroy(this->hcfKey_); +} + +HcfKey *NapiKey::GetHcfKey() +{ + return this->hcfKey_; +} + +napi_value NapiKey::JsGetAlgorithm(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + NapiKey *napiKey = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + + (void)napi_unwrap(env, thisVar, (void **)&napiKey); + HcfKey *key = napiKey->GetHcfKey(); + + const char *algo = key->getAlgorithm(key); + napi_value instance = nullptr; + napi_create_string_utf8(env, (const char *)algo, NAPI_AUTO_LENGTH, &instance); + return instance; +} + +napi_value NapiKey::JsGetFormat(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + NapiKey *napiKey = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + + (void)napi_unwrap(env, thisVar, (void **)&napiKey); + HcfKey *key = napiKey->GetHcfKey(); + + const char *format = key->getFormat(key); + napi_value instance = nullptr; + napi_create_string_utf8(env, (const char *)format, NAPI_AUTO_LENGTH, &instance); + return instance; +} + +napi_value NapiKey::JsGetEncoded(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + NapiKey *napiKey = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + + (void)napi_unwrap(env, thisVar, (void **)&napiKey); + HcfKey *key = napiKey->GetHcfKey(); + + HcfBlob blob = {0}; + HcfResult res = key->getEncoded(key, &blob); + if (res != 0) { + LOGE("getEncoded failed!"); + return nullptr; + } + napi_value instance = ConvertBlobToNapiValue(env, &blob); + HcfFree(blob.data); + return instance; +} + +napi_value NapiKey::KeyConstructor(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + return thisVar; +} + +napi_value NapiKey::CreateHcfKey(napi_env env) +{ + napi_value instance; + napi_value constructor = nullptr; + napi_get_reference_value(env, classRef_, &constructor); + napi_new_instance(env, constructor, 0, nullptr, &instance); + return instance; +} + +void NapiKey::DefineHcfKeyJSClass(napi_env env) +{ + napi_property_descriptor classDesc[] = { + DECLARE_NAPI_FUNCTION("getEncoded", NapiKey::JsGetEncoded), + {.utf8name = "format", .getter = NapiKey::JsGetFormat}, + {.utf8name = "algName", .getter = NapiKey::JsGetAlgorithm}, + }; + napi_value constructor = nullptr; + napi_define_class(env, "HcfKey", NAPI_AUTO_LENGTH, KeyConstructor, nullptr, + sizeof(classDesc) / sizeof(classDesc[0]), classDesc, &constructor); + napi_create_reference(env, constructor, 1, &classRef_); +} + +} // CryptoFramework +} // OHOS diff --git a/frameworks/js/napi/src/napi_key_agreement.cpp b/frameworks/js/napi/src/napi_key_agreement.cpp new file mode 100644 index 0000000..754e5d7 --- /dev/null +++ b/frameworks/js/napi/src/napi_key_agreement.cpp @@ -0,0 +1,321 @@ +/* + * Copyright (C) 2022 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 "napi_key_agreement.h" + +#include "securec.h" +#include "log.h" +#include "memory.h" + +#include "napi_crypto_framework_defines.h" +#include "napi_pri_key.h" +#include "napi_pub_key.h" +#include "napi_utils.h" + +namespace OHOS { +namespace CryptoFramework { + +struct KeyAgreementCtx { + napi_env env = nullptr; + + AsyncType asyncType = ASYNC_CALLBACK; + napi_ref callback = nullptr; + napi_deferred deferred = nullptr; + napi_value promise = nullptr; + napi_async_work asyncWork = nullptr; + + HcfKeyAgreement *keyAgreement; + HcfPriKey *priKey; + HcfPubKey *pubKey; + + HcfResult result; + HcfBlob returnSecret; +}; + +thread_local napi_ref NapiKeyAgreement::classRef_ = nullptr; + +static void FreeKeyAgreementCtx(napi_env env, KeyAgreementCtx *ctx) +{ + if (ctx == nullptr) { + return; + } + + if (ctx->asyncWork != nullptr) { + napi_delete_async_work(env, ctx->asyncWork); + ctx->asyncWork = nullptr; + } + + if (ctx->callback != nullptr) { + napi_delete_reference(env, ctx->callback); + ctx->callback = nullptr; + } + + if (ctx->returnSecret.data != nullptr) { + HcfFree(ctx->returnSecret.data); + ctx->returnSecret.data = nullptr; + ctx->returnSecret.len = 0; + } + + HcfFree(ctx); +} + +static bool BuildKeyAgreementJsCtx(napi_env env, napi_callback_info info, KeyAgreementCtx *ctx) +{ + napi_value thisVar = nullptr; + size_t expectedArgc = PARAMS_NUM_THREE; + size_t argc; + 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); + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "params num error.")); + return false; + } + ctx->asyncType = (argc == expectedArgc) ? ASYNC_CALLBACK : ASYNC_PROMISE; + + NapiKeyAgreement *napiKeyAgreement = NULL; + napi_status status = napi_unwrap(env, thisVar, (void **)(&napiKeyAgreement)); + if (status != napi_ok) { + LOGE("failed to unwrap napi verify obj."); + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "[Self]: param unwarp error.")); + return false; + } + + size_t index = 0; + NapiPriKey *napiPriKey = NULL; + status = napi_unwrap(env, argv[index], (void **)(&napiPriKey)); + if (status != napi_ok) { + LOGE("failed to unwrap priKey verify obj."); + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "[PriKey]: param unwarp error.")); + return false; + } + + index++; + NapiPubKey *napiPubKey = NULL; + status = napi_unwrap(env, argv[index], (void **)(&napiPubKey)); + if (status != napi_ok) { + LOGE("failed to unwrap napi pubKey obj."); + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "[PubKey]: param unwarp error.")); + return false; + } + + ctx->keyAgreement = napiKeyAgreement->GetKeyAgreement(); + ctx->priKey = napiPriKey->GetPriKey(); + ctx->pubKey = napiPubKey->GetPubKey(); + + if (ctx->asyncType == ASYNC_PROMISE) { + napi_create_promise(env, &ctx->deferred, &ctx->promise); + return true; + } else { + return GetCallbackFromJSParams(env, argv[expectedArgc - 1], &ctx->callback); + } +} + +static void ReturnCallbackResult(napi_env env, KeyAgreementCtx *ctx, napi_value result) +{ + napi_value businessError = nullptr; + if (ctx->result != HCF_SUCCESS) { + businessError = GenerateBusinessError(env, ctx->result, COMMON_ERR_MSG.c_str()); + } + + napi_value params[ARGS_SIZE_TWO] = { businessError, result }; + + napi_value func = nullptr; + napi_get_reference_value(env, ctx->callback, &func); + + napi_value recv = nullptr; + napi_value callFuncRet = nullptr; + napi_get_undefined(env, &recv); + napi_call_function(env, recv, func, ARGS_SIZE_TWO, params, &callFuncRet); +} + +static void ReturnPromiseResult(napi_env env, KeyAgreementCtx *ctx, napi_value result) +{ + if (ctx->result == HCF_SUCCESS) { + napi_resolve_deferred(env, ctx->deferred, result); + } else { + napi_reject_deferred(env, ctx->deferred, GenerateBusinessError(env, ctx->result, COMMON_ERR_MSG.c_str())); + } +} + +void KeyAgreementAsyncWorkProcess(napi_env env, void *data) +{ + KeyAgreementCtx *ctx = static_cast(data); + + HcfResult res = ctx->keyAgreement->generateSecret(ctx->keyAgreement, + ctx->priKey, ctx->pubKey, &ctx->returnSecret); + + ctx->result = res; + if (res != HCF_SUCCESS) { + LOGE("generate secret fail."); + } +} + +void KeyAgreementAsyncWorkReturn(napi_env env, napi_status status, void *data) +{ + KeyAgreementCtx *ctx = static_cast(data); + + napi_value dataBlob = nullptr; + if (ctx->result == HCF_SUCCESS) { + dataBlob = ConvertBlobToNapiValue(env, &ctx->returnSecret); + } + + if (ctx->asyncType == ASYNC_CALLBACK) { + ReturnCallbackResult(env, ctx, dataBlob); + } else { + ReturnPromiseResult(env, ctx, dataBlob); + } + FreeKeyAgreementCtx(env, ctx); +} + +static napi_value NewKeyAgreementAsyncWork(napi_env env, KeyAgreementCtx *ctx) +{ + napi_value resourceName = nullptr; + napi_create_string_utf8(env, "generateSecret", NAPI_AUTO_LENGTH, &resourceName); + + napi_create_async_work( + env, nullptr, resourceName, + [](napi_env env, void *data) { + KeyAgreementAsyncWorkProcess(env, data); + return; + }, + [](napi_env env, napi_status status, void *data) { + KeyAgreementAsyncWorkReturn(env, status, data); + return; + }, + (void *)ctx, + &ctx->asyncWork); + + napi_queue_async_work(env, ctx->asyncWork); + if (ctx->asyncType == ASYNC_PROMISE) { + return ctx->promise; + } else { + napi_value result = nullptr; + napi_get_null(env, &result); + return result; + } +} + +NapiKeyAgreement::NapiKeyAgreement(HcfKeyAgreement *keyAgreement) +{ + this->keyAgreement_ = keyAgreement; +} + +NapiKeyAgreement::~NapiKeyAgreement() +{ + OH_HCF_ObjDestroy(this->keyAgreement_); +} + +HcfKeyAgreement *NapiKeyAgreement::GetKeyAgreement() +{ + return this->keyAgreement_; +} + +napi_value NapiKeyAgreement::JsGenerateSecret(napi_env env, napi_callback_info info) +{ + LOGI("enter ..."); + KeyAgreementCtx *ctx = (KeyAgreementCtx *)HcfMalloc(sizeof(KeyAgreementCtx), 0); + if (ctx == NULL) { + LOGE("create context fail."); + return NULL; + } + + if (!BuildKeyAgreementJsCtx(env, info, ctx)) { + LOGE("build context fail."); + FreeKeyAgreementCtx(env, ctx); + return nullptr; + } + + return NewKeyAgreementAsyncWork(env, ctx); +} + +napi_value NapiKeyAgreement::KeyAgreementConstructor(napi_env env, napi_callback_info info) +{ + LOGI("enter ..."); + + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + + LOGI("out ..."); + return thisVar; +} + +napi_value NapiKeyAgreement::CreateJsKeyAgreement(napi_env env, napi_callback_info info) +{ + LOGI("enter ..."); + size_t exceptedArgc = PARAMS_NUM_ONE; + size_t argc; + napi_value argv[PARAMS_NUM_ONE] = { nullptr }; + napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); + + if (argc != exceptedArgc) { + LOGE("The input args num is invalid."); + return nullptr; + } + + napi_value instance; + napi_value constructor = nullptr; + napi_get_reference_value(env, classRef_, &constructor); + napi_new_instance(env, constructor, argc, argv, &instance); + + std::string algName; + if (!GetStringFromJSParams(env, argv[0], algName)) { + return nullptr; + } + + HcfKeyAgreement *keyAgreement = NULL; + int32_t res = HcfKeyAgreementCreate(algName.c_str(), &keyAgreement); + if (res != HCF_SUCCESS) { + LOGE("create c keyAgreement fail."); + return nullptr; + } + + NapiKeyAgreement *napiKeyAgreement = new NapiKeyAgreement(keyAgreement); + + napi_wrap( + env, instance, napiKeyAgreement, + [](napi_env env, void *data, void *hint) { + NapiKeyAgreement *napiKeyAgreement = static_cast(data); + delete napiKeyAgreement; + return; + }, + nullptr, + nullptr); + + napi_value napiAlgName = nullptr; + napi_create_string_utf8(env, algName.c_str(), NAPI_AUTO_LENGTH, &napiAlgName); + napi_set_named_property(env, instance, CRYPTO_TAG_ALG_NAME.c_str(), napiAlgName); + + LOGI("out ..."); + return instance; +} + +void NapiKeyAgreement::DefineKeyAgreementJSClass(napi_env env, napi_value exports) +{ + napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("createKeyAgreement", NapiKeyAgreement::CreateJsKeyAgreement), + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); + + napi_property_descriptor classDesc[] = { + DECLARE_NAPI_FUNCTION("generateSecret", NapiKeyAgreement::JsGenerateSecret), + }; + napi_value constructor = nullptr; + napi_define_class(env, "KeyAgreement", NAPI_AUTO_LENGTH, NapiKeyAgreement::KeyAgreementConstructor, nullptr, + sizeof(classDesc) / sizeof(classDesc[0]), classDesc, &constructor); + napi_create_reference(env, constructor, 1, &classRef_); +} +} // CryptoFramework +} // OHOS diff --git a/frameworks/js/napi/src/napi_key_pair.cpp b/frameworks/js/napi/src/napi_key_pair.cpp new file mode 100644 index 0000000..08343f1 --- /dev/null +++ b/frameworks/js/napi/src/napi_key_pair.cpp @@ -0,0 +1,100 @@ +/* + * Copyright (C) 2022 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 "napi_key_pair.h" + +#include "securec.h" +#include "log.h" +#include "memory.h" +#include "napi_crypto_framework_defines.h" +#include "napi_pri_key.h" +#include "napi_pub_key.h" + +#include "napi_utils.h" + +namespace OHOS { +namespace CryptoFramework { + +thread_local napi_ref NapiKeyPair::classRef_ = nullptr; + +NapiKeyPair::NapiKeyPair(HcfKeyPair *keyPair) +{ + this->keyPair_ = keyPair; +} + +NapiKeyPair::~NapiKeyPair() +{ + OH_HCF_ObjDestroy(this->keyPair_); +} + +napi_value NapiKeyPair::KeyPairConstructor(napi_env env, napi_callback_info info) +{ + LOGI("enter ..."); + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + LOGI("out ..."); + return thisVar; +} + +napi_value NapiKeyPair::ConvertToJsKeyPair(napi_env env) +{ + LOGI("enter ..."); + + napi_value instance; + napi_value constructor = nullptr; + napi_get_reference_value(env, classRef_, &constructor); + napi_new_instance(env, constructor, 0, nullptr, &instance); + + NapiPubKey *napiPubKey = new NapiPubKey(this->keyPair_->pubKey); + NapiPriKey *napiPriKey = new NapiPriKey(this->keyPair_->priKey); + + napi_value pubKey = napiPubKey->ConvertToJsPubKey(env); + napi_value priKey = napiPriKey->ConvertToJsPriKey(env); + + napi_wrap( + env, pubKey, napiPubKey, + [](napi_env env, void *data, void *hint) { + NapiPubKey *napiPubKey = static_cast(data); + delete napiPubKey; + return; + }, + nullptr, nullptr); + napi_wrap( + env, priKey, napiPriKey, + [](napi_env env, void *data, void *hint) { + NapiPriKey *napiPriKey = static_cast(data); + delete napiPriKey; + return; + }, + nullptr, nullptr); + + napi_set_named_property(env, instance, CRYPTO_TAG_PUB_KEY.c_str(), pubKey); + napi_set_named_property(env, instance, CRYPTO_TAG_PRI_KEY.c_str(), priKey); + + LOGI("out ..."); + return instance; +} + +void NapiKeyPair::DefineKeyPairJSClass(napi_env env) +{ + napi_property_descriptor classDesc[] = {}; + napi_value constructor = nullptr; + napi_define_class(env, "KeyPair", NAPI_AUTO_LENGTH, KeyPairConstructor, nullptr, + sizeof(classDesc) / sizeof(classDesc[0]), classDesc, &constructor); + napi_create_reference(env, constructor, 1, &classRef_); +} + +} // CryptoFramework +} // OHOS diff --git a/frameworks/js/napi/src/napi_mac.cpp b/frameworks/js/napi/src/napi_mac.cpp new file mode 100644 index 0000000..4525b8f --- /dev/null +++ b/frameworks/js/napi/src/napi_mac.cpp @@ -0,0 +1,484 @@ +/* + * Copyright (C) 2022 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 "napi_mac.h" + +#include "securec.h" +#include "log.h" +#include "memory.h" + +#include "napi_sym_key.h" +#include "napi_utils.h" +#include "napi_crypto_framework_defines.h" + +namespace OHOS { +namespace CryptoFramework { + +napi_ref NapiMac::classRef_ = nullptr; + +struct MacCtx { + napi_env env = nullptr; + + CfAsyncType asyncType = ASYNC_TYPE_CALLBACK; + napi_ref callback = nullptr; + napi_deferred deferred = nullptr; + napi_value promise = nullptr; + napi_async_work asyncWork = nullptr; + + NapiMac *macClass = nullptr; + std::string algoName = ""; + HcfSymKey *symKey = nullptr; + HcfBlob *inBlob = nullptr; + + HcfResult errCode = HCF_SUCCESS; + const char *errMsg = nullptr; + HcfBlob *outBlob = nullptr; +}; + +static void FreeCryptoFwkCtx(napi_env env, MacCtx *context) +{ + if (context == nullptr) { + return; + } + if (context->asyncWork != nullptr) { + napi_delete_async_work(env, context->asyncWork); + context->asyncWork = nullptr; + } + if (context->callback != nullptr) { + napi_delete_reference(env, context->callback); + context->callback = nullptr; + } + if (context->symKey != nullptr) { + OH_HCF_ObjDestroy(context->symKey); + } + if (context->inBlob != nullptr) { + HcfFree(context->inBlob->data); + context->inBlob->data = nullptr; + context->inBlob->len = 0; + } + if (context->outBlob != nullptr) { + HcfFree(context->outBlob->data); + context->outBlob->data = nullptr; + context->outBlob->len = 0; + } + HcfFree(context); +} + +static void ReturnCallbackResult(napi_env env, MacCtx *context, napi_value result) +{ + napi_value businessError = nullptr; + if (context->errCode != HCF_SUCCESS) { + businessError = GenerateBusinessError(env, context->errCode, context->errMsg); + } + napi_value params[ARGS_SIZE_TWO] = { businessError, result }; + + napi_value func = nullptr; + napi_get_reference_value(env, context->callback, &func); + + napi_value recv = nullptr; + napi_value callFuncRet = nullptr; + napi_get_undefined(env, &recv); + napi_call_function(env, recv, func, ARGS_SIZE_TWO, params, &callFuncRet); +} + +static void ReturnPromiseResult(napi_env env, MacCtx *context, napi_value result) +{ + if (context->errCode == HCF_SUCCESS) { + napi_resolve_deferred(env, context->deferred, result); + } else { + napi_reject_deferred(env, context->deferred, GenerateBusinessError(env, context->errCode, context->errMsg)); + } +} + +static bool CreateCallbackAndPromise(napi_env env, MacCtx *context, size_t argc, + size_t maxCount, napi_value callbackValue) +{ + context->asyncType = (argc == maxCount) ? ASYNC_TYPE_CALLBACK : ASYNC_TYPE_PROMISE; + if (context->asyncType == ASYNC_TYPE_CALLBACK) { + if (!GetCallbackFromJSParams(env, callbackValue, &context->callback)) { + LOGE("get callback failed!"); + return false; + } + } else { + napi_create_promise(env, &context->deferred, &context->promise); + } + return true; +} + +NapiMac::NapiMac(HcfMac *macObj) +{ + this->macObj_ = macObj; +} + +NapiMac::~NapiMac() +{ + OH_HCF_ObjDestroy(this->macObj_); +} + +static void MacInitExecute(napi_env env, void *data) +{ + LOGI("enter MacInitExecute ..."); + MacCtx *context = static_cast(data); + NapiMac *macClass = context->macClass; + HcfMac *macObj = macClass->GetMac(); + HcfSymKey *symKey = (HcfSymKey *)context->symKey; + context->errCode = macObj->init(macObj, symKey); + if (context->errCode != HCF_SUCCESS) { + LOGE("init failed!"); + context->errMsg = "init failed"; + } +} + +static void MacInitComplete(napi_env env, napi_status status, void *data) +{ + MacCtx *context = static_cast(data); + napi_value nullInstance = nullptr; + napi_get_null(env, &nullInstance); + if (context->asyncType == ASYNC_TYPE_CALLBACK) { + ReturnCallbackResult(env, context, nullInstance); + } else { + ReturnPromiseResult(env, context, nullInstance); + } + FreeCryptoFwkCtx(env, context); +} + +static void MacUpdateExecute(napi_env env, void *data) +{ + MacCtx *context = static_cast(data); + NapiMac *macClass = context->macClass; + HcfMac *macObj = macClass->GetMac(); + HcfBlob *inBlob = static_cast(context->inBlob); + context->errCode = macObj->update(macObj, inBlob); + if (context->errCode != HCF_SUCCESS) { + LOGE("update failed!"); + context->errMsg = "update failed"; + } +} + +static void MacUpdateComplete(napi_env env, napi_status status, void *data) +{ + MacCtx *context = static_cast(data); + napi_value nullInstance = nullptr; + napi_get_null(env, &nullInstance); + if (context->asyncType == ASYNC_TYPE_CALLBACK) { + ReturnCallbackResult(env, context, nullInstance); + } else { + ReturnPromiseResult(env, context, nullInstance); + } + FreeCryptoFwkCtx(env, context); +} + +static void MacDoFinalExecute(napi_env env, void *data) +{ + MacCtx *context = static_cast(data); + NapiMac *macClass = context->macClass; + HcfMac *macObj = macClass->GetMac(); + HcfBlob *outBlob = (HcfBlob *)HcfMalloc(sizeof(HcfBlob), 0); + if (outBlob == nullptr) { + LOGE("outBlob is null!"); + context->errCode = HCF_ERR_MALLOC; + context->errMsg = "malloc data blob failed"; + return; + } + context->errCode = macObj->doFinal(macObj, outBlob); + if (context->errCode != HCF_SUCCESS) { + LOGE("doFinal failed!"); + context->errMsg = "doFinal failed"; + return; + } + context->outBlob = outBlob; +} + +static void MacDoFinalComplete(napi_env env, napi_status status, void *data) +{ + LOGI("enter MacDoFinalComplete ..."); + MacCtx *context = static_cast(data); + napi_value returnOutBlob = ConvertBlobToNapiValue(env, context->outBlob); + if (returnOutBlob == nullptr) { + LOGE("returnOutBlob is nullptr!"); + returnOutBlob = NapiGetNull(env); + } + if (context->asyncType == ASYNC_TYPE_CALLBACK) { + ReturnCallbackResult(env, context, returnOutBlob); + } else { + ReturnPromiseResult(env, context, returnOutBlob); + } + FreeCryptoFwkCtx(env, context); +} + +napi_value NapiMac::MacInit(napi_env env, napi_callback_info info) +{ + size_t expectedArgsCount = ARGS_SIZE_TWO; + size_t argc = expectedArgsCount; + napi_value argv[ARGS_SIZE_TWO] = { 0 }; + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_TWO, false)) { + return nullptr; + } + MacCtx *context = (MacCtx *)HcfMalloc(sizeof(MacCtx), 0); + if (context == nullptr) { + napi_throw(env, GenerateBusinessError(env, HCF_ERR_MALLOC, "malloc context failed")); + LOGE("malloc context failed!"); + return nullptr; + } + context->macClass = this; + NapiSymKey *symKey = nullptr; + napi_unwrap(env, argv[PARAM0], (void**)&symKey); + if (symKey == nullptr) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "symKey is null")); + LOGE("symKey is null!"); + FreeCryptoFwkCtx(env, context); + return nullptr; + } + context->symKey = symKey->GetSymKey(); + context->asyncType = (argc == expectedArgsCount) ? ASYNC_TYPE_CALLBACK : ASYNC_TYPE_PROMISE; + if (!CreateCallbackAndPromise(env, context, argc, ARGS_SIZE_TWO, argv[PARAM1])) { + FreeCryptoFwkCtx(env, context); + return nullptr; + } + napi_create_async_work( + env, nullptr, GetResourceName(env, "Init"), + MacInitExecute, + MacInitComplete, + (void *)context, + &context->asyncWork); + napi_queue_async_work(env, context->asyncWork); + if (context->asyncType == ASYNC_TYPE_PROMISE) { + return context->promise; + } else { + return NapiGetNull(env); + } +} + +napi_value NapiMac::MacUpdate(napi_env env, napi_callback_info info) +{ + size_t expectedArgsCount = ARGS_SIZE_TWO; + size_t argc = expectedArgsCount; + napi_value argv[ARGS_SIZE_TWO] = { 0 }; + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_TWO, false)) { + return nullptr; + } + MacCtx *context = (MacCtx *)HcfMalloc(sizeof(MacCtx), 0); + if (context == nullptr) { + napi_throw(env, GenerateBusinessError(env, HCF_ERR_MALLOC, "malloc context failed")); + LOGE("malloc context failed!"); + return nullptr; + } + context->macClass = this; + context->inBlob = GetBlobFromNapiValue(env, argv[PARAM0]); + if (context->inBlob == nullptr) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "inBlob is null")); + LOGE("inBlob is null!"); + return nullptr; + } + if (!CreateCallbackAndPromise(env, context, argc, ARGS_SIZE_TWO, argv[PARAM1])) { + FreeCryptoFwkCtx(env, context); + return nullptr; + } + napi_create_async_work( + env, nullptr, GetResourceName(env, "MacUpate"), + MacUpdateExecute, + MacUpdateComplete, + (void *)context, + &context->asyncWork); + napi_queue_async_work(env, context->asyncWork); + if (context->asyncType == ASYNC_TYPE_PROMISE) { + return context->promise; + } else { + return NapiGetNull(env); + } +} + +napi_value NapiMac::MacDoFinal(napi_env env, napi_callback_info info) +{ + size_t expectedArgsCount = ARGS_SIZE_ONE; + size_t argc = expectedArgsCount; + napi_value argv[ARGS_SIZE_ONE] = { 0 }; + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ONE, false)) { + return nullptr; + } + MacCtx *context = (MacCtx *)HcfMalloc(sizeof(MacCtx), 0); + if (context == nullptr) { + napi_throw(env, GenerateBusinessError(env, HCF_ERR_MALLOC, "malloc context failed")); + LOGE("malloc context failed!"); + return nullptr; + } + context->macClass = this; + context->asyncType = (argc == expectedArgsCount) ? ASYNC_TYPE_CALLBACK : ASYNC_TYPE_PROMISE; + if (!CreateCallbackAndPromise(env, context, argc, ARGS_SIZE_ONE, argv[PARAM0])) { + FreeCryptoFwkCtx(env, context); + return nullptr; + } + napi_create_async_work( + env, nullptr, GetResourceName(env, "MacDoFinal"), + MacDoFinalExecute, + MacDoFinalComplete, + (void *)context, + &context->asyncWork); + napi_queue_async_work(env, context->asyncWork); + if (context->asyncType == ASYNC_TYPE_PROMISE) { + return context->promise; + } else { + return NapiGetNull(env); + } +} + +napi_value NapiMac::GetMacLength(napi_env env, napi_callback_info info) +{ + size_t expectedArgsCount = ARGS_SIZE_ZERO; + size_t argc = expectedArgsCount; + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, &argc, nullptr, &thisVar, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ZERO, true)) { + return nullptr; + } + HcfMac *macObj = GetMac(); + uint32_t retLen = macObj->getMacLength(macObj); + napi_value napiLen = nullptr; + napi_create_uint32(env, retLen, &napiLen); + return napiLen; +} + +static napi_value NapiMacInit(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiMac *macObj = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&macObj)); + if (macObj == nullptr) { + LOGE("macObj is nullptr!"); + return NapiGetNull(env); + } + return macObj->MacInit(env, info); +} + +static napi_value NapiMacUpdate(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiMac *macObj = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&macObj)); + if (macObj == nullptr) { + LOGE("macObj is nullptr!"); + return NapiGetNull(env); + } + return macObj->MacUpdate(env, info); +} + +static napi_value NapiMacDoFinal(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiMac *macObj = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&macObj)); + if (macObj == nullptr) { + LOGE("macObj is nullptr!"); + return NapiGetNull(env); + } + return macObj->MacDoFinal(env, info); +} + +static napi_value NapiGetMacLength(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiMac *macObj = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&macObj)); + if (macObj == nullptr) { + LOGE("macObj is nullptr!"); + return NapiGetNull(env); + } + return macObj->GetMacLength(env, info); +} + +napi_value NapiMac::MacConstructor(napi_env env, napi_callback_info info) +{ + printf("enter MacConstructor..."); + napi_value thisVar = nullptr; + size_t exceptedArgc = ARGS_SIZE_ONE; + size_t argc = exceptedArgc; + napi_value argv[ARGS_SIZE_ONE] = { 0 }; + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + std::string algoName; + if (!GetStringFromJSParams(env, argv[0], algoName)) { + return NapiGetNull(env); + } + HcfMac *macObj = nullptr; + int32_t res = HcfMacCreate(algoName.c_str(), &macObj); + if (res != HCF_SUCCESS) { + LOGE("create c macObj failed."); + return NapiGetNull(env); + } + NapiMac *macNapiObj = new NapiMac(macObj); + napi_wrap( + env, thisVar, macNapiObj, + [](napi_env env, void *data, void *hint) { + NapiMac *mac = (NapiMac *)(data); + delete mac; + return; + }, + nullptr, + nullptr); + napi_value napiAlgName = nullptr; + napi_create_string_utf8(env, algoName.c_str(), NAPI_AUTO_LENGTH, &napiAlgName); + napi_set_named_property(env, thisVar, CRYPTO_TAG_ALG_NAME.c_str(), napiAlgName); + printf("out MacConstructor..."); + return thisVar; +} + +napi_value NapiMac::CreateMac(napi_env env, napi_callback_info info) +{ + printf("enter CreateMac..."); + size_t exceptedArgc = ARGS_SIZE_ONE; + size_t argc; + napi_value argv[ARGS_SIZE_ONE] = { 0 }; + napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); + if (argc != exceptedArgc) { + LOGE("The input args num is invalid."); + return NapiGetNull(env); + } + napi_value instance; + napi_value constructor = nullptr; + napi_get_reference_value(env, classRef_, &constructor); + napi_new_instance(env, constructor, argc, argv, &instance); + printf("out CreateMac..."); + return instance; +} + +void NapiMac::DefineMacJSClass(napi_env env, napi_value exports) +{ + napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("createMac", CreateMac), + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); + napi_property_descriptor classDesc[] = { + DECLARE_NAPI_FUNCTION("init", NapiMacInit), + DECLARE_NAPI_FUNCTION("update", NapiMacUpdate), + DECLARE_NAPI_FUNCTION("doFinal", NapiMacDoFinal), + DECLARE_NAPI_FUNCTION("getMacLength", NapiGetMacLength), + }; + napi_value constructor = nullptr; + napi_define_class(env, "Mac", NAPI_AUTO_LENGTH, MacConstructor, nullptr, + sizeof(classDesc) / sizeof(classDesc[0]), classDesc, &constructor); + napi_create_reference(env, constructor, 1, &classRef_); +} + +} // CryptoFramework +} // OHOS \ No newline at end of file diff --git a/frameworks/js/napi/src/napi_md.cpp b/frameworks/js/napi/src/napi_md.cpp new file mode 100644 index 0000000..25463f4 --- /dev/null +++ b/frameworks/js/napi/src/napi_md.cpp @@ -0,0 +1,390 @@ +/* + * Copyright (C) 2022 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 "napi_md.h" + +#include "securec.h" +#include "log.h" +#include "memory.h" + +#include "napi_utils.h" +#include "napi_crypto_framework_defines.h" + +namespace OHOS { +namespace CryptoFramework { + +napi_ref NapiMd::classRef_ = nullptr; + +struct MdCtx { + napi_env env = nullptr; + + CfAsyncType asyncType = ASYNC_TYPE_CALLBACK; + napi_ref callback = nullptr; + napi_deferred deferred = nullptr; + napi_value promise = nullptr; + + napi_async_work asyncWork = nullptr; + + NapiMd *mdClass = nullptr; + std::string algoName = ""; + HcfBlob *inBlob = nullptr; + + HcfResult errCode = HCF_SUCCESS; + const char *errMsg = nullptr; + HcfBlob *outBlob = nullptr; +}; + +static void FreeCryptoFwkCtx(napi_env env, MdCtx *context) +{ + if (context == nullptr) { + return; + } + if (context->asyncWork != nullptr) { + napi_delete_async_work(env, context->asyncWork); + context->asyncWork = nullptr; + } + if (context->callback != nullptr) { + napi_delete_reference(env, context->callback); + context->callback = nullptr; + } + if (context->inBlob != nullptr) { + HcfFree(context->inBlob->data); + context->inBlob->data = nullptr; + context->inBlob->len = 0; + } + if (context->outBlob != nullptr) { + HcfFree(context->outBlob->data); + context->outBlob->data = nullptr; + context->outBlob->len = 0; + } + HcfFree(context); +} + +static void ReturnCallbackResult(napi_env env, MdCtx *context, napi_value result) +{ + napi_value businessError = GenerateBusinessError(env, context->errCode, context->errMsg); + napi_value params[ARGS_SIZE_TWO] = { businessError, result }; + napi_value func = nullptr; + napi_get_reference_value(env, context->callback, &func); + + napi_value recv = nullptr; + napi_value callFuncRet = nullptr; + napi_get_undefined(env, &recv); + napi_call_function(env, recv, func, ARGS_SIZE_TWO, params, &callFuncRet); +} + +static void ReturnPromiseResult(napi_env env, MdCtx *context, napi_value result) +{ + if (context->errCode == HCF_SUCCESS) { + napi_resolve_deferred(env, context->deferred, result); + } else { + napi_reject_deferred(env, context->deferred, GenerateBusinessError(env, context->errCode, context->errMsg)); + } +} + +static bool CreateCallbackAndPromise(napi_env env, MdCtx *context, size_t argc, + size_t maxCount, napi_value callbackValue) +{ + context->asyncType = (argc == maxCount) ? ASYNC_TYPE_CALLBACK : ASYNC_TYPE_PROMISE; + if (context->asyncType == ASYNC_TYPE_CALLBACK) { + if (!GetCallbackFromJSParams(env, callbackValue, &context->callback)) { + LOGE("get callback failed!"); + return false; + } + } else { + napi_create_promise(env, &context->deferred, &context->promise); + } + return true; +} + +NapiMd::NapiMd(HcfMd *mdObj) +{ + this->mdObj_ = mdObj; +} + +NapiMd::~NapiMd() +{ + OH_HCF_ObjDestroy(this->mdObj_); +} + +static void MdUpdateExecute(napi_env env, void *data) +{ + MdCtx *context = static_cast(data); + NapiMd *mdClass = context->mdClass; + HcfMd *mdObj = mdClass->GetMd(); + context->errCode = mdObj->update(mdObj, context->inBlob); + if (context->errCode != HCF_SUCCESS) { + LOGE("update failed!"); + context->errMsg = "update failed"; + } +} + +static void MdUpdateComplete(napi_env env, napi_status status, void *data) +{ + MdCtx *context = static_cast(data); + napi_value nullInstance = nullptr; + napi_get_null(env, &nullInstance); + if (context->asyncType == ASYNC_TYPE_CALLBACK) { + ReturnCallbackResult(env, context, nullInstance); + } else { + ReturnPromiseResult(env, context, nullInstance); + } + FreeCryptoFwkCtx(env, context); +} + +static void MdDoFinalExecute(napi_env env, void *data) +{ + MdCtx *context = static_cast(data); + NapiMd *mdClass = context->mdClass; + HcfMd *mdObj = mdClass->GetMd(); + HcfBlob *outBlob = (HcfBlob *)HcfMalloc(sizeof(HcfBlob), 0); + if (outBlob == nullptr) { + LOGE("outBlob is null!"); + context->errCode = HCF_ERR_MALLOC; + context->errMsg = "malloc data blob failed"; + return; + } + context->errCode = mdObj->doFinal(mdObj, outBlob); + if (context->errCode != HCF_SUCCESS) { + LOGE("doFinal failed!"); + context->errMsg = "doFinal failed"; + return; + } + context->outBlob = outBlob; +} + +static void MdDoFinalComplete(napi_env env, napi_status status, void *data) +{ + MdCtx *context = static_cast(data); + napi_value returnOutBlob = ConvertBlobToNapiValue(env, context->outBlob); + if (returnOutBlob == nullptr) { + LOGE("returnOutBlob is nullptr!"); + returnOutBlob = NapiGetNull(env); + } + if (context->asyncType == ASYNC_TYPE_CALLBACK) { + ReturnCallbackResult(env, context, returnOutBlob); + } else { + ReturnPromiseResult(env, context, returnOutBlob); + } + FreeCryptoFwkCtx(env, context); +} + +napi_value NapiMd::MdUpdate(napi_env env, napi_callback_info info) +{ + // check param count + size_t argc = ARGS_SIZE_TWO; + napi_value argv[ARGS_SIZE_TWO] = { 0 }; + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_TWO, false)) { + return nullptr; + } + MdCtx *context = (MdCtx *)HcfMalloc(sizeof(MdCtx), 0); + if (context == nullptr) { + napi_throw(env, GenerateBusinessError(env, HCF_ERR_MALLOC, "malloc context failed")); + LOGE("malloc context failed!"); + return nullptr; + } + context->mdClass = this; + context->inBlob = GetBlobFromNapiValue(env, argv[PARAM0]); + if (context->inBlob == nullptr) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "inBlob is null")); + LOGE("inBlob is null!"); + return nullptr; + } + if (!CreateCallbackAndPromise(env, context, argc, ARGS_SIZE_TWO, argv[PARAM1])) { + FreeCryptoFwkCtx(env, context); + return nullptr; + } + napi_create_async_work( + env, nullptr, GetResourceName(env, "MdUpdate"), + MdUpdateExecute, + MdUpdateComplete, + (void *)context, + &context->asyncWork); + napi_queue_async_work(env, context->asyncWork); + if (context->asyncType == ASYNC_TYPE_PROMISE) { + return context->promise; + } else { + return NapiGetNull(env); + } +} + +napi_value NapiMd::MdDoFinal(napi_env env, napi_callback_info info) +{ + size_t expectedArgsCount = ARGS_SIZE_ONE; + size_t argc = expectedArgsCount; + napi_value argv[ARGS_SIZE_ONE] = { 0 }; + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ONE, false)) { + return nullptr; + } + MdCtx *context = (MdCtx *)HcfMalloc(sizeof(MdCtx), 0); + if (context == nullptr) { + napi_throw(env, GenerateBusinessError(env, HCF_ERR_MALLOC, "malloc context failed")); + LOGE("malloc context failed!"); + return nullptr; + } + context->mdClass = this; + if (!CreateCallbackAndPromise(env, context, argc, ARGS_SIZE_ONE, argv[PARAM0])) { + FreeCryptoFwkCtx(env, context); + return nullptr; + } + napi_create_async_work( + env, nullptr, GetResourceName(env, "MdDoFinal"), + MdDoFinalExecute, + MdDoFinalComplete, + (void *)context, + &context->asyncWork); + napi_queue_async_work(env, context->asyncWork); + if (context->asyncType == ASYNC_TYPE_PROMISE) { + return context->promise; + } else { + return NapiGetNull(env); + } +} + +napi_value NapiMd::GetMdLength(napi_env env, napi_callback_info info) +{ + size_t expectedArgsCount = ARGS_SIZE_ZERO; + size_t argc = expectedArgsCount; + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, &argc, nullptr, &thisVar, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ZERO, true)) { + return nullptr; + } + HcfMd *mdObj = GetMd(); + uint32_t retLen = mdObj->getMdLength(mdObj); + napi_value napiLen = nullptr; + napi_create_uint32(env, retLen, &napiLen); + return napiLen; +} + +static napi_value NapiMdUpdate(napi_env env, napi_callback_info info) +{ + LOGI("enter NapiMdUpdate ..."); + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiMd *mdObj = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&mdObj)); + if (mdObj == nullptr) { + LOGE("mdObj is nullptr!"); + return NapiGetNull(env); + } + return mdObj->MdUpdate(env, info); +} + +static napi_value NapiMdDoFinal(napi_env env, napi_callback_info info) +{ + LOGI("enter NapiMdDoFinal ..."); + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiMd *mdObj = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&mdObj)); + if (mdObj == nullptr) { + LOGE("mdObj is nullptr!"); + return NapiGetNull(env); + } + return mdObj->MdDoFinal(env, info); +} + +static napi_value NapiGetMdLength(napi_env env, napi_callback_info info) +{ + LOGI("enter NapiGetMdLength ..."); + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiMd *mdObj = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&mdObj)); + if (mdObj == nullptr) { + LOGE("mdObj is nullptr!"); + return NapiGetNull(env); + } + return mdObj->GetMdLength(env, info); +} + +napi_value NapiMd::MdConstructor(napi_env env, napi_callback_info info) +{ + printf("enter MdConstructor..."); + napi_value thisVar = nullptr; + size_t exceptedArgc = ARGS_SIZE_ONE; + size_t argc = exceptedArgc; + napi_value argv[ARGS_SIZE_ONE] = { 0 }; + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + std::string algoName; + if (!GetStringFromJSParams(env, argv[PARAM0], algoName)) { + return NapiGetNull(env); + } + HcfMd *mdObj = nullptr; + int32_t res = HcfMdCreate(algoName.c_str(), &mdObj); + if (res != HCF_SUCCESS) { + LOGE("create c mdObj failed."); + return NapiGetNull(env); + } + NapiMd *mdNapiObj = new NapiMd(mdObj); + napi_wrap( + env, thisVar, mdNapiObj, + [](napi_env env, void *data, void *hint) { + NapiMd *md = (NapiMd *)(data); + delete md; + return; + }, + nullptr, + nullptr); + napi_value napiAlgName = nullptr; + napi_create_string_utf8(env, algoName.c_str(), NAPI_AUTO_LENGTH, &napiAlgName); + napi_set_named_property(env, thisVar, CRYPTO_TAG_ALG_NAME.c_str(), napiAlgName); + printf("out MdConstructor..."); + return thisVar; +} + +napi_value NapiMd::CreateMd(napi_env env, napi_callback_info info) +{ + printf("enter CreateMd..."); + size_t exceptedArgc = ARGS_SIZE_ONE; + size_t argc; + napi_value argv[ARGS_SIZE_ONE] = { 0 }; + napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); + if (argc != exceptedArgc) { + LOGE("The input args num is invalid."); + return NapiGetNull(env); + } + napi_value instance; + napi_value constructor = nullptr; + napi_get_reference_value(env, classRef_, &constructor); + napi_new_instance(env, constructor, argc, argv, &instance); + printf("out CreateMd..."); + return instance; +} + +void NapiMd::DefineMdJSClass(napi_env env, napi_value exports) +{ + napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("createMd", CreateMd), + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); + napi_property_descriptor classDesc[] = { + DECLARE_NAPI_FUNCTION("update", NapiMdUpdate), + DECLARE_NAPI_FUNCTION("digest", NapiMdDoFinal), + DECLARE_NAPI_FUNCTION("getMdLength", NapiGetMdLength), + }; + napi_value constructor = nullptr; + napi_define_class(env, "Md", NAPI_AUTO_LENGTH, MdConstructor, nullptr, + sizeof(classDesc) / sizeof(classDesc[0]), classDesc, &constructor); + napi_create_reference(env, constructor, 1, &classRef_); +} + +} // CryptoFramework +} // OHOS \ No newline at end of file diff --git a/frameworks/js/napi/src/napi_pri_key.cpp b/frameworks/js/napi/src/napi_pri_key.cpp new file mode 100644 index 0000000..0d2e127 --- /dev/null +++ b/frameworks/js/napi/src/napi_pri_key.cpp @@ -0,0 +1,122 @@ +/* + * Copyright (C) 2022 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 "napi_pri_key.h" + +#include "securec.h" +#include "log.h" +#include "memory.h" + +#include "napi_crypto_framework_defines.h" +#include "napi_utils.h" + +namespace OHOS { +namespace CryptoFramework { + +thread_local napi_ref NapiPriKey::classRef_ = nullptr; + +NapiPriKey::NapiPriKey(HcfPriKey *priKey) +{ + this->priKey_ = priKey; +} + +NapiPriKey::~NapiPriKey() {} + +HcfPriKey *NapiPriKey::GetPriKey() +{ + return this->priKey_; +} + +napi_value NapiPriKey::PriKeyConstructor(napi_env env, napi_callback_info info) +{ + LOGI("enter ..."); + + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + + LOGI("out ..."); + return thisVar; +} + +napi_value NapiPriKey::ConvertToJsPriKey(napi_env env) +{ + LOGI("enter ..."); + + napi_value instance; + napi_value constructor = nullptr; + napi_get_reference_value(env, classRef_, &constructor); + napi_new_instance(env, constructor, 0, nullptr, &instance); + + const char *algName = this->priKey_->base.getAlgorithm(&(this->priKey_->base)); + const char *format = this->priKey_->base.getFormat(&(this->priKey_->base)); + + napi_value napiAlgName = nullptr; + napi_create_string_utf8(env, algName, NAPI_AUTO_LENGTH, &napiAlgName); + napi_set_named_property(env, instance, CRYPTO_TAG_ALG_NAME.c_str(), napiAlgName); + + napi_value napiFormat = nullptr; + napi_create_string_utf8(env, format, NAPI_AUTO_LENGTH, &napiFormat); + napi_set_named_property(env, instance, CRYPTO_TAG_FORMAT.c_str(), napiFormat); + + LOGI("out ..."); + return instance; +} + +napi_value NapiPriKey::JsGetEncoded(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiPriKey *napiPriKey = nullptr; + napi_unwrap(env, thisVar, (void **)(&napiPriKey)); + + HcfPriKey *priKey = napiPriKey->GetPriKey(); + + HcfBlob returnBlob; + HcfResult res = priKey->base.getEncoded(&priKey->base, &returnBlob); + if (res != HCF_SUCCESS) { + LOGE("c getEncoded fail."); + return nullptr; + } + + return ConvertBlobToNapiValue(env, &returnBlob); +} + +napi_value NapiPriKey::JsClearMem(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiPriKey *napiPriKey = nullptr; + napi_unwrap(env, thisVar, (void **)(&napiPriKey)); + + HcfPriKey *priKey = napiPriKey->GetPriKey(); + + priKey->clearMem(priKey); + return nullptr; +} + +void NapiPriKey::DefinePriKeyJSClass(napi_env env) +{ + napi_property_descriptor classDesc[] = { + DECLARE_NAPI_FUNCTION("getEncoded", NapiPriKey::JsGetEncoded), + DECLARE_NAPI_FUNCTION("clearMem", NapiPriKey::JsClearMem), + }; + napi_value constructor = nullptr; + napi_define_class(env, "PriKey", NAPI_AUTO_LENGTH, NapiPriKey::PriKeyConstructor, nullptr, + sizeof(classDesc) / sizeof(classDesc[0]), classDesc, &constructor); + napi_create_reference(env, constructor, 1, &classRef_); +} + +} // CryptoFramework +} // OHOS diff --git a/frameworks/js/napi/src/napi_pub_key.cpp b/frameworks/js/napi/src/napi_pub_key.cpp new file mode 100644 index 0000000..b7676c8 --- /dev/null +++ b/frameworks/js/napi/src/napi_pub_key.cpp @@ -0,0 +1,107 @@ +/* + * Copyright (C) 2022 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 "napi_pub_key.h" + +#include "securec.h" +#include "log.h" +#include "memory.h" +#include "napi_crypto_framework_defines.h" + +#include "napi_utils.h" + +namespace OHOS { +namespace CryptoFramework { + +thread_local napi_ref NapiPubKey::classRef_ = nullptr; + +NapiPubKey::NapiPubKey(HcfPubKey *pubKey) +{ + this->pubKey_ = pubKey; +} + +NapiPubKey::~NapiPubKey() {} + +HcfPubKey *NapiPubKey::GetPubKey() +{ + return this->pubKey_; +} + +napi_value NapiPubKey::PubKeyConstructor(napi_env env, napi_callback_info info) +{ + LOGI("enter ..."); + + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + + LOGI("out ..."); + return thisVar; +} + +napi_value NapiPubKey::ConvertToJsPubKey(napi_env env) +{ + LOGI("enter ..."); + + napi_value instance; + napi_value constructor = nullptr; + napi_get_reference_value(env, classRef_, &constructor); + napi_new_instance(env, constructor, 0, nullptr, &instance); + + const char *algName = this->pubKey_->base.getAlgorithm(&(this->pubKey_->base)); + const char *format = this->pubKey_->base.getFormat(&(this->pubKey_->base)); + + napi_value napiAlgName = nullptr; + napi_create_string_utf8(env, algName, NAPI_AUTO_LENGTH, &napiAlgName); + napi_set_named_property(env, instance, CRYPTO_TAG_ALG_NAME.c_str(), napiAlgName); + + napi_value napiFormat = nullptr; + napi_create_string_utf8(env, format, NAPI_AUTO_LENGTH, &napiFormat); + napi_set_named_property(env, instance, CRYPTO_TAG_FORMAT.c_str(), napiFormat); + + LOGI("out ..."); + return instance; +} + +napi_value NapiPubKey::JsGetEncoded(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiPubKey *napiPubKey = nullptr; + napi_unwrap(env, thisVar, (void **)(&napiPubKey)); + + HcfPubKey *pubKey = napiPubKey->GetPubKey(); + HcfBlob returnBlob; + HcfResult res = pubKey->base.getEncoded(&pubKey->base, &returnBlob); + if (res != HCF_SUCCESS) { + LOGE("c getEncoded fail."); + return nullptr; + } + + return ConvertBlobToNapiValue(env, &returnBlob); +} + +void NapiPubKey::DefinePubKeyJSClass(napi_env env) +{ + napi_property_descriptor classDesc[] = { + DECLARE_NAPI_FUNCTION("getEncoded", NapiPubKey::JsGetEncoded), + }; + napi_value constructor = nullptr; + napi_define_class(env, "PubKey", NAPI_AUTO_LENGTH, NapiPubKey::PubKeyConstructor, nullptr, + sizeof(classDesc) / sizeof(classDesc[0]), classDesc, &constructor); + napi_create_reference(env, constructor, 1, &classRef_); +} + +} // CryptoFramework +} // OHOS diff --git a/frameworks/js/napi/src/napi_rand.cpp b/frameworks/js/napi/src/napi_rand.cpp new file mode 100644 index 0000000..e45fdf4 --- /dev/null +++ b/frameworks/js/napi/src/napi_rand.cpp @@ -0,0 +1,365 @@ +/* + * Copyright (C) 2022 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 "napi_rand.h" + +#include "securec.h" +#include "log.h" +#include "memory.h" + +#include "napi_utils.h" +#include "napi_crypto_framework_defines.h" + +namespace OHOS { +namespace CryptoFramework { + +napi_ref NapiRand::classRef_ = nullptr; + +struct RandCtx { + napi_env env = nullptr; + + CfAsyncType asyncType = ASYNC_TYPE_CALLBACK; + napi_ref callback = nullptr; + napi_deferred deferred = nullptr; + napi_value promise = nullptr; + napi_async_work asyncWork = nullptr; + + NapiRand *randClass = nullptr; + uint32_t numBytes = 0; + HcfBlob *seedBlob = nullptr; + + HcfResult errCode = HCF_SUCCESS; + const char *errMsg = nullptr; + HcfBlob *randBlob = nullptr; +}; + +static void FreeCryptoFwkCtx(napi_env env, RandCtx *context) +{ + if (context == nullptr) { + return; + } + if (context->asyncWork != nullptr) { + napi_delete_async_work(env, context->asyncWork); + context->asyncWork = nullptr; + } + + if (context->callback != nullptr) { + napi_delete_reference(env, context->callback); + context->callback = nullptr; + } + if (context->seedBlob != nullptr) { + HcfFree(context->seedBlob->data); + context->seedBlob->data = nullptr; + context->seedBlob->len = 0; + } + if (context->randBlob != nullptr) { + HcfFree(context->randBlob->data); + context->randBlob->data = nullptr; + context->randBlob->len = 0; + } + HcfFree(context); +} + +static void ReturnCallbackResult(napi_env env, RandCtx *context, napi_value result) +{ + napi_value businessError = GenerateBusinessError(env, context->errCode, context->errMsg); + + napi_value params[ARGS_SIZE_TWO] = { businessError, result }; + + napi_value func = nullptr; + napi_get_reference_value(env, context->callback, &func); + + napi_value recv = nullptr; + napi_value callFuncRet = nullptr; + napi_get_undefined(env, &recv); + napi_call_function(env, recv, func, ARGS_SIZE_TWO, params, &callFuncRet); +} + +static void ReturnPromiseResult(napi_env env, RandCtx *context, napi_value result) +{ + if (context->errCode == HCF_SUCCESS) { + napi_resolve_deferred(env, context->deferred, result); + } else { + napi_reject_deferred(env, context->deferred, GenerateBusinessError(env, context->errCode, context->errMsg)); + } +} + +static bool CreateCallbackAndPromise(napi_env env, RandCtx *context, size_t argc, + size_t maxCount, napi_value callbackValue) +{ + context->asyncType = (argc == maxCount) ? ASYNC_TYPE_CALLBACK : ASYNC_TYPE_PROMISE; + if (context->asyncType == ASYNC_TYPE_CALLBACK) { + if (!GetCallbackFromJSParams(env, callbackValue, &context->callback)) { + LOGE("get callback failed!"); + return false; + } + } else { + napi_create_promise(env, &context->deferred, &context->promise); + } + return true; +} + +NapiRand::NapiRand(HcfRand *randObj) +{ + this->randObj_ = randObj; +} + +NapiRand::~NapiRand() +{ + OH_HCF_ObjDestroy(this->randObj_); +} + +static void GenerateRandomExecute(napi_env env, void *data) +{ + RandCtx *context = static_cast(data); + NapiRand *randClass = context->randClass; + HcfRand *randObj = randClass->GetRand(); + HcfBlob *randBlob = (HcfBlob *)HcfMalloc(sizeof(HcfBlob), 0); + if (randBlob == nullptr) { + LOGE("randBlob is null!"); + context->errCode = HCF_ERR_MALLOC; + context->errMsg = "malloc data blob failed"; + return; + } + uint32_t numBytes = context->numBytes; + context->errCode = randObj->generateRandom(randObj, numBytes, randBlob); + if (context->errCode != HCF_SUCCESS) { + LOGE("generateRandom failed!"); + context->errMsg = "generateRandom failed"; + return; + } + context->randBlob = randBlob; +} + +static void GenerateRandomComplete(napi_env env, napi_status status, void *data) +{ + RandCtx *context = static_cast(data); + napi_value returnRandBlob = ConvertBlobToNapiValue(env, context->randBlob); + if (returnRandBlob == nullptr) { + LOGE("returnOutBlob is nullptr!"); + returnRandBlob = NapiGetNull(env); + } + if (context->asyncType == ASYNC_TYPE_CALLBACK) { + ReturnCallbackResult(env, context, returnRandBlob); + } else { + ReturnPromiseResult(env, context, returnRandBlob); + } + FreeCryptoFwkCtx(env, context); +} + +static void SetSeedExecute(napi_env env, void *data) +{ + RandCtx *context = static_cast(data); + NapiRand *randClass = context->randClass; + HcfRand *randObj = randClass->GetRand(); + HcfBlob *seedBlob = static_cast(context->seedBlob); + context->errCode = randObj->setSeed(randObj, seedBlob); + if (context->errCode != HCF_SUCCESS) { + LOGE("setSeed failed!"); + context->errMsg = "setSeed failed"; + return; + } +} + +static void SetSeedComplete(napi_env env, napi_status status, void *data) +{ + LOGI("enter SetSeedComplete ..."); + RandCtx *context = static_cast(data); + napi_value nullInstance = nullptr; + napi_get_null(env, &nullInstance); + if (context->asyncType == ASYNC_TYPE_CALLBACK) { + ReturnCallbackResult(env, context, nullInstance); + } else { + ReturnPromiseResult(env, context, nullInstance); + } + FreeCryptoFwkCtx(env, context); +} + +napi_value NapiRand::GenerateRandom(napi_env env, napi_callback_info info) +{ + size_t expectedArgsCount = ARGS_SIZE_TWO; + size_t argc = expectedArgsCount; + napi_value argv[ARGS_SIZE_TWO] = { 0 }; + napi_value thisVar = nullptr; + napi_value ret = NapiGetNull(env); + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + if ((argc != expectedArgsCount) && (argc != expectedArgsCount - CALLBACK_SIZE)) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "invalid params count")); + LOGE("The arguments count is not expected!"); + return ret; + } + RandCtx *context = (RandCtx *)HcfMalloc(sizeof(RandCtx), 0); + if (context == nullptr) { + napi_throw(env, GenerateBusinessError(env, HCF_ERR_MALLOC, "malloc context failed")); + LOGE("malloc context failed!"); + return ret; + } + context->randClass = this; + if (!GetUint32FromJSParams(env, argv[PARAM0], context->numBytes)) { + LOGE("get numBytes failed!"); + FreeCryptoFwkCtx(env, context); + return ret; + } + if (!CreateCallbackAndPromise(env, context, argc, ARGS_SIZE_TWO, argv[PARAM1])) { + FreeCryptoFwkCtx(env, context); + return nullptr; + } + napi_create_async_work( + env, nullptr, GetResourceName(env, "GenerateRandom"), + GenerateRandomExecute, + GenerateRandomComplete, + (void *)context, + &context->asyncWork); + napi_queue_async_work(env, context->asyncWork); + if (context->asyncType == ASYNC_TYPE_PROMISE) { + return context->promise; + } else { + return NapiGetNull(env); + } +} + +napi_value NapiRand::SetSeed(napi_env env, napi_callback_info info) +{ + size_t expectedArgsCount = ARGS_SIZE_TWO; + size_t argc = expectedArgsCount; + napi_value argv[ARGS_SIZE_TWO] = { 0 }; + napi_value thisVar = nullptr; + napi_value ret = NapiGetNull(env); + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + if ((argc != expectedArgsCount) && (argc != expectedArgsCount - CALLBACK_SIZE)) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "invalid params count")); + LOGE("The arguments count is not expected!"); + return ret; + } + RandCtx *context = (RandCtx *)HcfMalloc(sizeof(RandCtx), 0); + if (context == nullptr) { + napi_throw(env, GenerateBusinessError(env, HCF_ERR_MALLOC, "malloc context failed")); + LOGE("malloc context failed!"); + return ret; + } + context->randClass = this; + context->randBlob = GetBlobFromNapiValue(env, argv[PARAM0]); + if (context->randBlob == nullptr) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "randBlob is null")); + LOGE("randBlob is null!"); + return ret; + } + if (!CreateCallbackAndPromise(env, context, argc, ARGS_SIZE_TWO, argv[PARAM1])) { + FreeCryptoFwkCtx(env, context); + return nullptr; + } + napi_create_async_work( + env, nullptr, GetResourceName(env, "SetSeed"), + SetSeedExecute, + SetSeedComplete, + (void *)context, + &context->asyncWork); + napi_queue_async_work(env, context->asyncWork); + if (context->asyncType == ASYNC_TYPE_PROMISE) { + return context->promise; + } else { + return NapiGetNull(env); + } +} + +static napi_value NapiGenerateRandom(napi_env env, napi_callback_info info) +{ + LOGI("enter NapiCreateRand ..."); + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiRand *randObj = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&randObj)); + if (randObj == nullptr) { + LOGE("randObj is nullptr!"); + return NapiGetNull(env); + } + return randObj->GenerateRandom(env, info); +} + +static napi_value NapiSetSeed(napi_env env, napi_callback_info info) +{ + LOGI("enter NapiSetSeed ..."); + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiRand *randObj = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&randObj)); + if (randObj == nullptr) { + LOGE("randObj is nullptr!"); + return NapiGetNull(env); + } + return randObj->SetSeed(env, info); +} + +napi_value NapiRand::RandConstructor(napi_env env, napi_callback_info info) +{ + printf("enter RandConstructor..."); + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + HcfRand *randObj = nullptr; + HcfResult res = HcfRandCreate(&randObj); + if (res != HCF_SUCCESS) { + LOGE("create c rand fail."); + return NapiGetNull(env); + } + NapiRand *randNapiObj = new NapiRand(randObj); + napi_wrap( + env, thisVar, randNapiObj, + [](napi_env env, void *data, void *hint) { + NapiRand *rand = (NapiRand *)(data); + delete rand; + return; + }, + nullptr, + nullptr); + printf("out RandConstructor..."); + return thisVar; +} + +napi_value NapiRand::CreateRand(napi_env env, napi_callback_info info) +{ + printf("enter CreateRand..."); + size_t exceptedArgc = ARGS_SIZE_ZERO; + size_t argc; + napi_get_cb_info(env, info, &argc, nullptr, nullptr, nullptr); + if (argc != exceptedArgc) { + LOGE("The input args num is invalid."); + return NapiGetNull(env); + } + napi_value instance; + napi_value constructor = nullptr; + napi_get_reference_value(env, classRef_, &constructor); + napi_new_instance(env, constructor, ARGS_SIZE_ZERO, nullptr, &instance); + printf("out CreateRand..."); + return instance; +} + +void NapiRand::DefineRandJSClass(napi_env env, napi_value exports) +{ + napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("createRandom", CreateRand), + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); + napi_property_descriptor classDesc[] = { + DECLARE_NAPI_FUNCTION("generateRandom", NapiGenerateRandom), + DECLARE_NAPI_FUNCTION("setSeed", NapiSetSeed), + }; + napi_value constructor = nullptr; + napi_define_class(env, "Random", NAPI_AUTO_LENGTH, RandConstructor, nullptr, + sizeof(classDesc) / sizeof(classDesc[0]), classDesc, &constructor); + napi_create_reference(env, constructor, 1, &classRef_); +} + +} // CryptoFramework +} // OHOS diff --git a/frameworks/js/napi/src/napi_sign.cpp b/frameworks/js/napi/src/napi_sign.cpp new file mode 100644 index 0000000..132b458 --- /dev/null +++ b/frameworks/js/napi/src/napi_sign.cpp @@ -0,0 +1,662 @@ +/* + * Copyright (C) 2022 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 "napi_sign.h" + +#include "securec.h" +#include "log.h" +#include "memory.h" + +#include "napi_crypto_framework_defines.h" +#include "napi_pri_key.h" +#include "napi_pub_key.h" +#include "napi_utils.h" + +namespace OHOS { +namespace CryptoFramework { + +struct SignInitCtx { + napi_env env = nullptr; + + AsyncType asyncType = ASYNC_CALLBACK; + napi_ref callback = nullptr; + napi_deferred deferred = nullptr; + napi_value promise = nullptr; + napi_async_work asyncWork = nullptr; + + HcfSign *sign; + HcfParamsSpec *params; + HcfPriKey *priKey; + + HcfResult result; +}; + +struct SignUpdateCtx { + napi_env env = nullptr; + + AsyncType asyncType = ASYNC_CALLBACK; + napi_ref callback = nullptr; + napi_deferred deferred = nullptr; + napi_value promise = nullptr; + napi_async_work asyncWork = nullptr; + + HcfSign *sign; + HcfBlob *data; + + HcfResult result; +}; + +struct SignDoFinalCtx { + napi_env env = nullptr; + + AsyncType asyncType = ASYNC_CALLBACK; + napi_ref callback = nullptr; + napi_deferred deferred = nullptr; + napi_value promise = nullptr; + napi_async_work asyncWork = nullptr; + + HcfSign *sign; + HcfBlob *data; + + HcfResult result; + HcfBlob returnSignatureData; +}; + +thread_local napi_ref NapiSign::classRef_ = nullptr; + +static void FreeSignInitCtx(napi_env env, SignInitCtx *ctx) +{ + if (ctx == nullptr) { + return; + } + + if (ctx->asyncWork != nullptr) { + napi_delete_async_work(env, ctx->asyncWork); + } + + if (ctx->callback != nullptr) { + napi_delete_reference(env, ctx->callback); + } + + HcfFree(ctx); +} + +static void FreeSignUpdateCtx(napi_env env, SignUpdateCtx *ctx) +{ + if (ctx == nullptr) { + return; + } + + if (ctx->asyncWork != nullptr) { + napi_delete_async_work(env, ctx->asyncWork); + } + + if (ctx->callback != nullptr) { + napi_delete_reference(env, ctx->callback); + } + + HcfBlobDataFree(ctx->data); + HcfFree(ctx->data); + HcfFree(ctx); +} + +static void FreeSignDoFinalCtx(napi_env env, SignDoFinalCtx *ctx) +{ + if (ctx == nullptr) { + return; + } + + if (ctx->asyncWork != nullptr) { + napi_delete_async_work(env, ctx->asyncWork); + ctx->asyncWork = nullptr; + } + + if (ctx->callback != nullptr) { + napi_delete_reference(env, ctx->callback); + ctx->callback = nullptr; + } + + if (ctx->returnSignatureData.data != nullptr) { + HcfFree(ctx->returnSignatureData.data); + ctx->returnSignatureData.data = nullptr; + ctx->returnSignatureData.len = 0; + } + + HcfBlobDataFree(ctx->data); + HcfFree(ctx->data); + HcfFree(ctx); +} + +static bool BuildSignJsInitCtx(napi_env env, napi_callback_info info, SignInitCtx *ctx) +{ + napi_value thisVar = nullptr; + size_t expectedArgc = PARAMS_NUM_TWO; + size_t argc; + napi_value argv[PARAMS_NUM_TWO] = { nullptr, 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); + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "params num error.")); + return false; + } + ctx->asyncType = (argc == expectedArgc) ? ASYNC_CALLBACK : ASYNC_PROMISE; + + NapiSign *napiSign = NULL; + napi_status status = napi_unwrap(env, thisVar, (void **)(&napiSign)); + if (status != napi_ok) { + LOGE("failed to unwrap napi sign obj."); + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "[Self]: param unwarp error.")); + return false; + } + + size_t index = 0; + NapiPriKey *napiPriKey = NULL; + status = napi_unwrap(env, argv[index], (void **)(&napiPriKey)); + if (status != napi_ok) { + LOGE("failed to unwrap napi priKey obj."); + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "[PriKey]: param unwarp error.")); + return false; + } + + ctx->sign = napiSign->GetSign(); + ctx->params = nullptr; + ctx->priKey = napiPriKey->GetPriKey(); + + if (ctx->asyncType == ASYNC_PROMISE) { + napi_create_promise(env, &ctx->deferred, &ctx->promise); + return true; + } else { + return GetCallbackFromJSParams(env, argv[expectedArgc - 1], &ctx->callback); + } +} + +static bool BuildSignJsUpdateCtx(napi_env env, napi_callback_info info, SignUpdateCtx *ctx) +{ + napi_value thisVar = nullptr; + size_t expectedArgc = PARAMS_NUM_TWO; + size_t argc; + napi_value argv[PARAMS_NUM_TWO] = { nullptr, 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); + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "params num error.")); + return false; + } + ctx->asyncType = (argc == PARAMS_NUM_TWO) ? ASYNC_CALLBACK : ASYNC_PROMISE; + + NapiSign *napiSign = NULL; + napi_status status = napi_unwrap(env, thisVar, (void **)(&napiSign)); + if (status != napi_ok) { + LOGE("failed to unwrap napi sign obj."); + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "[Self]: param unwarp error.")); + return false; + } + + size_t index = 0; + HcfBlob *blob = GetBlobFromNapiValue(env, argv[index]); + if (blob == nullptr) { + LOGE("failed to get data."); + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "[Data]: must be of the DataBlob type.")); + return false; + } + + ctx->sign = napiSign->GetSign(); + ctx->data = blob; + + if (ctx->asyncType == ASYNC_PROMISE) { + napi_create_promise(env, &ctx->deferred, &ctx->promise); + return true; + } else { + return GetCallbackFromJSParams(env, argv[expectedArgc - 1], &ctx->callback); + } +} + +static bool BuildSignJsDoFinalCtx(napi_env env, napi_callback_info info, SignDoFinalCtx *ctx) +{ + napi_value thisVar = nullptr; + size_t expectedArgc = PARAMS_NUM_TWO; + size_t argc; + napi_value argv[PARAMS_NUM_TWO] = { nullptr, 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); + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "params num error.")); + return false; + } + ctx->asyncType = (argc == PARAMS_NUM_TWO) ? ASYNC_CALLBACK : ASYNC_PROMISE; + + NapiSign *napiSign = nullptr; + napi_status status = napi_unwrap(env, thisVar, (void **)(&napiSign)); + if (status != napi_ok) { + LOGE("failed to unwrap napi sign obj."); + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "[Self]: param unwarp error.")); + return false; + } + + size_t index = 0; + napi_valuetype valueType; + napi_typeof(env, argv[index], &valueType); + HcfBlob *data = nullptr; + if (valueType != napi_null) { + data = GetBlobFromNapiValue(env, argv[index]); + if (data == nullptr) { + LOGE("failed to get data."); + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "[Data]: must be of the DataBlob type.")); + return false; + } + } + + ctx->sign = napiSign->GetSign(); + ctx->data = data; + + if (ctx->asyncType == ASYNC_PROMISE) { + napi_create_promise(env, &ctx->deferred, &ctx->promise); + return true; + } else { + return GetCallbackFromJSParams(env, argv[expectedArgc - 1], &ctx->callback); + } +} + +static void ReturnInitCallbackResult(napi_env env, SignInitCtx *ctx, napi_value result) +{ + napi_value businessError = nullptr; + if (ctx->result != HCF_SUCCESS) { + businessError = GenerateBusinessError(env, ctx->result, COMMON_ERR_MSG.c_str()); + } + + napi_value params[ARGS_SIZE_ONE] = { businessError }; + + napi_value func = nullptr; + napi_get_reference_value(env, ctx->callback, &func); + + napi_value recv = nullptr; + napi_value callFuncRet = nullptr; + napi_get_undefined(env, &recv); + napi_call_function(env, recv, func, ARGS_SIZE_ONE, params, &callFuncRet); +} + +static void ReturnInitPromiseResult(napi_env env, SignInitCtx *ctx, napi_value result) +{ + if (ctx->result == HCF_SUCCESS) { + napi_resolve_deferred(env, ctx->deferred, result); + } else { + napi_reject_deferred(env, ctx->deferred, GenerateBusinessError(env, ctx->result, COMMON_ERR_MSG.c_str())); + } +} + +static void ReturnUpdateCallbackResult(napi_env env, SignUpdateCtx *ctx, napi_value result) +{ + napi_value businessError = nullptr; + if (ctx->result != HCF_SUCCESS) { + businessError = GenerateBusinessError(env, ctx->result, COMMON_ERR_MSG.c_str()); + } + + napi_value params[ARGS_SIZE_ONE] = { businessError }; + + napi_value func = nullptr; + napi_get_reference_value(env, ctx->callback, &func); + + napi_value recv = nullptr; + napi_value callFuncRet = nullptr; + napi_get_undefined(env, &recv); + napi_call_function(env, recv, func, ARGS_SIZE_ONE, params, &callFuncRet); +} + +static void ReturnUpdatePromiseResult(napi_env env, SignUpdateCtx *ctx, napi_value result) +{ + if (ctx->result == HCF_SUCCESS) { + napi_resolve_deferred(env, ctx->deferred, result); + } else { + napi_reject_deferred(env, ctx->deferred, GenerateBusinessError(env, ctx->result, COMMON_ERR_MSG.c_str())); + } +} + +static void ReturnDoFinalCallbackResult(napi_env env, SignDoFinalCtx *ctx, napi_value result) +{ + napi_value businessError = nullptr; + if (ctx->result != HCF_SUCCESS) { + businessError = GenerateBusinessError(env, ctx->result, COMMON_ERR_MSG.c_str()); + } + + napi_value params[ARGS_SIZE_TWO] = { businessError, result }; + + napi_value func = nullptr; + napi_get_reference_value(env, ctx->callback, &func); + + napi_value recv = nullptr; + napi_value callFuncRet = nullptr; + napi_get_undefined(env, &recv); + napi_call_function(env, recv, func, ARGS_SIZE_TWO, params, &callFuncRet); +} + +static void ReturnDoFinalPromiseResult(napi_env env, SignDoFinalCtx *ctx, napi_value result) +{ + if (ctx->result == HCF_SUCCESS) { + napi_resolve_deferred(env, ctx->deferred, result); + } else { + napi_reject_deferred(env, ctx->deferred, GenerateBusinessError(env, ctx->result, COMMON_ERR_MSG.c_str())); + } +} + +void SignJsInitAsyncWorkProcess(napi_env env, void *data) +{ + SignInitCtx *ctx = static_cast(data); + + HcfResult res = ctx->sign->init(ctx->sign, ctx->params, ctx->priKey); + + ctx->result = res; + if (res != HCF_SUCCESS) { + LOGE("sign init fail."); + } +} + +void SignJsInitAsyncWorkReturn(napi_env env, napi_status status, void *data) +{ + SignInitCtx *ctx = static_cast(data); + + if (ctx->asyncType == ASYNC_CALLBACK) { + ReturnInitCallbackResult(env, ctx, NapiGetNull(env)); + } else { + ReturnInitPromiseResult(env, ctx, NapiGetNull(env)); + } + FreeSignInitCtx(env, ctx); +} + +void SignJsUpdateAsyncWorkProcess(napi_env env, void *data) +{ + SignUpdateCtx *ctx = static_cast(data); + + HcfResult res = ctx->sign->update(ctx->sign, ctx->data); + + ctx->result = res; + if (res != HCF_SUCCESS) { + LOGE("sign update fail."); + } +} + +void SignJsUpdateAsyncWorkReturn(napi_env env, napi_status status, void *data) +{ + SignUpdateCtx *ctx = static_cast(data); + + if (ctx->asyncType == ASYNC_CALLBACK) { + ReturnUpdateCallbackResult(env, ctx, NapiGetNull(env)); + } else { + ReturnUpdatePromiseResult(env, ctx, NapiGetNull(env)); + } + FreeSignUpdateCtx(env, ctx); +} + +void SignJsDoFinalAsyncWorkProcess(napi_env env, void *data) +{ + SignDoFinalCtx *ctx = static_cast(data); + + HcfResult res = ctx->sign->sign(ctx->sign, ctx->data, &ctx->returnSignatureData); + + ctx->result = res; + if (res != HCF_SUCCESS) { + LOGE("sign doFinal fail."); + } +} + +void SignJsDoFinalAsyncWorkReturn(napi_env env, napi_status status, void *data) +{ + SignDoFinalCtx *ctx = static_cast(data); + + napi_value dataBlob = nullptr; + if (ctx->result == HCF_SUCCESS) { + dataBlob = ConvertBlobToNapiValue(env, &ctx->returnSignatureData); + } + + if (ctx->asyncType == ASYNC_CALLBACK) { + ReturnDoFinalCallbackResult(env, ctx, dataBlob); + } else { + ReturnDoFinalPromiseResult(env, ctx, dataBlob); + } + FreeSignDoFinalCtx(env, ctx); +} + +static napi_value NewSignJsInitAsyncWork(napi_env env, SignInitCtx *ctx) +{ + napi_value resourceName = nullptr; + napi_create_string_utf8(env, "init", NAPI_AUTO_LENGTH, &resourceName); + + napi_create_async_work( + env, nullptr, resourceName, + [](napi_env env, void *data) { + SignJsInitAsyncWorkProcess(env, data); + return; + }, + [](napi_env env, napi_status status, void *data) { + SignJsInitAsyncWorkReturn(env, status, data); + return; + }, + (void *)ctx, + &ctx->asyncWork); + + napi_queue_async_work(env, ctx->asyncWork); + if (ctx->asyncType == ASYNC_PROMISE) { + return ctx->promise; + } else { + napi_value result = nullptr; + napi_get_null(env, &result); + return result; + } +} + +static napi_value NewSignJsUpdateAsyncWork(napi_env env, SignUpdateCtx *ctx) +{ + napi_value resourceName = nullptr; + napi_create_string_utf8(env, "update", NAPI_AUTO_LENGTH, &resourceName); + + napi_create_async_work( + env, nullptr, resourceName, + [](napi_env env, void *data) { + SignJsUpdateAsyncWorkProcess(env, data); + return; + }, + [](napi_env env, napi_status status, void *data) { + SignJsUpdateAsyncWorkReturn(env, status, data); + return; + }, + (void *)ctx, + &ctx->asyncWork); + + napi_queue_async_work(env, ctx->asyncWork); + if (ctx->asyncType == ASYNC_PROMISE) { + return ctx->promise; + } else { + napi_value result = nullptr; + napi_get_null(env, &result); + return result; + } +} + +static napi_value NewSignJsDoFinalAsyncWork(napi_env env, SignDoFinalCtx *ctx) +{ + napi_value resourceName = nullptr; + napi_create_string_utf8(env, "sign", NAPI_AUTO_LENGTH, &resourceName); + + napi_create_async_work( + env, nullptr, resourceName, + [](napi_env env, void *data) { + SignJsDoFinalAsyncWorkProcess(env, data); + return; + }, + [](napi_env env, napi_status status, void *data) { + SignJsDoFinalAsyncWorkReturn(env, status, data); + return; + }, + (void *)ctx, + &ctx->asyncWork); + + napi_queue_async_work(env, ctx->asyncWork); + if (ctx->asyncType == ASYNC_PROMISE) { + return ctx->promise; + } else { + napi_value result = nullptr; + napi_get_null(env, &result); + return result; + } +} + +NapiSign::NapiSign(HcfSign *sign) +{ + this->sign_ = sign; +} + +NapiSign::~NapiSign() +{ + OH_HCF_ObjDestroy(this->sign_); +} + +HcfSign *NapiSign::GetSign() +{ + return this->sign_; +} + +napi_value NapiSign::JsInit(napi_env env, napi_callback_info info) +{ + LOGI("enter ..."); + SignInitCtx *ctx = (SignInitCtx *)HcfMalloc(sizeof(SignInitCtx), 0); + if (ctx == NULL) { + LOGE("create context fail."); + return NULL; + } + + if (!BuildSignJsInitCtx(env, info, ctx)) { + LOGE("build context fail."); + FreeSignInitCtx(env, ctx); + return nullptr; + } + + return NewSignJsInitAsyncWork(env, ctx); +} + +napi_value NapiSign::JsUpdate(napi_env env, napi_callback_info info) +{ + LOGI("enter ..."); + SignUpdateCtx *ctx = (SignUpdateCtx *)HcfMalloc(sizeof(SignUpdateCtx), 0); + if (ctx == NULL) { + LOGE("create context fail."); + return NULL; + } + + if (!BuildSignJsUpdateCtx(env, info, ctx)) { + LOGE("build context fail."); + FreeSignUpdateCtx(env, ctx); + return nullptr; + } + + return NewSignJsUpdateAsyncWork(env, ctx); +} + +napi_value NapiSign::JsSign(napi_env env, napi_callback_info info) +{ + LOGI("enter ..."); + SignDoFinalCtx *ctx = (SignDoFinalCtx *)HcfMalloc(sizeof(SignDoFinalCtx), 0); + if (ctx == NULL) { + LOGE("create context fail."); + return NULL; + } + + if (!BuildSignJsDoFinalCtx(env, info, ctx)) { + LOGE("build context fail."); + FreeSignDoFinalCtx(env, ctx); + return nullptr; + } + + return NewSignJsDoFinalAsyncWork(env, ctx); +} + +napi_value NapiSign::SignConstructor(napi_env env, napi_callback_info info) +{ + LOGI("enter ..."); + + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + + LOGI("out ..."); + return thisVar; +} + +napi_value NapiSign::CreateJsSign(napi_env env, napi_callback_info info) +{ + LOGI("enter ..."); + size_t exceptedArgc = PARAMS_NUM_ONE; + size_t argc; + napi_value argv[PARAMS_NUM_ONE] = { nullptr }; + napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); + + if (argc != exceptedArgc) { + LOGE("The input args num is invalid."); + return nullptr; + } + + napi_value instance; + napi_value constructor = nullptr; + napi_get_reference_value(env, classRef_, &constructor); + napi_new_instance(env, constructor, argc, argv, &instance); + + std::string algName; + if (!GetStringFromJSParams(env, argv[0], algName)) { + return nullptr; + } + + HcfSign *sign = NULL; + int32_t res = HcfSignCreate(algName.c_str(), &sign); + if (res != HCF_SUCCESS) { + LOGE("create c sign fail."); + return nullptr; + } + + NapiSign *napiSign = new NapiSign(sign); + + napi_wrap( + env, instance, napiSign, + [](napi_env env, void *data, void *hint) { + NapiSign *napiSign = (NapiSign *)(data); + delete napiSign; + return; + }, + nullptr, + nullptr); + + napi_value napiAlgName = nullptr; + napi_create_string_utf8(env, algName.c_str(), NAPI_AUTO_LENGTH, &napiAlgName); + napi_set_named_property(env, instance, CRYPTO_TAG_ALG_NAME.c_str(), napiAlgName); + + LOGI("out ..."); + return instance; +} + +void NapiSign::DefineSignJSClass(napi_env env, napi_value exports) +{ + napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("createSign", NapiSign::CreateJsSign), + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); + + napi_property_descriptor classDesc[] = { + DECLARE_NAPI_FUNCTION("init", NapiSign::JsInit), + DECLARE_NAPI_FUNCTION("update", NapiSign::JsUpdate), + DECLARE_NAPI_FUNCTION("sign", NapiSign::JsSign), + }; + napi_value constructor = nullptr; + napi_define_class(env, "Sign", NAPI_AUTO_LENGTH, NapiSign::SignConstructor, nullptr, + sizeof(classDesc) / sizeof(classDesc[0]), classDesc, &constructor); + napi_create_reference(env, constructor, 1, &classRef_); +} +} // CryptoFramework +} // OHOS diff --git a/frameworks/js/napi/src/napi_sym_key.cpp b/frameworks/js/napi/src/napi_sym_key.cpp new file mode 100644 index 0000000..d3a137c --- /dev/null +++ b/frameworks/js/napi/src/napi_sym_key.cpp @@ -0,0 +1,126 @@ +/* + * Copyright (C) 2022 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 "napi_sym_key.h" + +#include "securec.h" +#include "log.h" +#include "memory.h" + +#include "napi_utils.h" +#include "napi_crypto_framework_defines.h" + +namespace OHOS { +namespace CryptoFramework { + +thread_local napi_ref NapiSymKey::classRef_ = nullptr; + +NapiSymKey::NapiSymKey(HcfSymKey *symKey) +{ + this->symKey_ = symKey; +} + +NapiSymKey::~NapiSymKey() +{ + OH_HCF_ObjDestroy(this->symKey_); +} + +HcfSymKey *NapiSymKey::GetSymKey() +{ + return this->symKey_; +} + +napi_value NapiSymKey::JsGetAlgorithm(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + NapiSymKey *napiSymKey = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); + + NAPI_CALL(env, napi_unwrap(env, thisVar, (void **)&napiSymKey)); + HcfSymKey *key = napiSymKey->GetSymKey(); + + const char *algo = key->key.getAlgorithm((HcfKey *)key); + napi_value instance = nullptr; + napi_create_string_utf8(env, (const char *)algo, NAPI_AUTO_LENGTH, &instance); + return instance; +} + +napi_value NapiSymKey::JsGetFormat(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + NapiSymKey *napiSymKey = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); + + NAPI_CALL(env, napi_unwrap(env, thisVar, (void **)&napiSymKey)); + HcfSymKey *key = napiSymKey->GetSymKey(); + + const char *format = key->key.getFormat((HcfKey *)key); + napi_value instance = nullptr; + napi_create_string_utf8(env, (const char *)format, NAPI_AUTO_LENGTH, &instance); + return instance; +} + +napi_value NapiSymKey::JsGetEncoded(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + NapiSymKey *napiSymKey = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); + + NAPI_CALL(env, napi_unwrap(env, thisVar, (void **)&napiSymKey)); + HcfSymKey *key = napiSymKey->GetSymKey(); + + HcfBlob blob = {0}; + HcfResult res = key->key.getEncoded((HcfKey *)key, &blob); + if (res != 0) { + napi_throw(env, GenerateBusinessError(env, res, "getEncoded failed.")); + LOGE("getEncoded failed!"); + return nullptr; + } + napi_value instance = ConvertBlobToNapiValue(env, &blob); + HcfFree(blob.data); + return instance; +} + +napi_value NapiSymKey::SymKeyConstructor(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); + return thisVar; +} + +napi_value NapiSymKey::CreateSymKey(napi_env env) +{ + napi_value instance = nullptr; + napi_value constructor = nullptr; + NAPI_CALL(env, napi_get_reference_value(env, classRef_, &constructor)); + NAPI_CALL(env, napi_new_instance(env, constructor, 0, nullptr, &instance)); + return instance; +} + +void NapiSymKey::DefineSymKeyJSClass(napi_env env) +{ + napi_property_descriptor classDesc[] = { + DECLARE_NAPI_FUNCTION("getEncoded", NapiSymKey::JsGetEncoded), + {.utf8name = "format", .getter = NapiSymKey::JsGetFormat}, + {.utf8name = "algName", .getter = NapiSymKey::JsGetAlgorithm}, + }; + napi_value constructor = nullptr; + napi_define_class(env, "SymKey", NAPI_AUTO_LENGTH, SymKeyConstructor, nullptr, + sizeof(classDesc) / sizeof(classDesc[0]), classDesc, &constructor); + napi_create_reference(env, constructor, 1, &classRef_); +} + +} // CryptoFramework +} // OHOS diff --git a/frameworks/js/napi/src/napi_sym_key_generator.cpp b/frameworks/js/napi/src/napi_sym_key_generator.cpp new file mode 100644 index 0000000..461cb94 --- /dev/null +++ b/frameworks/js/napi/src/napi_sym_key_generator.cpp @@ -0,0 +1,455 @@ +/* + * Copyright (C) 2022 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 "napi_sym_key_generator.h" + +#include "securec.h" +#include "log.h" +#include "memory.h" +#include "napi_key.h" +#include "napi_utils.h" +#include "napi_crypto_framework_defines.h" + +namespace OHOS { +namespace CryptoFramework { + +thread_local napi_ref NapiSymKeyGenerator::classRef_ = nullptr; + +struct SymKeyGeneratorFwkCtxT { + napi_env env = nullptr; + AsyncType asyncType = ASYNC_CALLBACK; + napi_ref callback = nullptr; + napi_deferred deferred = nullptr; + napi_value promise = nullptr; + napi_async_work asyncWork = nullptr; + + int32_t errCode = 0; + HcfSymKey *returnSymKey = nullptr; + const char *errMsg = nullptr; + + HcfSymKeyGenerator *generator = nullptr; + HcfBlob keyMaterial = { 0 }; +}; + +using SymKeyGeneratorFwkCtx = SymKeyGeneratorFwkCtxT *; + +static void FreeSymKeyGeneratorFwkCtx(napi_env env, SymKeyGeneratorFwkCtx &context) +{ + if (context == nullptr) { + return; + } + + if (context->asyncWork != nullptr) { + napi_delete_async_work(env, context->asyncWork); + context->asyncWork = nullptr; + } + + if (context->callback != nullptr) { + napi_delete_reference(env, context->callback); + context->callback = nullptr; + } + + if (context->keyMaterial.data != nullptr) { + (void)memset_s(context->keyMaterial.data, context->keyMaterial.len, 0, context->keyMaterial.len); + HcfFree(context->keyMaterial.data); + context->keyMaterial.data = nullptr; + context->keyMaterial.len = 0; + } + context->errMsg = nullptr; + + HcfFree(context); + context = nullptr; +} + +static bool BuildContextForGenerateKey(napi_env env, napi_callback_info info, SymKeyGeneratorFwkCtx context) +{ + napi_value thisVar = nullptr; + size_t expectedArgc = ARGS_SIZE_ONE; + size_t argc = ARGS_SIZE_ONE; + napi_value argv[ARGS_SIZE_ONE] = { nullptr }; + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + if (argc != expectedArgc && argc != expectedArgc - 1) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "generate key failed for wrong argument num.")); + LOGE("wrong argument num. require 0 or 1 arguments. [Argc]: %zu!", argc); + return false; + } + context->asyncType = (argc == expectedArgc) ? ASYNC_CALLBACK : ASYNC_PROMISE; + NapiSymKeyGenerator *napiGenerator; + napi_status status = napi_unwrap(env, thisVar, (void **)(&napiGenerator)); + if (status != napi_ok) { + LOGE("failed to unwrap NapiSymKeyGenerator obj!"); + return false; + } + + context->generator = napiGenerator->GetSymKeyGenerator(); + if (context->generator == nullptr) { + LOGE("failed to get generator obj!"); + return false; + } + + size_t index = 0; + if (context->asyncType == ASYNC_PROMISE) { + napi_create_promise(env, &context->deferred, &context->promise); + return true; + } else { + return GetCallbackFromJSParams(env, argv[index], &context->callback); + } +} + +static bool BuildContextForConvertKey(napi_env env, napi_callback_info info, SymKeyGeneratorFwkCtx context) +{ + napi_value thisVar = nullptr; + size_t expectedArgc = ARGS_SIZE_TWO; + size_t argc = ARGS_SIZE_TWO; + napi_value argv[ARGS_SIZE_TWO] = { nullptr }; + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + if (argc != expectedArgc && argc != expectedArgc - 1) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "convert key failed for wrong argument num.")); + LOGE("wrong argument num. require 1 or 2 arguments. [Argc]: %zu!", argc); + return false; + } + context->asyncType = (argc == expectedArgc) ? ASYNC_CALLBACK : ASYNC_PROMISE; + + NapiSymKeyGenerator *napiGenerator; + napi_status status = napi_unwrap(env, thisVar, (void **)(&napiGenerator)); + if (status != napi_ok) { + LOGE("failed to unwrap NapiSymKeyGenerator obj!"); + return false; + } + + context->generator = napiGenerator->GetSymKeyGenerator(); + if (context->generator == nullptr) { + LOGE("failed to get generator obj!"); + return false; + } + + size_t index = 0; + HcfBlob *blob = GetBlobFromNapiValue(env, argv[index++]); + if (blob == nullptr) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "convert key failed for invalid input blob.")); + LOGE("get keyMaterial failed!"); + return false; + } + context->keyMaterial = *blob; + HcfFree(blob); + if (context->asyncType == ASYNC_PROMISE) { + napi_create_promise(env, &context->deferred, &context->promise); + return true; + } else { + return GetCallbackFromJSParams(env, argv[index], &context->callback); + } +} + +static void ReturnPromiseResult(napi_env env, SymKeyGeneratorFwkCtx context, napi_value result) +{ + if (context->errCode == HCF_SUCCESS) { + napi_resolve_deferred(env, context->deferred, result); + } else { + napi_reject_deferred(env, context->deferred, GenerateBusinessError(env, context->errCode, context->errMsg)); + } +} + +static void ReturnCallbackResult(napi_env env, SymKeyGeneratorFwkCtx context, napi_value result) +{ + napi_value businessError = NapiGetNull(env); + if (context->errCode != HCF_SUCCESS) { + businessError = GenerateBusinessError(env, context->errCode, context->errMsg); + } + napi_value params[ARGS_SIZE_TWO] = { businessError, result }; + + napi_value func = nullptr; + napi_get_reference_value(env, context->callback, &func); + + napi_value recv = nullptr; + napi_value callFuncRet = nullptr; + napi_get_undefined(env, &recv); + napi_call_function(env, recv, func, ARGS_SIZE_TWO, params, &callFuncRet); +} + +static void AsyncGenKeyProcess(napi_env env, void *data) +{ + SymKeyGeneratorFwkCtx context = static_cast(data); + HcfSymKeyGenerator *generator = context->generator; + + HcfSymKey *key = NULL; + HcfResult res = generator->generateSymKey(generator, &key); + if (res != HCF_SUCCESS) { + LOGE("generate sym key failed."); + context->errCode = res; + context->errMsg = "generate sym key failed."; + return; + } + + context->errCode = HCF_SUCCESS; + context->returnSymKey = key; +} + +static void AsyncKeyReturn(napi_env env, napi_status status, void *data) +{ + napi_value instance = NapiKey::CreateHcfKey(env); + SymKeyGeneratorFwkCtx context = static_cast(data); + NapiKey *napiKey = new NapiKey((HcfKey *)context->returnSymKey); + + napi_status ret = napi_wrap(env, instance, napiKey, + [](napi_env env, void *data, void *hint) { + NapiKey *napiKey = static_cast(data); + delete napiKey; + return; + }, + nullptr, nullptr); + if (ret != napi_ok) { + LOGE("failed to wrap napiSymKey obj!"); + context->errCode = HCF_INVALID_PARAMS; + delete napiKey; + } + + if (context->asyncType == ASYNC_CALLBACK) { + ReturnCallbackResult(env, context, instance); + } else { + ReturnPromiseResult(env, context, instance); + } + FreeSymKeyGeneratorFwkCtx(env, context); +} + +static void AsyncConvertKeyProcess(napi_env env, void *data) +{ + SymKeyGeneratorFwkCtx context = static_cast(data); + HcfSymKeyGenerator *generator = context->generator; + + HcfSymKey *key = NULL; + HcfResult res = generator->convertSymKey(generator, &context->keyMaterial, &key); + if (res != HCF_SUCCESS) { + LOGE("convertSymKey key failed!"); + context->errCode = res; + context->errMsg = "convert sym key failed."; + return; + } + + context->errCode = HCF_SUCCESS; + context->returnSymKey = key; +} + +static napi_value NewConvertKeyAsyncWork(napi_env env, SymKeyGeneratorFwkCtx context) +{ + napi_value resourceName = nullptr; + napi_create_string_utf8(env, "convertSymKey", NAPI_AUTO_LENGTH, &resourceName); + + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + AsyncConvertKeyProcess(env, data); + return; + }, + [](napi_env env, napi_status status, void *data) { + AsyncKeyReturn(env, status, data); + return; + }, + (void *)context, + &context->asyncWork); + + napi_queue_async_work(env, context->asyncWork); + if (context->asyncType == ASYNC_PROMISE) { + return context->promise; + } else { + return NapiGetNull(env); + } +} + +static napi_value NewGenKeyAsyncWork(napi_env env, SymKeyGeneratorFwkCtx context) +{ + napi_value resourceName = nullptr; + napi_create_string_utf8(env, "generatorSymKey", NAPI_AUTO_LENGTH, &resourceName); + + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + AsyncGenKeyProcess(env, data); + return; + }, + [](napi_env env, napi_status status, void *data) { + AsyncKeyReturn(env, status, data); + return; + }, + (void *)context, + &context->asyncWork); + + napi_queue_async_work(env, context->asyncWork); + if (context->asyncType == ASYNC_PROMISE) { + return context->promise; + } else { + return NapiGetNull(env); + } +} + +NapiSymKeyGenerator::NapiSymKeyGenerator(HcfSymKeyGenerator *generator) +{ + this->generator_ = generator; +} + +NapiSymKeyGenerator::~NapiSymKeyGenerator() +{ + OH_HCF_ObjDestroy(this->generator_); +} + +HcfSymKeyGenerator *NapiSymKeyGenerator::GetSymKeyGenerator() +{ + return this->generator_; +} + +napi_value NapiSymKeyGenerator::JsGenerateSymKey(napi_env env, napi_callback_info info) +{ + SymKeyGeneratorFwkCtx context = (SymKeyGeneratorFwkCtx)HcfMalloc(sizeof(SymKeyGeneratorFwkCtxT), 0); + if (context == nullptr) { + LOGE("Create context failed!"); + return nullptr; + } + + if (!BuildContextForGenerateKey(env, info, context)) { + LOGE("Build context fail."); + FreeSymKeyGeneratorFwkCtx(env, context); + return nullptr; + } + + napi_value result = NewGenKeyAsyncWork(env, context); + if (result == nullptr) { + LOGE("NewGenKeyAsyncWork failed!"); + FreeSymKeyGeneratorFwkCtx(env, context); + return nullptr; + } + return result; +} + +napi_value NapiSymKeyGenerator::JsConvertKey(napi_env env, napi_callback_info info) +{ + SymKeyGeneratorFwkCtx context = (SymKeyGeneratorFwkCtx)HcfMalloc(sizeof(SymKeyGeneratorFwkCtxT), 0); + if (context == nullptr) { + LOGE("malloc SymKeyGeneratorFwkCtx failed!"); + return nullptr; + } + + if (!BuildContextForConvertKey(env, info, context)) { + LOGE("BuildContextForConvertKey failed!"); + FreeSymKeyGeneratorFwkCtx(env, context); + return nullptr; + } + + napi_value result = NewConvertKeyAsyncWork(env, context); + if (result == nullptr) { + LOGE("Get deviceauth async work failed!"); + FreeSymKeyGeneratorFwkCtx(env, context); + return nullptr; + } + return result; +} + +napi_value NapiSymKeyGenerator::SymKeyGeneratorConstructor(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); + return thisVar; +} + +napi_value NapiSymKeyGenerator::CreateSymKeyGenerator(napi_env env, napi_callback_info info) +{ + size_t exceptedArgc = ARGS_SIZE_ONE; + size_t argc = ARGS_SIZE_ONE; + napi_value argv[ARGS_SIZE_ONE] = { 0 }; + napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); + + if (argc != exceptedArgc) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "The input args num is invalid.")); + LOGE("The input args num is invalid."); + return nullptr; + } + + napi_value instance; + napi_value constructor = nullptr; + NAPI_CALL(env, napi_get_reference_value(env, classRef_, &constructor)); + NAPI_CALL(env, napi_new_instance(env, constructor, argc, argv, &instance)); + + std::string algoName; + if (!GetStringFromJSParams(env, argv[0], algoName)) { + LOGE("failed to get algoName."); + return nullptr; + } + + HcfSymKeyGenerator *generator = NULL; + int32_t res = HcfSymKeyGeneratorCreate(algoName.c_str(), &generator); + if (res != HCF_SUCCESS) { + napi_throw(env, GenerateBusinessError(env, res, "create C generator fail.")); + LOGE("create C generator fail."); + return nullptr; + } + NapiSymKeyGenerator *napiSymKeyGenerator = new NapiSymKeyGenerator(generator); + if (napiSymKeyGenerator == nullptr) { + LOGE("new napiSymKeyGenerator failed!"); + return nullptr; + } + + napi_status status = napi_wrap(env, instance, napiSymKeyGenerator, + [](napi_env env, void *data, void *hint) { + NapiSymKeyGenerator *napiSymKeyGenerator = static_cast(data); + delete napiSymKeyGenerator; + return; + }, + nullptr, + nullptr); + if (status != napi_ok) { + LOGE("failed to wrap napiSymKeyGenerator obj!"); + delete napiSymKeyGenerator; + return nullptr; + } + return instance; +} + +napi_value NapiSymKeyGenerator::JsGetAlgorithm(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + NapiSymKeyGenerator *napiSymKeyGenerator = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); + + NAPI_CALL(env, napi_unwrap(env, thisVar, (void **)&napiSymKeyGenerator)); + HcfSymKeyGenerator *generator = napiSymKeyGenerator->GetSymKeyGenerator(); + + const char *algo = generator->getAlgoName(generator); + napi_value instance = nullptr; + napi_create_string_utf8(env, (const char *)algo, NAPI_AUTO_LENGTH, &instance); + return instance; +} + +void NapiSymKeyGenerator::DefineSymKeyGeneratorJSClass(napi_env env, napi_value exports) +{ + napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("createSymKeyGenerator", NapiSymKeyGenerator::CreateSymKeyGenerator), + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); + + napi_property_descriptor classDesc[] = { + DECLARE_NAPI_FUNCTION("generateSymKey", NapiSymKeyGenerator::JsGenerateSymKey), + DECLARE_NAPI_FUNCTION("convertKey", NapiSymKeyGenerator::JsConvertKey), + { .utf8name = "algName", .getter = NapiSymKeyGenerator::JsGetAlgorithm }, + }; + napi_value constructor = nullptr; + napi_define_class(env, "SymKeyGenerator", NAPI_AUTO_LENGTH, NapiSymKeyGenerator::SymKeyGeneratorConstructor, + nullptr, sizeof(classDesc) / sizeof(classDesc[0]), classDesc, &constructor); + napi_create_reference(env, constructor, 1, &classRef_); +} + +} // CryptoFramework +} // OHOS diff --git a/frameworks/js/napi/src/napi_utils.cpp b/frameworks/js/napi/src/napi_utils.cpp new file mode 100644 index 0000000..df32efe --- /dev/null +++ b/frameworks/js/napi/src/napi_utils.cpp @@ -0,0 +1,746 @@ +/* + * Copyright (C) 2022 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 "napi_utils.h" + +#include "log.h" +#include "memory.h" +#include "securec.h" +#include "cipher.h" +#include "napi_crypto_framework_defines.h" +#include "detailed_iv_params.h" +#include "detailed_gcm_params.h" +#include "detailed_ccm_params.h" + +namespace OHOS { +namespace CryptoFramework { + +using namespace std; + +napi_value NapiGetNull(napi_env env) +{ + napi_value result = nullptr; + napi_get_null(env, &result); + return result; +} + +napi_value ConvertArrayToNapiValue(napi_env env, HcfArray *array) +{ + if (array == nullptr) { + LOGE("array is null!"); + return nullptr; + } + if (array->count == 0) { + LOGE("array count is 0!"); + return nullptr; + } + napi_value returnArray = nullptr; + napi_create_array(env, &returnArray); + if (returnArray == nullptr) { + LOGE("create return array failed!"); + return nullptr; + } + for (uint32_t i = 0; i < array->count; i++) { + HcfBlob *blob = (HcfBlob *)(array->data + i); + napi_value outBuffer = GenerateArrayBuffer(env, blob->data, blob->len); + if (outBuffer == nullptr) { + LOGE("generate array buffer failed!"); + return nullptr; + } + napi_value element = nullptr; + napi_create_typedarray(env, napi_uint8_array, blob->len, outBuffer, 0, &element); + napi_set_element(env, returnArray, i, element); + } + napi_value returnValue = nullptr; + napi_create_object(env, &returnValue); + napi_set_named_property(env, returnValue, CRYPTO_TAG_DATA.c_str(), returnArray); + return returnValue; +} + +napi_value GenerateArrayBuffer(napi_env env, uint8_t *data, uint32_t size) +{ + uint8_t *buffer = (uint8_t *)HcfMalloc(size, 0); + if (buffer == nullptr) { + LOGE("malloc uint8 array buffer failed!"); + return nullptr; + } + + if (memcpy_s(buffer, size, data, size) != EOK) { + LOGE("memcpy_s data to buffer failed!"); + HcfFree(buffer); + return nullptr; + } + + napi_value outBuffer = nullptr; + napi_status status = napi_create_external_arraybuffer( + env, buffer, size, [](napi_env env, void *data, void *hint) { HcfFree(data); }, nullptr, &outBuffer); + if (status != napi_ok) { + LOGE("create uint8 array buffer failed!"); + HcfFree(buffer); + return nullptr; + } + buffer = nullptr; + return outBuffer; +} + +static bool GetDataOfEncodingBlob(napi_env env, napi_value data, HcfEncodingBlob *encodingBlob) +{ + napi_typedarray_type arrayType; + napi_value arrayBuffer = nullptr; + size_t length = 0; + size_t offset = 0; + void *rawData = nullptr; + + napi_status status = napi_get_typedarray_info(env, data, &arrayType, &length, + (void **)&rawData, &arrayBuffer, &offset); + if (status != napi_ok) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "get array data failed")); + LOGE("failed to get array data!"); + return false; + } + if (arrayType != napi_uint8_array) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "array type is not uint8 array")); + LOGE("array is not uint8 array!"); + return false; + } + + if (length == 0) { + LOGE("input data length is 0"); + return false; + } + encodingBlob->data = (uint8_t *)HcfMalloc(length, 0); + if (encodingBlob->data == nullptr) { + LOGE("malloc encoding blob data failed!"); + return false; + } + if (memcpy_s(encodingBlob->data, length, rawData, length) != EOK) { + LOGE("memcpy_s encoding blob data failed!"); + HcfFree(encodingBlob->data); + encodingBlob->data = nullptr; + return false; + } + encodingBlob->len = length; + return true; +} + +bool GetEncodingBlobFromValue(napi_env env, napi_value obj, HcfEncodingBlob **encodingBlob) +{ + *encodingBlob = (HcfEncodingBlob *)HcfMalloc(sizeof(HcfEncodingBlob), 0); + if (*encodingBlob == nullptr) { + LOGE("malloc encoding blob failed!"); + return false; + } + napi_value data = nullptr; + napi_status status = napi_get_named_property(env, obj, CRYPTO_TAG_DATA.c_str(), &data); + if (status != napi_ok) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "get encoding blob data failed")); + LOGE("failed to get encoding blob data!"); + HcfFree(*encodingBlob); + *encodingBlob = nullptr; + return false; + } + if (!GetDataOfEncodingBlob(env, data, *encodingBlob)) { + HcfFree(*encodingBlob); + *encodingBlob = nullptr; + return false; + } + napi_value format = nullptr; + status = napi_get_named_property(env, obj, CRYPTO_TAG_ENCODING_FORMAT.c_str(), &format); + if (status != napi_ok) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "get encoding blob format failed")); + LOGE("failed to get encoding blob format!"); + HcfFree((*encodingBlob)->data); + (*encodingBlob)->data = nullptr; + HcfFree(*encodingBlob); + *encodingBlob = nullptr; + return false; + } + napi_get_value_uint32(env, format, (uint32_t *)(&(*encodingBlob)->encodingFormat)); + return true; +} + +napi_value ConvertEncodingBlobToNapiValue(napi_env env, HcfEncodingBlob *encodingBlob) +{ + napi_value outBuffer = GenerateArrayBuffer(env, encodingBlob->data, encodingBlob->len); + if (outBuffer == nullptr) { + LOGE("generate array buffer failed!"); + return nullptr; + } + napi_value outData = nullptr; + napi_create_typedarray(env, napi_uint8_array, encodingBlob->len, outBuffer, 0, &outData); + napi_value encoding = nullptr; + napi_create_uint32(env, encodingBlob->encodingFormat, &encoding); + napi_value returnEncodingBlob = nullptr; + napi_create_object(env, &returnEncodingBlob); + napi_set_named_property(env, returnEncodingBlob, CRYPTO_TAG_DATA.c_str(), outData); + napi_set_named_property(env, returnEncodingBlob, CRYPTO_TAG_ENCODING_FORMAT.c_str(), encoding); + return returnEncodingBlob; +} + +HcfBlob *GetBlobFromNapiValue(napi_env env, napi_value arg) +{ + if ((env == nullptr) || (arg == nullptr)) { + LOGE("Invalid parmas!"); + return nullptr; + } + napi_value data = nullptr; + napi_status status = napi_get_named_property(env, arg, CRYPTO_TAG_DATA.c_str(), &data); + if ((status != napi_ok) || (data == nullptr)) { + LOGE("failed to get valid data property!"); + return nullptr; + } + + size_t length = 0; + size_t offset = 0; + void *rawData = nullptr; + napi_value arrayBuffer = nullptr; + napi_typedarray_type arrayType; + // Warning: Do not release the rawData returned by this interface because the rawData is managed by VM. + status = napi_get_typedarray_info(env, data, &arrayType, &length, (void **)&rawData, &arrayBuffer, &offset); + if ((status != napi_ok) || (length == 0) || (rawData == nullptr)) { + LOGE("failed to get valid rawData."); + return nullptr; + } + if (arrayType != napi_uint8_array) { + LOGE("input data is not uint8 array."); + return nullptr; + } + + HcfBlob *newBlob = (HcfBlob *)HcfMalloc(sizeof(HcfBlob), 0); + if (newBlob == NULL) { + LOGE("Failed to allocate newBlob memory!"); + return nullptr; + } + newBlob->len = length; + newBlob->data = (uint8_t *)HcfMalloc(length, 0); + if (newBlob->data == nullptr) { + LOGE("malloc blob data failed!"); + HcfFree(newBlob); + return nullptr; + } + if (memcpy_s(newBlob->data, length, rawData, length) != EOK) { + LOGE("memcpy_s blob data failed!"); + HcfFree(newBlob->data); + HcfFree(newBlob); + return nullptr; + } + + return newBlob; +} + +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(); +} + +static HcfBlob *GetBlobFromParamsSpec(napi_env env, napi_value arg, string type) +{ + napi_value data = nullptr; + HcfBlob *blob = nullptr; + + napi_status status = napi_get_named_property(env, arg, type.c_str(), &data); + if ((status != napi_ok) || (data == nullptr)) { + LOGE("failed to get valid data property!"); + return nullptr; + } + blob = GetBlobFromNapiValue(env, data); + if (blob == nullptr) { + LOGE("GetBlobFromNapiValue failed!"); + return nullptr; + } + return blob; +} + +static bool GetIvParamsSpec(napi_env env, napi_value arg, HcfParamsSpec **paramsSpec) +{ + HcfIvParamsSpec *ivParamsSpec = (HcfIvParamsSpec *)HcfMalloc(sizeof(HcfIvParamsSpec), 0); + if (ivParamsSpec == nullptr) { + LOGE("ccmParamsSpec malloc failed!"); + return false; + } + + HcfBlob *iv = GetBlobFromParamsSpec(env, arg, IV_PARAMS); + if (iv == nullptr) { + LOGE("GetBlobFromNapiValue failed!"); + HcfFree(ivParamsSpec); + return false; + } + ivParamsSpec->base.getType = GetIvParamsSpecType; + ivParamsSpec->iv = *iv; + *paramsSpec = (HcfParamsSpec *)ivParamsSpec; + HcfFree(iv); + return true; +} + +static bool GetIvAndAadBlob(napi_env env, napi_value arg, HcfBlob **iv, HcfBlob **aad) +{ + *iv = GetBlobFromParamsSpec(env, arg, IV_PARAMS); + if (*iv == nullptr) { + LOGE("get iv failed!"); + return false; + } + + *aad = GetBlobFromParamsSpec(env, arg, AAD_PARAMS); + if (*aad == nullptr) { + LOGE("get aad failed!"); + HcfFree((*iv)->data); + HcfFree(*iv); + return false; + } + return true; +} + +static bool GetGcmParamsSpec(napi_env env, napi_value arg, HcfCryptoMode opMode, HcfParamsSpec **paramsSpec) +{ + HcfBlob *iv = nullptr; + HcfBlob *aad = nullptr; + HcfBlob *tag = nullptr; + HcfBlob authTag = {}; + bool ret = false; + + HcfGcmParamsSpec *gcmParamsSpec = (HcfGcmParamsSpec *)HcfMalloc(sizeof(HcfGcmParamsSpec), 0); + if (gcmParamsSpec == nullptr) { + LOGE("gcmParamsSpec malloc failed!"); + return false; + } + + ret = GetIvAndAadBlob(env, arg, &iv, &aad); + if (!ret) { + LOGE("GetIvAndAadBlob failed!"); + goto clearup; + } + + if (opMode == DECRYPT_MODE) { + tag = GetBlobFromParamsSpec(env, arg, AUTHTAG_PARAMS); + if (tag == nullptr) { + LOGE("get tag failed!"); + goto clearup; + } + } else if (opMode == ENCRYPT_MODE) { + authTag.data = (uint8_t *)HcfMalloc(GCM_AUTH_TAG_LEN, 0); + if (authTag.data == nullptr) { + LOGE("get tag failed!"); + goto clearup; + } + authTag.len = GCM_AUTH_TAG_LEN; + } else { + goto clearup; + } + + gcmParamsSpec->base.getType = GetGcmParamsSpecType; + gcmParamsSpec->iv = *iv; + gcmParamsSpec->aad = *aad; + gcmParamsSpec->tag = opMode == DECRYPT_MODE ? *tag : authTag; + *paramsSpec = (HcfParamsSpec *)gcmParamsSpec; + ret = true; +clearup: + if (ret != true) { + HcfBlobDataFree(iv); + HcfBlobDataFree(aad); + HcfBlobDataFree(tag); + HcfFree(gcmParamsSpec); + } + HcfFree(iv); + HcfFree(aad); + HcfFree(tag); + return ret; +} + +static bool GetCcmParamsSpec(napi_env env, napi_value arg, HcfCryptoMode opMode, HcfParamsSpec **paramsSpec) +{ + HcfBlob *iv = nullptr; + HcfBlob *aad = nullptr; + HcfBlob *tag = nullptr; + HcfBlob authTag = {}; + bool ret = false; + + HcfCcmParamsSpec *ccmParamsSpec = (HcfCcmParamsSpec *)HcfMalloc(sizeof(HcfCcmParamsSpec), 0); + if (ccmParamsSpec == nullptr) { + LOGE("ccmParamsSpec malloc failed!"); + return ret; + } + ret = GetIvAndAadBlob(env, arg, &iv, &aad); + if (!ret) { + LOGE("GetIvAndAadBlob failed!"); + goto clearup; + } + + if (opMode == DECRYPT_MODE) { + tag = GetBlobFromParamsSpec(env, arg, AUTHTAG_PARAMS); + if (tag == nullptr) { + LOGE("get tag failed!"); + goto clearup; + } + } else if (opMode == ENCRYPT_MODE) { + authTag.data = (uint8_t *)HcfMalloc(CCM_AUTH_TAG_LEN, 0); + if (authTag.data == nullptr) { + LOGE("get tag failed!"); + goto clearup; + } + authTag.len = CCM_AUTH_TAG_LEN; + } else { + goto clearup; + } + ccmParamsSpec->base.getType = GetCcmParamsSpecType; + ccmParamsSpec->iv = *iv; + ccmParamsSpec->aad = *aad; + ccmParamsSpec->tag = opMode == DECRYPT_MODE ? *tag : authTag; + *paramsSpec = (HcfParamsSpec *)ccmParamsSpec; + ret = true; +clearup: + if (ret != true) { + HcfBlobDataFree(iv); + HcfBlobDataFree(aad); + HcfBlobDataFree(tag); + HcfFree(ccmParamsSpec); + } + HcfFree(iv); + HcfFree(aad); + HcfFree(tag); + return ret; +} + +bool GetParamsSpecFormNapiValue(napi_env env, napi_value arg, HcfCryptoMode opMode, HcfParamsSpec **paramsSpec) +{ + napi_value data = nullptr; + if ((env == nullptr) || (arg == nullptr) || (paramsSpec == nullptr)) { + LOGE("Invalid parmas!"); + return false; + } + + napi_status status = napi_get_named_property(env, arg, ALGO_PARAMS.c_str(), &data); + if ((status != napi_ok) || (data == nullptr)) { + LOGE("failed to get valid data property!"); + return false; + } + string algoName; + if (!GetStringFromJSParams(env, data, algoName)) { + LOGE("GetStringFromJSParams failed!"); + return false; + } + if (algoName.compare(IV_PARAMS_SPEC) == 0) { + return GetIvParamsSpec(env, arg, paramsSpec); + } else if (algoName.compare(GCM_PARAMS_SPEC) == 0) { + return GetGcmParamsSpec(env, arg, opMode, paramsSpec); + } else if (algoName.compare(CCM_PARAMS_SPEC) == 0) { + return GetCcmParamsSpec(env, arg, opMode, paramsSpec); + } else { + return false; + } +} + +napi_value ConvertBlobToNapiValue(napi_env env, HcfBlob *blob) +{ + if (blob == nullptr || blob->data == nullptr || blob->len == 0) { + LOGE("Invalid blob!"); + return nullptr; + } + uint8_t *buffer = (uint8_t *)HcfMalloc(blob->len, 0); + if (buffer == nullptr) { + LOGE("malloc uint8 array buffer failed!"); + return nullptr; + } + + if (memcpy_s(buffer, blob->len, blob->data, blob->len) != EOK) { + LOGE("memcpy_s data to buffer failed!"); + HcfFree(buffer); + return nullptr; + } + + napi_value outBuffer = nullptr; + napi_status status = napi_create_external_arraybuffer( + 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!"); + HcfFree(buffer); + return nullptr; + } + buffer = nullptr; + + napi_value outData = nullptr; + napi_create_typedarray(env, napi_uint8_array, blob->len, outBuffer, 0, &outData); + napi_value dataBlob = nullptr; + napi_create_object(env, &dataBlob); + napi_set_named_property(env, dataBlob, CRYPTO_TAG_DATA.c_str(), outData); + + return dataBlob; +} + +static bool GetDataOfCertChain(napi_env env, napi_value data, HcfCertChainData *certChain) +{ + napi_typedarray_type arrayType; + napi_value arrayBuffer = nullptr; + size_t length = 0; + size_t offset = 0; + void *rawData = nullptr; + + napi_status status = napi_get_typedarray_info(env, data, &arrayType, &length, + (void **)&rawData, &arrayBuffer, &offset); + if (status != napi_ok) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "get array data failed")); + LOGE("failed to get array data!"); + return false; + } + if (arrayType != napi_uint8_array) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "array type is not uint8 array")); + LOGE("array is not uint8 array!"); + return false; + } + + if (length == 0) { + LOGE("input data length is 0"); + return false; + } + certChain->data = (uint8_t *)HcfMalloc(length, 0); + if (certChain->data == nullptr) { + LOGE("malloc cert chain data failed!"); + return false; + } + if (memcpy_s(certChain->data, length, rawData, length) != EOK) { + LOGE("memcpy_s cert chain data failed!"); + HcfFree(certChain->data); + certChain->data = nullptr; + return false; + } + certChain->dataLen = length; + return true; +} + +bool GetCertChainFromValue(napi_env env, napi_value obj, HcfCertChainData **certChainData) +{ + *certChainData = (HcfCertChainData *)HcfMalloc(sizeof(HcfCertChainData), 0); + if (*certChainData == nullptr) { + LOGE("malloc certChainData failed!"); + return false; + } + napi_value data = nullptr; + napi_status status = napi_get_named_property(env, obj, CRYPTO_TAG_DATA.c_str(), &data); + if (status != napi_ok) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "get cert chain data failed")); + LOGE("failed to get cert chain data!"); + HcfFree(*certChainData); + *certChainData = nullptr; + return false; + } + if (!GetDataOfCertChain(env, data, *certChainData)) { + HcfFree(*certChainData); + *certChainData = nullptr; + return false; + } + + napi_value certCount = nullptr; + status = napi_get_named_property(env, obj, CRYPTO_TAG_COUNT.c_str(), &certCount); + if (status != napi_ok) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "get cert chain count failed")); + LOGE("failed to get cert count!"); + HcfFree((*certChainData)->data); + (*certChainData)->data = nullptr; + HcfFree(*certChainData); + *certChainData = nullptr; + return false; + } + napi_get_value_uint32(env, certCount, (uint32_t *)(&(*certChainData)->count)); + + napi_value format = nullptr; + status = napi_get_named_property(env, obj, CRYPTO_TAG_ENCODING_FORMAT.c_str(), &format); + if (status != napi_ok) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "get cert chain format failed")); + LOGE("failed to get cert chain format!"); + HcfFree((*certChainData)->data); + (*certChainData)->data = nullptr; + HcfFree(*certChainData); + *certChainData = nullptr; + return false; + } + napi_get_value_uint32(env, format, (uint32_t *)(&(*certChainData)->format)); + return true; +} + +bool GetStringFromJSParams(napi_env env, napi_value arg, string &returnStr) +{ + napi_valuetype valueType; + napi_typeof(env, arg, &valueType); + if (valueType != napi_string) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "param type is not string")); + LOGE("wrong argument type. expect string type. [Type]: %d", valueType); + return false; + } + + size_t length = 0; + if (napi_get_value_string_utf8(env, arg, nullptr, 0, &length) != napi_ok) { + LOGE("can not get string length"); + return false; + } + returnStr.reserve(length + 1); + returnStr.resize(length); + if (napi_get_value_string_utf8(env, arg, returnStr.data(), (length + 1), &length) != napi_ok) { + LOGE("can not get string value"); + return false; + } + return true; +} + +bool GetInt32FromJSParams(napi_env env, napi_value arg, int32_t &returnInt) +{ + napi_valuetype valueType; + napi_typeof(env, arg, &valueType); + if (valueType != napi_number) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "param type is not number")); + LOGE("wrong argument type. expect int type. [Type]: %d", valueType); + return false; + } + + if (napi_get_value_int32(env, arg, &returnInt) != napi_ok) { + LOGE("can not get int value"); + return false; + } + return true; +} + +bool GetUint32FromJSParams(napi_env env, napi_value arg, uint32_t &returnInt) +{ + napi_valuetype valueType; + napi_typeof(env, arg, &valueType); + if (valueType != napi_number) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "param type is not number")); + LOGE("wrong argument type. expect int type. [Type]: %d", valueType); + return false; + } + + if (napi_get_value_uint32(env, arg, &returnInt) != napi_ok) { + LOGE("can not get int value"); + return false; + } + return true; +} + +bool GetCallbackFromJSParams(napi_env env, napi_value arg, napi_ref *returnCb) +{ + napi_valuetype valueType = napi_undefined; + napi_typeof(env, arg, &valueType); + if (valueType != napi_function) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "param type is not function")); + LOGE("wrong argument type. expect callback type. [Type]: %d", valueType); + return false; + } + + napi_create_reference(env, arg, 1, returnCb); + return true; +} + +bool ParseArrayBuffer(napi_env env, napi_value args, uint8_t **data, size_t &size) +{ + napi_status status; + napi_valuetype valuetype; + napi_typeof(env, args, &valuetype); + + if (valuetype != napi_object) { + LOGE("Wrong argument type(%d). object expected.", valuetype); + return false; + } + + status = napi_get_arraybuffer_info(env, args, (void**)data, &size); + if (status != napi_ok) { + LOGE("can not get arraybuffer, error is %d", status); + (*data)[0] = -1; + return false; + } + LOGI("arraybuffer size is %zu", size); + return true; +} + +static uint32_t GetJsErrValueByErrCode(int32_t errCode) +{ + switch (errCode) { + case HCF_INVALID_PARAMS: + return JS_ERR_INVALID_PARAMS; + case HCF_NOT_SUPPORT: + return JS_ERR_NOT_SUPPORT; + case HCF_ERR_MALLOC: + return JS_ERR_OUT_OF_MEMORY; + case HCF_ERR_COPY: + return JS_ERR_INTERNAL_ERROR; + case HCF_ERR_CRYPTO_OPERATION: + return JS_ERR_CRYPTO_OPERATION; + case HCF_ERR_CERT_SIGNATURE_FAILURE: + return JS_ERR_CERT_SIGNATURE_FAILURE; + case HCF_ERR_CERT_NOT_YET_VALID: + return JS_ERR_CERT_NOT_YET_VALID; + case HCF_ERR_CERT_HAS_EXPIRED: + return JS_ERR_CERT_HAS_EXPIRED; + case HCF_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY: + return JS_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY; + case HCF_ERR_KEYUSAGE_NO_CERTSIGN: + return JS_ERR_KEYUSAGE_NO_CERTSIGN; + case HCF_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE: + return JS_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE; + default: + return JS_ERR_DEFAULT_ERR; + } +} + +napi_value GenerateBusinessError(napi_env env, int32_t errCode, const char *errMsg) +{ + napi_value businessError = nullptr; + + napi_value code = nullptr; + napi_create_uint32(env, GetJsErrValueByErrCode(errCode), &code); + + napi_value msg = nullptr; + napi_create_string_utf8(env, errMsg, NAPI_AUTO_LENGTH, &msg); + + napi_create_error(env, nullptr, msg, &businessError); + napi_set_named_property(env, businessError, CRYPTO_TAG_ERR_CODE.c_str(), code); + + return businessError; +} + +bool CheckArgsCount(napi_env env, size_t argc, size_t expectedCount, bool isSync) +{ + if (isSync) { + if (argc != expectedCount) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "invalid params count")); + LOGE("invalid params count!"); + return false; + } + } else { + if ((argc != expectedCount) && (argc != (expectedCount - ARGS_SIZE_ONE))) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "invalid params count")); + LOGE("invalid params count!"); + return false; + } + } + return true; +} + +napi_value GetResourceName(napi_env env, const char *name) +{ + napi_value resourceName = nullptr; + napi_create_string_utf8(env, name, NAPI_AUTO_LENGTH, &resourceName); + return resourceName; +} + +} // namespace CryptoFramework +} // namespace OHOS diff --git a/frameworks/js/napi/src/napi_verify.cpp b/frameworks/js/napi/src/napi_verify.cpp new file mode 100644 index 0000000..d5276e3 --- /dev/null +++ b/frameworks/js/napi/src/napi_verify.cpp @@ -0,0 +1,686 @@ +/* + * Copyright (C) 2022 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 "napi_verify.h" + +#include "securec.h" +#include "log.h" +#include "memory.h" + +#include "napi_crypto_framework_defines.h" +#include "napi_pri_key.h" +#include "napi_pub_key.h" +#include "napi_utils.h" + +namespace OHOS { +namespace CryptoFramework { + +struct VerifyInitCtx { + napi_env env = nullptr; + + AsyncType asyncType = ASYNC_CALLBACK; + napi_ref callback = nullptr; + napi_deferred deferred = nullptr; + napi_value promise = nullptr; + napi_async_work asyncWork = nullptr; + + HcfVerify *verify; + HcfParamsSpec *params; + HcfPubKey *pubKey; + + HcfResult result; +}; + +struct VerifyUpdateCtx { + napi_env env = nullptr; + + AsyncType asyncType = ASYNC_CALLBACK; + napi_ref callback = nullptr; + napi_deferred deferred = nullptr; + napi_value promise = nullptr; + napi_async_work asyncWork = nullptr; + + HcfVerify *verify; + HcfBlob *data; + + HcfResult result; +}; + +struct VerifyDoFinalCtx { + napi_env env = nullptr; + + AsyncType asyncType = ASYNC_CALLBACK; + napi_ref callback = nullptr; + napi_deferred deferred = nullptr; + napi_value promise = nullptr; + napi_async_work asyncWork = nullptr; + + HcfVerify *verify; + HcfBlob *data; + HcfBlob *signatureData; + + bool result; +}; + +thread_local napi_ref NapiVerify::classRef_ = nullptr; + +static void FreeVerifyInitCtx(napi_env env, VerifyInitCtx *ctx) +{ + if (ctx == nullptr) { + return; + } + + if (ctx->asyncWork != nullptr) { + napi_delete_async_work(env, ctx->asyncWork); + ctx->asyncWork = nullptr; + } + + if (ctx->callback != nullptr) { + napi_delete_reference(env, ctx->callback); + ctx->callback = nullptr; + } + + HcfFree(ctx); +} + +static void FreeVerifyUpdateCtx(napi_env env, VerifyUpdateCtx *ctx) +{ + if (ctx == nullptr) { + return; + } + + if (ctx->asyncWork != nullptr) { + napi_delete_async_work(env, ctx->asyncWork); + ctx->asyncWork = nullptr; + } + + if (ctx->callback != nullptr) { + napi_delete_reference(env, ctx->callback); + ctx->callback = nullptr; + } + + HcfBlobDataFree(ctx->data); + HcfFree(ctx->data); + HcfFree(ctx); +} + +static void FreeVerifyDoFinalCtx(napi_env env, VerifyDoFinalCtx *ctx) +{ + if (ctx == nullptr) { + return; + } + + if (ctx->asyncWork != nullptr) { + napi_delete_async_work(env, ctx->asyncWork); + ctx->asyncWork = nullptr; + } + + if (ctx->callback != nullptr) { + napi_delete_reference(env, ctx->callback); + ctx->callback = nullptr; + } + + HcfBlobDataFree(ctx->data); + HcfFree(ctx->data); + HcfBlobDataFree(ctx->signatureData); + HcfFree(ctx->signatureData); + HcfFree(ctx); +} + +static bool BuildVerifyJsInitCtx(napi_env env, napi_callback_info info, VerifyInitCtx *ctx) +{ + napi_value thisVar = nullptr; + size_t expectedArgc = PARAMS_NUM_TWO; + size_t argc; + napi_value argv[PARAMS_NUM_TWO] = { nullptr, 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); + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "params num error.")); + return false; + } + ctx->asyncType = (argc == expectedArgc) ? ASYNC_CALLBACK : ASYNC_PROMISE; + + NapiVerify *napiVerify = NULL; + napi_status status = napi_unwrap(env, thisVar, (void **)(&napiVerify)); + if (status != napi_ok) { + LOGE("failed to unwrap napi verify obj."); + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "[Self]: param unwarp error.")); + return false; + } + + size_t index = 0; + NapiPubKey *napiPubKey = NULL; + status = napi_unwrap(env, argv[index], (void **)(&napiPubKey)); + if (status != napi_ok) { + LOGE("failed to unwrap napi pubKey obj."); + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "[PubKey]: param unwarp error.")); + return false; + } + + ctx->verify = napiVerify->GetVerify(); + ctx->params = nullptr; + ctx->pubKey = napiPubKey->GetPubKey(); + + if (ctx->asyncType == ASYNC_PROMISE) { + napi_create_promise(env, &ctx->deferred, &ctx->promise); + return true; + } else { + return GetCallbackFromJSParams(env, argv[expectedArgc - 1], &ctx->callback); + } +} + +static bool BuildVerifyJsUpdateCtx(napi_env env, napi_callback_info info, VerifyUpdateCtx *ctx) +{ + napi_value thisVar = nullptr; + size_t expectedArgc = PARAMS_NUM_TWO; + size_t argc; + napi_value argv[PARAMS_NUM_TWO] = { nullptr, 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); + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "params num error.")); + return false; + } + ctx->asyncType = (argc == expectedArgc) ? ASYNC_CALLBACK : ASYNC_PROMISE; + + NapiVerify *napiVerify = NULL; + napi_status status = napi_unwrap(env, thisVar, (void **)(&napiVerify)); + if (status != napi_ok) { + LOGE("failed to unwrap napi verify obj."); + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "params num error.")); + return false; + } + + size_t index = 0; + HcfBlob *blob = GetBlobFromNapiValue(env, argv[index]); + if (blob == nullptr) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "[Data]: must be of the DataBlob type.")); + return false; + } + + ctx->verify = napiVerify->GetVerify(); + ctx->data = blob; + + if (ctx->asyncType == ASYNC_PROMISE) { + napi_create_promise(env, &ctx->deferred, &ctx->promise); + return true; + } else { + return GetCallbackFromJSParams(env, argv[expectedArgc - 1], &ctx->callback); + } +} + +static bool GetDataBlobAndSignatureFromInput(napi_env env, napi_value dataValue, napi_value signatureDataValue, + HcfBlob **returnData, HcfBlob **returnSignatureData) +{ + napi_valuetype valueType; + napi_typeof(env, dataValue, &valueType); + HcfBlob *data = nullptr; + if (valueType != napi_null) { + data = GetBlobFromNapiValue(env, dataValue); + if (data == nullptr) { + LOGE("failed to get data."); + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "[Data]: must be of the DataBlob type.")); + return false; + } + } + + HcfBlob *signatureData = GetBlobFromNapiValue(env, signatureDataValue); + if (signatureData == nullptr) { + LOGE("failed to get signature."); + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, + "[SignatureData]: must be of the DataBlob type.")); + HcfBlobDataFree(data); + HcfFree(data); + return false; + } + + *returnData = data; + *returnSignatureData = signatureData; + return true; +} + +static bool BuildVerifyJsDoFinalCtx(napi_env env, napi_callback_info info, VerifyDoFinalCtx *ctx) +{ + napi_value thisVar = nullptr; + size_t expectedArgc = PARAMS_NUM_THREE; + size_t argc; + napi_value argv[PARAMS_NUM_THREE] = { nullptr, nullptr, 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); + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "params num error.")); + return false; + } + ctx->asyncType = (argc == expectedArgc) ? ASYNC_CALLBACK : ASYNC_PROMISE; + + NapiVerify *napiVerify = nullptr; + napi_status status = napi_unwrap(env, thisVar, (void **)(&napiVerify)); + if (status != napi_ok) { + LOGE("failed to unwrap napi verify obj."); + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "[Self]: param unwarp error.")); + return false; + } + + HcfBlob *data = nullptr; + HcfBlob *signatureData = nullptr; + if (!GetDataBlobAndSignatureFromInput(env, argv[PARAM0], argv[PARAM1], &data, &signatureData)) { + return false; + } + + ctx->verify = napiVerify->GetVerify(); + ctx->data = data; + ctx->signatureData = signatureData; + + if (ctx->asyncType == ASYNC_PROMISE) { + napi_create_promise(env, &ctx->deferred, &ctx->promise); + return true; + } else { + return GetCallbackFromJSParams(env, argv[expectedArgc - 1], &ctx->callback); + } +} + +static void ReturnInitCallbackResult(napi_env env, VerifyInitCtx *ctx, napi_value result) +{ + napi_value businessError = nullptr; + if (ctx->result != HCF_SUCCESS) { + businessError = GenerateBusinessError(env, ctx->result, COMMON_ERR_MSG.c_str()); + } + + napi_value params[ARGS_SIZE_ONE] = { businessError }; + + napi_value func = nullptr; + napi_get_reference_value(env, ctx->callback, &func); + + napi_value recv = nullptr; + napi_value callFuncRet = nullptr; + napi_get_undefined(env, &recv); + napi_call_function(env, recv, func, ARGS_SIZE_ONE, params, &callFuncRet); +} + +static void ReturnInitPromiseResult(napi_env env, VerifyInitCtx *ctx, napi_value result) +{ + if (ctx->result == HCF_SUCCESS) { + napi_resolve_deferred(env, ctx->deferred, result); + } else { + napi_reject_deferred(env, ctx->deferred, GenerateBusinessError(env, ctx->result, COMMON_ERR_MSG.c_str())); + } +} + +static void ReturnUpdateCallbackResult(napi_env env, VerifyUpdateCtx *ctx, napi_value result) +{ + napi_value businessError = nullptr; + if (ctx->result != HCF_SUCCESS) { + businessError = GenerateBusinessError(env, ctx->result, COMMON_ERR_MSG.c_str()); + } + + napi_value params[ARGS_SIZE_ONE] = { businessError }; + + napi_value func = nullptr; + napi_get_reference_value(env, ctx->callback, &func); + + napi_value recv = nullptr; + napi_value callFuncRet = nullptr; + napi_get_undefined(env, &recv); + napi_call_function(env, recv, func, ARGS_SIZE_ONE, params, &callFuncRet); +} + +static void ReturnUpdatePromiseResult(napi_env env, VerifyUpdateCtx *ctx, napi_value result) +{ + if (ctx->result == HCF_SUCCESS) { + napi_resolve_deferred(env, ctx->deferred, result); + } else { + napi_reject_deferred(env, ctx->deferred, GenerateBusinessError(env, ctx->result, COMMON_ERR_MSG.c_str())); + } +} + +static void ReturnDoFinalCallbackResult(napi_env env, VerifyDoFinalCtx *ctx, napi_value result) +{ + napi_value businessError = nullptr; + if (ctx->result != HCF_SUCCESS) { + businessError = GenerateBusinessError(env, ctx->result, COMMON_ERR_MSG.c_str()); + } + + napi_value params[ARGS_SIZE_TWO] = { businessError, result }; + + napi_value func = nullptr; + napi_get_reference_value(env, ctx->callback, &func); + + napi_value recv = nullptr; + napi_value callFuncRet = nullptr; + napi_get_undefined(env, &recv); + napi_call_function(env, recv, func, ARGS_SIZE_TWO, params, &callFuncRet); +} + +static void ReturnDoFinalPromiseResult(napi_env env, VerifyDoFinalCtx *ctx, napi_value result) +{ + if (ctx->result) { + napi_resolve_deferred(env, ctx->deferred, result); + } else { + napi_reject_deferred(env, ctx->deferred, + GenerateBusinessError(env, HCF_ERR_CRYPTO_OPERATION, COMMON_ERR_MSG.c_str())); + } +} + +void VerifyJsInitAsyncWorkProcess(napi_env env, void *data) +{ + VerifyInitCtx *ctx = static_cast(data); + + HcfResult res = ctx->verify->init(ctx->verify, ctx->params, ctx->pubKey); + + ctx->result = res; + if (res != HCF_SUCCESS) { + LOGE("verify init fail."); + } +} + +void VerifyJsInitAsyncWorkReturn(napi_env env, napi_status status, void *data) +{ + VerifyInitCtx *ctx = static_cast(data); + + if (ctx->asyncType == ASYNC_CALLBACK) { + ReturnInitCallbackResult(env, ctx, NapiGetNull(env)); + } else { + ReturnInitPromiseResult(env, ctx, NapiGetNull(env)); + } + FreeVerifyInitCtx(env, ctx); +} + +void VerifyJsUpdateAsyncWorkProcess(napi_env env, void *data) +{ + VerifyUpdateCtx *ctx = static_cast(data); + + HcfResult res = ctx->verify->update(ctx->verify, ctx->data); + + ctx->result = res; + if (res != HCF_SUCCESS) { + LOGE("verify update fail."); + } +} + +void VerifyJsUpdateAsyncWorkReturn(napi_env env, napi_status status, void *data) +{ + VerifyUpdateCtx *ctx = static_cast(data); + + if (ctx->asyncType == ASYNC_CALLBACK) { + ReturnUpdateCallbackResult(env, ctx, NapiGetNull(env)); + } else { + ReturnUpdatePromiseResult(env, ctx, NapiGetNull(env)); + } + FreeVerifyUpdateCtx(env, ctx); +} + +void VerifyJsDoFinalAsyncWorkProcess(napi_env env, void *data) +{ + VerifyDoFinalCtx *ctx = static_cast(data); + + bool res = ctx->verify->verify(ctx->verify, ctx->data, ctx->signatureData); + + ctx->result = res; + if (!res) { + LOGE("verify doFinal fail."); + return; + } +} + +void VerifyJsDoFinalAsyncWorkReturn(napi_env env, napi_status status, void *data) +{ + VerifyDoFinalCtx *ctx = static_cast(data); + + napi_value result = nullptr; + napi_get_boolean(env, ctx->result, &result); + + if (ctx->asyncType == ASYNC_CALLBACK) { + ReturnDoFinalCallbackResult(env, ctx, result); + } else { + ReturnDoFinalPromiseResult(env, ctx, result); + } + FreeVerifyDoFinalCtx(env, ctx); +} + +static napi_value NewVerifyJsInitAsyncWork(napi_env env, VerifyInitCtx *ctx) +{ + napi_value resourceName = nullptr; + napi_create_string_utf8(env, "init", NAPI_AUTO_LENGTH, &resourceName); + + napi_create_async_work( + env, nullptr, resourceName, + [](napi_env env, void *data) { + VerifyJsInitAsyncWorkProcess(env, data); + return; + }, + [](napi_env env, napi_status status, void *data) { + VerifyJsInitAsyncWorkReturn(env, status, data); + return; + }, + (void *)ctx, + &ctx->asyncWork); + + napi_queue_async_work(env, ctx->asyncWork); + if (ctx->asyncType == ASYNC_PROMISE) { + return ctx->promise; + } else { + napi_value result = nullptr; + napi_get_null(env, &result); + return result; + } +} + +static napi_value NewVerifyJsUpdateAsyncWork(napi_env env, VerifyUpdateCtx *ctx) +{ + napi_value resourceName = nullptr; + napi_create_string_utf8(env, "update", NAPI_AUTO_LENGTH, &resourceName); + + napi_create_async_work( + env, nullptr, resourceName, + [](napi_env env, void *data) { + VerifyJsUpdateAsyncWorkProcess(env, data); + return; + }, + [](napi_env env, napi_status status, void *data) { + VerifyJsUpdateAsyncWorkReturn(env, status, data); + return; + }, + (void *)ctx, + &ctx->asyncWork); + + napi_queue_async_work(env, ctx->asyncWork); + if (ctx->asyncType == ASYNC_PROMISE) { + return ctx->promise; + } else { + napi_value result = nullptr; + napi_get_null(env, &result); + return result; + } +} + +static napi_value NewVerifyJsDoFinalAsyncWork(napi_env env, VerifyDoFinalCtx *ctx) +{ + napi_value resourceName = nullptr; + napi_create_string_utf8(env, "verify", NAPI_AUTO_LENGTH, &resourceName); + + napi_create_async_work( + env, nullptr, resourceName, + [](napi_env env, void *data) { + VerifyJsDoFinalAsyncWorkProcess(env, data); + return; + }, + [](napi_env env, napi_status status, void *data) { + VerifyJsDoFinalAsyncWorkReturn(env, status, data); + return; + }, + (void *)ctx, + &ctx->asyncWork); + + napi_queue_async_work(env, ctx->asyncWork); + if (ctx->asyncType == ASYNC_PROMISE) { + return ctx->promise; + } else { + napi_value result = nullptr; + napi_get_null(env, &result); + return result; + } +} + +NapiVerify::NapiVerify(HcfVerify *verify) +{ + this->verify_ = verify; +} + +NapiVerify::~NapiVerify() +{ + OH_HCF_ObjDestroy(this->verify_); +} + +HcfVerify *NapiVerify::GetVerify() +{ + return this->verify_; +} + +napi_value NapiVerify::JsInit(napi_env env, napi_callback_info info) +{ + LOGI("enter ..."); + VerifyInitCtx *ctx = (VerifyInitCtx *)HcfMalloc(sizeof(VerifyInitCtx), 0); + if (ctx == NULL) { + LOGE("create context fail."); + return NULL; + } + + if (!BuildVerifyJsInitCtx(env, info, ctx)) { + LOGE("build context fail."); + FreeVerifyInitCtx(env, ctx); + return nullptr; + } + + return NewVerifyJsInitAsyncWork(env, ctx); +} + +napi_value NapiVerify::JsUpdate(napi_env env, napi_callback_info info) +{ + LOGI("enter ..."); + VerifyUpdateCtx *ctx = (VerifyUpdateCtx *)HcfMalloc(sizeof(VerifyUpdateCtx), 0); + if (ctx == NULL) { + LOGE("create context fail."); + return NULL; + } + + if (!BuildVerifyJsUpdateCtx(env, info, ctx)) { + LOGE("build context fail."); + FreeVerifyUpdateCtx(env, ctx); + return nullptr; + } + + return NewVerifyJsUpdateAsyncWork(env, ctx); +} + +napi_value NapiVerify::JsVerify(napi_env env, napi_callback_info info) +{ + LOGI("enter ..."); + VerifyDoFinalCtx *ctx = (VerifyDoFinalCtx *)HcfMalloc(sizeof(VerifyDoFinalCtx), 0); + if (ctx == NULL) { + LOGE("create context fail."); + return NULL; + } + + if (!BuildVerifyJsDoFinalCtx(env, info, ctx)) { + LOGE("build context fail."); + FreeVerifyDoFinalCtx(env, ctx); + return nullptr; + } + + return NewVerifyJsDoFinalAsyncWork(env, ctx); +} + +napi_value NapiVerify::VerifyConstructor(napi_env env, napi_callback_info info) +{ + LOGI("enter ..."); + + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + + LOGI("out ..."); + return thisVar; +} + +napi_value NapiVerify::CreateJsVerify(napi_env env, napi_callback_info info) +{ + LOGI("enter ..."); + size_t exceptedArgc = PARAMS_NUM_ONE; + size_t argc; + napi_value argv[PARAMS_NUM_ONE] = { nullptr }; + napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); + + if (argc != exceptedArgc) { + LOGE("The input args num is invalid."); + return nullptr; + } + + napi_value instance; + napi_value constructor = nullptr; + napi_get_reference_value(env, classRef_, &constructor); + napi_new_instance(env, constructor, argc, argv, &instance); + + std::string algName; + if (!GetStringFromJSParams(env, argv[0], algName)) { + LOGE("failed to get algoName."); + return nullptr; + } + + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate(algName.c_str(), &verify); + if (res != HCF_SUCCESS) { + LOGE("create c verify fail."); + return nullptr; + } + + NapiVerify *napiVerify = new NapiVerify(verify); + + napi_wrap( + env, instance, napiVerify, + [](napi_env env, void *data, void *hint) { + NapiVerify *napiVerify = (NapiVerify *)(data); + delete napiVerify; + return; + }, + nullptr, + nullptr); + + napi_value napiAlgName = nullptr; + napi_create_string_utf8(env, algName.c_str(), NAPI_AUTO_LENGTH, &napiAlgName); + napi_set_named_property(env, instance, CRYPTO_TAG_ALG_NAME.c_str(), napiAlgName); + + LOGI("out ..."); + return instance; +} + +void NapiVerify::DefineVerifyJSClass(napi_env env, napi_value exports) +{ + napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("createVerify", NapiVerify::CreateJsVerify), + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); + + napi_property_descriptor classDesc[] = { + DECLARE_NAPI_FUNCTION("init", NapiVerify::JsInit), + DECLARE_NAPI_FUNCTION("update", NapiVerify::JsUpdate), + DECLARE_NAPI_FUNCTION("verify", NapiVerify::JsVerify), + }; + napi_value constructor = nullptr; + napi_define_class(env, "Verify", NAPI_AUTO_LENGTH, NapiVerify::VerifyConstructor, nullptr, + sizeof(classDesc) / sizeof(classDesc[0]), classDesc, &constructor); + napi_create_reference(env, constructor, 1, &classRef_); +} +} // CryptoFramework +} // OHOS diff --git a/frameworks/js/napi/src/napi_x509_certificate.cpp b/frameworks/js/napi/src/napi_x509_certificate.cpp new file mode 100644 index 0000000..3e24823 --- /dev/null +++ b/frameworks/js/napi/src/napi_x509_certificate.cpp @@ -0,0 +1,1181 @@ +/* + * Copyright (c) 2022 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 "napi_x509_certificate.h" + +#include "napi/native_node_api.h" +#include "napi/native_api.h" +#include "log.h" +#include "memory.h" +#include "utils.h" +#include "object_base.h" +#include "result.h" +#include "napi_crypto_framework_defines.h" +#include "napi_pub_key.h" +#include "napi_utils.h" + +namespace OHOS { +namespace CryptoFramework { + +napi_ref NapiX509Cert::classRef_ = nullptr; + +struct CfCtx { + CfAsyncType asyncType = ASYNC_TYPE_CALLBACK; + napi_value promise = nullptr; + napi_ref callback = nullptr; + napi_deferred deferred = nullptr; + napi_async_work asyncWork = nullptr; + + HcfEncodingBlob *encodingBlob = nullptr; + NapiX509Cert *certClass = nullptr; + HcfPubKey *pubKey = nullptr; + std::string date; + + int32_t errCode = 0; + const char *errMsg = nullptr; + HcfX509Certificate *cert; + HcfEncodingBlob *encoded = nullptr; + HcfPubKey *returnPubKey = nullptr; +}; + +NapiX509Cert::NapiX509Cert(HcfX509Certificate *x509Cert) +{ + this->x509Cert_ = x509Cert; +} + +NapiX509Cert::~NapiX509Cert() +{ + OH_HCF_ObjDestroy(this->x509Cert_); +} + +static void FreeCryptoFwkCtx(napi_env env, CfCtx *context) +{ + if (context == nullptr) { + return; + } + + if (context->asyncWork != nullptr) { + napi_delete_async_work(env, context->asyncWork); + } + + if (context->callback != nullptr) { + napi_delete_reference(env, context->callback); + } + + HcfEncodingBlobDataFree(context->encodingBlob); + HcfFree(context->encodingBlob); + context->encodingBlob = nullptr; + + HcfEncodingBlobDataFree(context->encoded); + HcfFree(context->encoded); + context->encoded = nullptr; + + HcfFree(context); + context = nullptr; +} + +static void ReturnCallbackResult(napi_env env, CfCtx *context, napi_value result) +{ + napi_value businessError = nullptr; + if (context->errCode != HCF_SUCCESS) { + businessError = GenerateBusinessError(env, context->errCode, context->errMsg); + } + napi_value params[ARGS_SIZE_TWO] = { businessError, result }; + + napi_value func = nullptr; + napi_get_reference_value(env, context->callback, &func); + + napi_value recv = nullptr; + napi_value callFuncRet = nullptr; + napi_get_undefined(env, &recv); + napi_call_function(env, recv, func, ARGS_SIZE_TWO, params, &callFuncRet); +} + +static void ReturnPromiseResult(napi_env env, CfCtx *context, napi_value result) +{ + if (context->errCode == HCF_SUCCESS) { + napi_resolve_deferred(env, context->deferred, result); + } else { + napi_reject_deferred(env, context->deferred, GenerateBusinessError(env, context->errCode, context->errMsg)); + } +} + +static void ReturnResult(napi_env env, CfCtx *context, napi_value result) +{ + if (context->asyncType == ASYNC_TYPE_CALLBACK) { + ReturnCallbackResult(env, context, result); + } else { + ReturnPromiseResult(env, context, result); + } +} + +static bool CreateCallbackAndPromise(napi_env env, CfCtx *context, size_t argc, + size_t maxCount, napi_value callbackValue) +{ + context->asyncType = (argc == maxCount) ? ASYNC_TYPE_CALLBACK : ASYNC_TYPE_PROMISE; + if (context->asyncType == ASYNC_TYPE_CALLBACK) { + if (!GetCallbackFromJSParams(env, callbackValue, &context->callback)) { + LOGE("get callback failed!"); + return false; + } + } else { + napi_create_promise(env, &context->deferred, &context->promise); + } + return true; +} + +static void VerifyExecute(napi_env env, void *data) +{ + LOGI("start to verify."); + CfCtx *context = static_cast(data); + HcfX509Certificate *cert = context->certClass->GetX509Cert(); + context->errCode = cert->base.verify((HcfCertificate *)cert, context->pubKey); + if (context->errCode != HCF_SUCCESS) { + LOGE("verify cert failed!"); + context->errMsg = "verify cert failed"; + } +} + +static void VerifyComplete(napi_env env, napi_status status, void *data) +{ + CfCtx *context = static_cast(data); + ReturnResult(env, context, NapiGetNull(env)); + FreeCryptoFwkCtx(env, context); +} + +static void checkValidityWithDateExecute(napi_env env, void *data) +{ + LOGI("start to check validity."); + CfCtx *context = static_cast(data); + HcfX509Certificate *cert = context->certClass->GetX509Cert(); + context->errCode = cert->checkValidityWithDate(cert, context->date.c_str()); + if (context->errCode != HCF_SUCCESS) { + LOGE("check cert validity failed!"); + context->errMsg = "check cert validity failed"; + } +} + +static void checkValidityWithDateComplete(napi_env env, napi_status status, void *data) +{ + CfCtx *context = static_cast(data); + ReturnResult(env, context, NapiGetNull(env)); + FreeCryptoFwkCtx(env, context); +} + +static void GetEncodedExecute(napi_env env, void *data) +{ + CfCtx *context = static_cast(data); + HcfX509Certificate *cert = context->certClass->GetX509Cert(); + HcfEncodingBlob *encodingBlob = (HcfEncodingBlob *)HcfMalloc(sizeof(HcfEncodingBlob), 0); + if (encodingBlob == nullptr) { + LOGE("malloc encoding blob failed!"); + context->errCode = HCF_ERR_MALLOC; + context->errMsg = "malloc encoding blob failed"; + return; + } + context->errCode = cert->base.getEncoded((HcfCertificate *)cert, encodingBlob); + if (context->errCode != HCF_SUCCESS) { + LOGE("get cert encoded failed!"); + context->errMsg = "get cert encoded failed"; + } + context->encoded = encodingBlob; +} + +static void GetEncodedComplete(napi_env env, napi_status status, void *data) +{ + CfCtx *context = static_cast(data); + if (context->errCode != HCF_SUCCESS) { + ReturnResult(env, context, nullptr); + FreeCryptoFwkCtx(env, context); + return; + } + napi_value returnEncodingBlob = ConvertEncodingBlobToNapiValue(env, context->encoded); + ReturnResult(env, context, returnEncodingBlob); + FreeCryptoFwkCtx(env, context); +} + +void GetPublicKeyExecute(napi_env env, void *data) +{ + CfCtx *context = static_cast(data); + HcfX509Certificate *cert = context->certClass->GetX509Cert(); + context->errCode = cert->base.getPublicKey((HcfCertificate *)cert, &context->returnPubKey); + if (context->errCode != HCF_SUCCESS) { + LOGE("get cert public key failed!"); + context->errMsg = "get cert public key failed"; + } +} + +void GetPublicKeyComplete(napi_env env, napi_status status, void *data) +{ + CfCtx *context = static_cast(data); + if (context->errCode != HCF_SUCCESS) { + ReturnResult(env, context, nullptr); + FreeCryptoFwkCtx(env, context); + return; + } + NapiPubKey *pubKeyClass = new NapiPubKey(context->returnPubKey); + napi_value instance = pubKeyClass->ConvertToJsPubKey(env); + napi_wrap( + env, instance, pubKeyClass, + [](napi_env env, void *data, void *hint) { + NapiPubKey *pubKeyClass = (NapiPubKey *)data; + delete pubKeyClass; + return; + }, + nullptr, nullptr); + ReturnResult(env, context, instance); + FreeCryptoFwkCtx(env, context); +} + +napi_value NapiX509Cert::Verify(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_TWO; + napi_value argv[ARGS_SIZE_TWO] = { 0 }; + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_TWO, false)) { + return nullptr; + } + + CfCtx *context = (CfCtx *)HcfMalloc(sizeof(CfCtx), 0); + if (context == nullptr) { + LOGE("malloc context failed!"); + return nullptr; + } + context->certClass = this; + + NapiPubKey *pubKey = nullptr; + napi_unwrap(env, argv[PARAM0], (void**)&pubKey); + if (pubKey == nullptr) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "public key is null")); + LOGE("pubKey is null!"); + FreeCryptoFwkCtx(env, context); + return nullptr; + } + context->pubKey = pubKey->GetPubKey(); + + if (!CreateCallbackAndPromise(env, context, argc, ARGS_SIZE_TWO, argv[PARAM1])) { + FreeCryptoFwkCtx(env, context); + return nullptr; + } + + napi_create_async_work( + env, nullptr, GetResourceName(env, "Verify"), + VerifyExecute, + VerifyComplete, + (void *)context, + &context->asyncWork); + + napi_queue_async_work(env, context->asyncWork); + if (context->asyncType == ASYNC_TYPE_PROMISE) { + return context->promise; + } else { + return NapiGetNull(env); + } +} + +napi_value NapiX509Cert::GetEncoded(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_ONE; + napi_value argv[ARGS_SIZE_ONE] = { 0 }; + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ONE, false)) { + return nullptr; + } + + CfCtx *context = (CfCtx *)HcfMalloc(sizeof(CfCtx), 0); + if (context == nullptr) { + LOGE("malloc context failed!"); + return nullptr; + } + context->certClass = this; + + if (!CreateCallbackAndPromise(env, context, argc, ARGS_SIZE_ONE, argv[PARAM0])) { + FreeCryptoFwkCtx(env, context); + return nullptr; + } + + napi_create_async_work( + env, nullptr, GetResourceName(env, "GetEncoded"), + GetEncodedExecute, + GetEncodedComplete, + (void *)context, + &context->asyncWork); + + napi_queue_async_work(env, context->asyncWork); + if (context->asyncType == ASYNC_TYPE_PROMISE) { + return context->promise; + } else { + return NapiGetNull(env); + } +} + +napi_value NapiX509Cert::GetPublicKey(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_ONE; + napi_value argv[ARGS_SIZE_ONE] = { 0 }; + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ONE, false)) { + return nullptr; + } + + CfCtx *context = (CfCtx *)HcfMalloc(sizeof(CfCtx), 0); + if (context == nullptr) { + LOGE("malloc context failed!"); + return nullptr; + } + context->certClass = this; + + if (!CreateCallbackAndPromise(env, context, argc, ARGS_SIZE_ONE, argv[PARAM0])) { + FreeCryptoFwkCtx(env, context); + return nullptr; + } + + napi_create_async_work( + env, nullptr, GetResourceName(env, "GetPublicKey"), + GetPublicKeyExecute, + GetPublicKeyComplete, + (void *)context, + &context->asyncWork); + + napi_queue_async_work(env, context->asyncWork); + if (context->asyncType == ASYNC_TYPE_PROMISE) { + return context->promise; + } else { + return NapiGetNull(env); + } +} + +napi_value NapiX509Cert::CheckValidityWithDate(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_TWO; + napi_value argv[ARGS_SIZE_TWO] = { 0 }; + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_TWO, false)) { + return nullptr; + } + + CfCtx *context = (CfCtx *)HcfMalloc(sizeof(CfCtx), 0); + if (context == nullptr) { + LOGE("malloc context failed!"); + return nullptr; + } + context->certClass = this; + + if (!GetStringFromJSParams(env, argv[PARAM0], context->date)) { + LOGE("get date param failed!"); + FreeCryptoFwkCtx(env, context); + return nullptr; + } + + if (!CreateCallbackAndPromise(env, context, argc, ARGS_SIZE_TWO, argv[PARAM1])) { + FreeCryptoFwkCtx(env, context); + return nullptr; + } + + napi_create_async_work( + env, nullptr, GetResourceName(env, "CheckValidityWithDate"), + checkValidityWithDateExecute, + checkValidityWithDateComplete, + (void *)context, + &context->asyncWork); + + napi_queue_async_work(env, context->asyncWork); + if (context->asyncType == ASYNC_TYPE_PROMISE) { + return context->promise; + } else { + return NapiGetNull(env); + } +} + +napi_value NapiX509Cert::GetVersion(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_ZERO; + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, &argc, nullptr, &thisVar, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ZERO, true)) { + return nullptr; + } + HcfX509Certificate *cert = GetX509Cert(); + int version = cert->getVersion(cert); + napi_value result = nullptr; + napi_create_int32(env, version, &result); + return result; +} + + +napi_value NapiX509Cert::GetSerialNumber(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_ZERO; + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, &argc, nullptr, &thisVar, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ZERO, true)) { + return nullptr; + } + HcfX509Certificate *cert = GetX509Cert(); + long serialNumber = cert->getSerialNumber(cert); + napi_value result = nullptr; + napi_create_int64(env, serialNumber, &result); + return result; +} + +napi_value NapiX509Cert::GetIssuerName(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_ZERO; + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, &argc, nullptr, &thisVar, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ZERO, true)) { + return nullptr; + } + + HcfBlob *blob = (HcfBlob *)HcfMalloc(sizeof(HcfBlob), 0); + if (blob == nullptr) { + LOGE("malloc blob failed!"); + return nullptr; + } + HcfX509Certificate *cert = GetX509Cert(); + HcfResult ret = cert->getIssuerName(cert, blob); + if (ret != HCF_SUCCESS) { + napi_throw(env, GenerateBusinessError(env, ret, "get issuer name failed")); + LOGE("getIssuerName failed!"); + HcfFree(blob); + blob = nullptr; + return nullptr; + } + napi_value returnValue = ConvertBlobToNapiValue(env, blob); + HcfBlobDataFree(blob); + HcfFree(blob); + blob = nullptr; + return returnValue; +} + +napi_value NapiX509Cert::GetSubjectName(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_ZERO; + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, &argc, nullptr, &thisVar, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ZERO, true)) { + return nullptr; + } + + HcfBlob *blob = (HcfBlob *)HcfMalloc(sizeof(HcfBlob), 0); + if (blob == nullptr) { + LOGE("malloc blob failed!"); + return nullptr; + } + HcfX509Certificate *cert = GetX509Cert(); + HcfResult ret = cert->getSubjectName(cert, blob); + if (ret != HCF_SUCCESS) { + napi_throw(env, GenerateBusinessError(env, ret, "get subject name failed")); + LOGE("getSubjectName failed!"); + HcfFree(blob); + blob = nullptr; + return nullptr; + } + napi_value returnValue = ConvertBlobToNapiValue(env, blob); + HcfBlobDataFree(blob); + HcfFree(blob); + blob = nullptr; + return returnValue; +} + +napi_value NapiX509Cert::GetNotBeforeTime(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_ZERO; + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, &argc, nullptr, &thisVar, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ZERO, true)) { + return nullptr; + } + + HcfBlob *blob = (HcfBlob *)HcfMalloc(sizeof(HcfBlob), 0); + if (blob == nullptr) { + LOGE("malloc blob failed!"); + return nullptr; + } + HcfX509Certificate *cert = GetX509Cert(); + HcfResult res = cert->getNotBeforeTime(cert, blob); + if (res != HCF_SUCCESS) { + napi_throw(env, GenerateBusinessError(env, res, "get not before time failed")); + LOGE("getNotBeforeTime failed!"); + HcfFree(blob); + blob = nullptr; + return nullptr; + } + napi_value result = nullptr; + napi_create_string_utf8(env, (char *)blob->data, blob->len, &result); + HcfBlobDataFree(blob); + HcfFree(blob); + blob = nullptr; + return result; +} + +napi_value NapiX509Cert::GetNotAfterTime(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_ZERO; + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, &argc, nullptr, &thisVar, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ZERO, true)) { + return nullptr; + } + + HcfBlob *blob = (HcfBlob *)HcfMalloc(sizeof(HcfBlob), 0); + if (blob == nullptr) { + LOGE("malloc blob failed!"); + return nullptr; + } + HcfX509Certificate *cert = GetX509Cert(); + HcfResult res = cert->getNotAfterTime(cert, blob); + if (res != HCF_SUCCESS) { + napi_throw(env, GenerateBusinessError(env, res, "get not after time failed")); + LOGE("getNotAfterTime failed!"); + HcfFree(blob); + blob = nullptr; + return nullptr; + } + napi_value result = nullptr; + napi_create_string_utf8(env, (char *)blob->data, blob->len, &result); + HcfBlobDataFree(blob); + HcfFree(blob); + blob = nullptr; + return result; +} + +napi_value NapiX509Cert::GetSignature(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_ZERO; + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, &argc, nullptr, &thisVar, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ZERO, true)) { + return nullptr; + } + + HcfBlob *blob = (HcfBlob *)HcfMalloc(sizeof(HcfBlob), 0); + if (blob == nullptr) { + LOGE("malloc blob failed!"); + return nullptr; + } + HcfX509Certificate *cert = GetX509Cert(); + HcfResult ret = cert->getSignature(cert, blob); + if (ret != HCF_SUCCESS) { + napi_throw(env, GenerateBusinessError(env, ret, "get signature failed")); + LOGE("getSignature failed!"); + HcfFree(blob); + blob = nullptr; + return nullptr; + } + napi_value returnValue = ConvertBlobToNapiValue(env, blob); + HcfBlobDataFree(blob); + HcfFree(blob); + blob = nullptr; + return returnValue; +} + +napi_value NapiX509Cert::GetSigAlgName(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_ZERO; + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, &argc, nullptr, &thisVar, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ZERO, true)) { + return nullptr; + } + + HcfBlob *blob = (HcfBlob *)HcfMalloc(sizeof(HcfBlob), 0); + if (blob == nullptr) { + LOGE("malloc blob failed!"); + return nullptr; + } + HcfX509Certificate *cert = GetX509Cert(); + HcfResult res = cert->getSignatureAlgName(cert, blob); + if (res != HCF_SUCCESS) { + napi_throw(env, GenerateBusinessError(env, res, "get signature alg name failed")); + LOGE("getSignatureAlgName failed!"); + HcfFree(blob); + blob = nullptr; + return nullptr; + } + napi_value result = nullptr; + napi_create_string_utf8(env, (char *)blob->data, blob->len, &result); + HcfBlobDataFree(blob); + HcfFree(blob); + blob = nullptr; + return result; +} + +napi_value NapiX509Cert::GetSigAlgOID(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_ZERO; + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, &argc, nullptr, &thisVar, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ZERO, true)) { + return nullptr; + } + HcfBlob *blob = (HcfBlob *)HcfMalloc(sizeof(HcfBlob), 0); + if (blob == nullptr) { + LOGE("malloc blob failed!"); + return nullptr; + } + HcfX509Certificate *cert = GetX509Cert(); + HcfResult res = cert->getSignatureAlgOid(cert, blob); + if (res != HCF_SUCCESS) { + napi_throw(env, GenerateBusinessError(env, res, "get signature alg oid failed")); + LOGE("getSignatureAlgOid failed!"); + HcfFree(blob); + blob = nullptr; + return nullptr; + } + napi_value result = nullptr; + napi_create_string_utf8(env, (char *)blob->data, blob->len, &result); + HcfBlobDataFree(blob); + HcfFree(blob); + blob = nullptr; + return result; +} + +napi_value NapiX509Cert::GetSigAlgParams(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_ZERO; + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, &argc, nullptr, &thisVar, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ZERO, true)) { + return nullptr; + } + + HcfBlob *blob = (HcfBlob *)HcfMalloc(sizeof(HcfBlob), 0); + if (blob == nullptr) { + LOGE("malloc blob failed!"); + return nullptr; + } + HcfX509Certificate *cert = GetX509Cert(); + HcfResult ret = cert->getSignatureAlgParams(cert, blob); + if (ret != HCF_SUCCESS) { + napi_throw(env, GenerateBusinessError(env, ret, "get signature alg params failed")); + LOGE("getSignatureAlgParams failed!"); + HcfFree(blob); + blob = nullptr; + return nullptr; + } + napi_value returnValue = ConvertBlobToNapiValue(env, blob); + HcfBlobDataFree(blob); + HcfFree(blob); + blob = nullptr; + return returnValue; +} + +napi_value NapiX509Cert::GetKeyUsage(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_ZERO; + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, &argc, nullptr, &thisVar, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ZERO, true)) { + return nullptr; + } + HcfBlob *blob = (HcfBlob *)HcfMalloc(sizeof(HcfBlob), 0); + if (blob == nullptr) { + LOGE("malloc blob failed!"); + return nullptr; + } + HcfX509Certificate *cert = GetX509Cert(); + HcfResult ret = cert->getKeyUsage(cert, blob); + if (ret != HCF_SUCCESS) { + napi_throw(env, GenerateBusinessError(env, ret, "get key usage failed")); + LOGE("getKeyUsage failed!"); + HcfFree(blob); + blob = nullptr; + return nullptr; + } + napi_value returnValue = ConvertBlobToNapiValue(env, blob); + HcfBlobDataFree(blob); + HcfFree(blob); + blob = nullptr; + return returnValue; +} + +napi_value NapiX509Cert::GetExtendedKeyUsage(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_ZERO; + napi_get_cb_info(env, info, &argc, nullptr, nullptr, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ZERO, true)) { + return nullptr; + } + + HcfArray *array = (HcfArray *)HcfMalloc(sizeof(HcfArray), 0); + if (array == nullptr) { + LOGE("malloc array failed!"); + return nullptr; + } + HcfX509Certificate *cert = GetX509Cert(); + HcfResult ret = cert->getExtKeyUsage(cert, array); + if (ret != HCF_SUCCESS) { + napi_throw(env, GenerateBusinessError(env, ret, "get ext key usage failed")); + LOGE("call getExtKeyUsage failed!"); + HcfFree(array); + array = nullptr; + return nullptr; + } + napi_value returnValue = ConvertArrayToNapiValue(env, array); + HcfArrayDataClearAndFree(array); + HcfFree(array); + array = nullptr; + return returnValue; +} + + +napi_value NapiX509Cert::GetBasicConstraints(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_ZERO; + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, &argc, nullptr, &thisVar, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ZERO, true)) { + return nullptr; + } + + HcfX509Certificate *cert = GetX509Cert(); + int32_t constrains = cert->getBasicConstraints(cert); + napi_value result = nullptr; + napi_create_int32(env, constrains, &result); + return result; +} + +napi_value NapiX509Cert::GetSubjectAlternativeNames(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_ZERO; + napi_get_cb_info(env, info, &argc, nullptr, nullptr, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ZERO, true)) { + return nullptr; + } + + HcfArray *array = (HcfArray *)HcfMalloc(sizeof(HcfArray), 0); + if (array == nullptr) { + LOGE("malloc array failed!"); + return nullptr; + } + HcfX509Certificate *cert = GetX509Cert(); + HcfResult ret = cert->getSubjectAltNames(cert, array); + if (ret != HCF_SUCCESS) { + napi_throw(env, GenerateBusinessError(env, ret, "get subject alt names failed")); + LOGE("call getSubjectAltNames failed!"); + HcfFree(array); + array = nullptr; + return nullptr; + } + napi_value returnValue = ConvertArrayToNapiValue(env, array); + HcfArrayDataClearAndFree(array); + HcfFree(array); + array = nullptr; + return returnValue; +} + +napi_value NapiX509Cert::GetIssuerAlternativeNames(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_ZERO; + napi_get_cb_info(env, info, &argc, nullptr, nullptr, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ZERO, true)) { + return nullptr; + } + + HcfArray *array = (HcfArray *)HcfMalloc(sizeof(HcfArray), 0); + if (array == nullptr) { + LOGE("malloc array failed!"); + return nullptr; + } + HcfX509Certificate *cert = GetX509Cert(); + HcfResult ret = cert->getIssuerAltNames(cert, array); + if (ret != HCF_SUCCESS) { + napi_throw(env, GenerateBusinessError(env, ret, "get issuer alt names failed")); + LOGE("call getIssuerAltNames failed!"); + HcfFree(array); + array = nullptr; + return nullptr; + } + napi_value returnValue = ConvertArrayToNapiValue(env, array); + HcfArrayDataClearAndFree(array); + HcfFree(array); + array = nullptr; + return returnValue; +} + +static napi_value NapiVerify(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509Cert *x509Cert = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509Cert)); + if (x509Cert == nullptr) { + LOGE("x509Cert is nullptr!"); + return nullptr; + } + return x509Cert->Verify(env, info); +} + +static napi_value NapiGetEncoded(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509Cert *x509Cert = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509Cert)); + if (x509Cert == nullptr) { + LOGE("x509Cert is nullptr!"); + return nullptr; + } + return x509Cert->GetEncoded(env, info); +} + +static napi_value NapiGetPublicKey(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509Cert *x509Cert = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509Cert)); + if (x509Cert == nullptr) { + LOGE("x509Cert is nullptr!"); + return nullptr; + } + return x509Cert->GetPublicKey(env, info); +} + +static napi_value NapiCheckValidityWithDate(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509Cert *x509Cert = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509Cert)); + if (x509Cert == nullptr) { + LOGE("x509Cert is nullptr!"); + return nullptr; + } + return x509Cert->CheckValidityWithDate(env, info); +} + +static napi_value NapiGetVersion(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509Cert *x509Cert = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509Cert)); + if (x509Cert == nullptr) { + LOGE("x509Cert is nullptr!"); + return nullptr; + } + return x509Cert->GetVersion(env, info); +} + +static napi_value NapiGetSerialNumber(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509Cert *x509Cert = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509Cert)); + if (x509Cert == nullptr) { + LOGE("x509Cert is nullptr!"); + return nullptr; + } + return x509Cert->GetSerialNumber(env, info); +} + +static napi_value NapiGetIssuerName(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509Cert *x509Cert = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509Cert)); + if (x509Cert == nullptr) { + LOGE("x509Cert is nullptr!"); + return nullptr; + } + return x509Cert->GetIssuerName(env, info); +} + +static napi_value NapiGetSubjectName(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509Cert *x509Cert = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509Cert)); + if (x509Cert == nullptr) { + LOGE("x509Cert is nullptr!"); + return nullptr; + } + return x509Cert->GetSubjectName(env, info); +} + +static napi_value NapiGetNotBeforeTime(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509Cert *x509Cert = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509Cert)); + if (x509Cert == nullptr) { + LOGE("x509Cert is nullptr!"); + return nullptr; + } + return x509Cert->GetNotBeforeTime(env, info); +} + +static napi_value NapiGetNotAfterTime(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509Cert *x509Cert = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509Cert)); + if (x509Cert == nullptr) { + LOGE("x509Cert is nullptr!"); + return nullptr; + } + return x509Cert->GetNotAfterTime(env, info); +} + +static napi_value NapiGetSignature(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509Cert *x509Cert = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509Cert)); + if (x509Cert == nullptr) { + LOGE("x509Cert is nullptr!"); + return nullptr; + } + return x509Cert->GetSignature(env, info); +} + +static napi_value NapiGetSigAlgName(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509Cert *x509Cert = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509Cert)); + if (x509Cert == nullptr) { + LOGE("x509Cert is nullptr!"); + return nullptr; + } + return x509Cert->GetSigAlgName(env, info); +} + +static napi_value NapiGetSigAlgOID(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509Cert *x509Cert = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509Cert)); + if (x509Cert == nullptr) { + LOGE("x509Cert is nullptr!"); + return nullptr; + } + return x509Cert->GetSigAlgOID(env, info); +} + +static napi_value NapiGetSigAlgParams(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509Cert *x509Cert = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509Cert)); + if (x509Cert == nullptr) { + LOGE("x509Cert is nullptr!"); + return nullptr; + } + return x509Cert->GetSigAlgParams(env, info); +} + +static napi_value NapiGetKeyUsage(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509Cert *x509Cert = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509Cert)); + if (x509Cert == nullptr) { + LOGE("x509Cert is nullptr!"); + return nullptr; + } + return x509Cert->GetKeyUsage(env, info); +} + +static napi_value NapiGetExtendedKeyUsage(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509Cert *x509Cert = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509Cert)); + if (x509Cert == nullptr) { + LOGE("x509Cert is nullptr!"); + return nullptr; + } + return x509Cert->GetExtendedKeyUsage(env, info); +} + +static napi_value NapiGetBasicConstraints(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509Cert *x509Cert = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509Cert)); + if (x509Cert == nullptr) { + LOGE("x509Cert is nullptr!"); + return nullptr; + } + return x509Cert->GetBasicConstraints(env, info); +} + +static napi_value NapiGetSubjectAlternativeNames(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509Cert *x509Cert = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509Cert)); + if (x509Cert == nullptr) { + LOGE("x509Cert is nullptr!"); + return nullptr; + } + return x509Cert->GetSubjectAlternativeNames(env, info); +} + +static napi_value NapiGetIssuerAlternativeNames(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509Cert *x509Cert = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509Cert)); + if (x509Cert == nullptr) { + LOGE("x509Cert is nullptr!"); + return nullptr; + } + return x509Cert->GetIssuerAlternativeNames(env, info); +} + +void NapiX509Cert::CreateX509CertExecute(napi_env env, void *data) +{ + CfCtx *context = static_cast(data); + context->errCode = HcfX509CertificateCreate(context->encodingBlob, &context->cert); +} + +void NapiX509Cert::CreateX509CertComplete(napi_env env, napi_status status, void *data) +{ + CfCtx *context = static_cast(data); + if (context->errCode != HCF_SUCCESS) { + LOGE("call create X509Cert failed!"); + ReturnResult(env, context, nullptr); + FreeCryptoFwkCtx(env, context); + return; + } + napi_value instance = CreateX509Cert(env); + NapiX509Cert *x509CertClass = new NapiX509Cert(context->cert); + napi_wrap( + env, instance, x509CertClass, + [](napi_env env, void *data, void *hint) { + NapiX509Cert *certClass = (NapiX509Cert *)data; + delete certClass; + return; + }, + nullptr, nullptr); + ReturnResult(env, context, instance); + FreeCryptoFwkCtx(env, context); +} + +napi_value NapiX509Cert::NapiCreateX509Cert(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_TWO; + napi_value argv[ARGS_SIZE_TWO] = { 0 }; + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_TWO, false)) { + return nullptr; + } + + CfCtx *context = (CfCtx *)HcfMalloc(sizeof(CfCtx), 0); + if (context == nullptr) { + LOGE("malloc context failed!"); + return nullptr; + } + if (!GetEncodingBlobFromValue(env, argv[PARAM0], &context->encodingBlob)) { + LOGE("get encoding blob from data failed!"); + FreeCryptoFwkCtx(env, context); + return nullptr; + } + + if (!CreateCallbackAndPromise(env, context, argc, ARGS_SIZE_TWO, argv[PARAM1])) { + FreeCryptoFwkCtx(env, context); + return nullptr; + } + + napi_create_async_work( + env, nullptr, GetResourceName(env, "CreateX509Cert"), + CreateX509CertExecute, + CreateX509CertComplete, + (void *)context, + &context->asyncWork); + + napi_queue_async_work(env, context->asyncWork); + if (context->asyncType == ASYNC_TYPE_PROMISE) { + return context->promise; + } else { + return NapiGetNull(env); + } +} + +static napi_value X509CertConstructor(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + return thisVar; +} + +void NapiX509Cert::DefineX509CertJSClass(napi_env env, napi_value exports) +{ + napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("createX509Cert", NapiCreateX509Cert), + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); + + napi_property_descriptor x509CertDesc[] = { + DECLARE_NAPI_FUNCTION("verify", NapiVerify), + DECLARE_NAPI_FUNCTION("getEncoded", NapiGetEncoded), + DECLARE_NAPI_FUNCTION("getPublicKey", NapiGetPublicKey), + DECLARE_NAPI_FUNCTION("checkValidityWithDate", NapiCheckValidityWithDate), + DECLARE_NAPI_FUNCTION("getVersion", NapiGetVersion), + DECLARE_NAPI_FUNCTION("getSerialNumber", NapiGetSerialNumber), + DECLARE_NAPI_FUNCTION("getIssuerName", NapiGetIssuerName), + DECLARE_NAPI_FUNCTION("getSubjectName", NapiGetSubjectName), + DECLARE_NAPI_FUNCTION("getNotBeforeTime", NapiGetNotBeforeTime), + DECLARE_NAPI_FUNCTION("getNotAfterTime", NapiGetNotAfterTime), + DECLARE_NAPI_FUNCTION("getSignature", NapiGetSignature), + DECLARE_NAPI_FUNCTION("getSignatureAlgName", NapiGetSigAlgName), + DECLARE_NAPI_FUNCTION("getSignatureAlgOid", NapiGetSigAlgOID), + DECLARE_NAPI_FUNCTION("getSignatureAlgParams", NapiGetSigAlgParams), + DECLARE_NAPI_FUNCTION("getKeyUsage", NapiGetKeyUsage), + DECLARE_NAPI_FUNCTION("getExtKeyUsage", NapiGetExtendedKeyUsage), + DECLARE_NAPI_FUNCTION("getBasicConstraints", NapiGetBasicConstraints), + DECLARE_NAPI_FUNCTION("getSubjectAltNames", NapiGetSubjectAlternativeNames), + DECLARE_NAPI_FUNCTION("getIssuerAltNames", NapiGetIssuerAlternativeNames), + }; + napi_value constructor = nullptr; + napi_define_class(env, "X509Cert", NAPI_AUTO_LENGTH, X509CertConstructor, nullptr, + sizeof(x509CertDesc) / sizeof(x509CertDesc[0]), x509CertDesc, &constructor); + napi_create_reference(env, constructor, 1, &classRef_); +} + +napi_value NapiX509Cert::CreateX509Cert(napi_env env) +{ + napi_value constructor = nullptr; + napi_value instance = nullptr; + napi_get_reference_value(env, classRef_, &constructor); + napi_new_instance(env, constructor, 0, nullptr, &instance); + return instance; +} + +} // namespace CryptoFramework +} // namespace OHOS diff --git a/frameworks/js/napi/src/napi_x509_crl.cpp b/frameworks/js/napi/src/napi_x509_crl.cpp new file mode 100644 index 0000000..e0e735f --- /dev/null +++ b/frameworks/js/napi/src/napi_x509_crl.cpp @@ -0,0 +1,1243 @@ +/* + * Copyright (c) 2022 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 "napi_x509_crl.h" + +#include "napi/native_node_api.h" +#include "napi/native_api.h" +#include "log.h" +#include "memory.h" +#include "utils.h" +#include "object_base.h" +#include "result.h" +#include "napi_crypto_framework_defines.h" +#include "napi_pub_key.h" +#include "napi_utils.h" +#include "napi_x509_certificate.h" +#include "napi_x509_crl_entry.h" + +namespace OHOS { +namespace CryptoFramework { + +napi_ref NapiX509Crl::classRef_ = nullptr; + +struct CfCtx { + CfAsyncType asyncType = ASYNC_TYPE_CALLBACK; + napi_value promise = nullptr; + napi_ref callback = nullptr; + napi_deferred deferred = nullptr; + napi_async_work asyncWork = nullptr; + + HcfEncodingBlob *encodingBlob = nullptr; + NapiX509Crl *crlClass = nullptr; + HcfX509Certificate *certificate = nullptr; + HcfPubKey *pubKey = nullptr; + int32_t serialNumber = 0; + + HcfX509CrlEntry *crlEntry = nullptr; + int32_t errCode = 0; + const char *errMsg = nullptr; + bool isRevoked = false; + HcfX509Crl *crl; + HcfEncodingBlob *encoded = nullptr; + HcfBlob *blob = nullptr; + HcfArray *array = nullptr; +}; + +static void FreeCryptoFwkCtx(napi_env env, CfCtx *context) +{ + if (context == nullptr) { + return; + } + + if (context->asyncWork != nullptr) { + napi_delete_async_work(env, context->asyncWork); + } + + if (context->callback != nullptr) { + napi_delete_reference(env, context->callback); + } + + HcfEncodingBlobDataFree(context->encodingBlob); + HcfFree(context->encodingBlob); + context->encodingBlob = nullptr; + + HcfEncodingBlobDataFree(context->encoded); + HcfFree(context->encoded); + context->encoded = nullptr; + + HcfBlobDataFree(context->blob); + HcfFree(context->blob); + context->blob = nullptr; + + if (context->array != nullptr) { + HcfFree(context->array->data); + context->array->data = nullptr; + HcfFree(context->array); + context->array = nullptr; + } + + HcfFree(context); + context = nullptr; +} + +static void ReturnCallbackResult(napi_env env, CfCtx *context, napi_value result) +{ + napi_value businessError = nullptr; + if (context->errCode != HCF_SUCCESS) { + businessError = GenerateBusinessError(env, context->errCode, context->errMsg); + } + napi_value params[ARGS_SIZE_TWO] = { businessError, result }; + + napi_value func = nullptr; + napi_get_reference_value(env, context->callback, &func); + + napi_value recv = nullptr; + napi_value callFuncRet = nullptr; + napi_get_undefined(env, &recv); + napi_call_function(env, recv, func, ARGS_SIZE_TWO, params, &callFuncRet); +} + +static void ReturnPromiseResult(napi_env env, CfCtx *context, napi_value result) +{ + if (context->errCode == HCF_SUCCESS) { + napi_resolve_deferred(env, context->deferred, result); + } else { + napi_reject_deferred(env, context->deferred, GenerateBusinessError(env, context->errCode, context->errMsg)); + } +} + +static void ReturnResult(napi_env env, CfCtx *context, napi_value result) +{ + if (context->asyncType == ASYNC_TYPE_CALLBACK) { + ReturnCallbackResult(env, context, result); + } else { + ReturnPromiseResult(env, context, result); + } +} + +static bool CreateCallbackAndPromise(napi_env env, CfCtx *context, size_t argc, + size_t maxCount, napi_value callbackValue) +{ + context->asyncType = (argc == maxCount) ? ASYNC_TYPE_CALLBACK : ASYNC_TYPE_PROMISE; + if (context->asyncType == ASYNC_TYPE_CALLBACK) { + if (!GetCallbackFromJSParams(env, callbackValue, &context->callback)) { + LOGE("get callback failed!"); + return false; + } + } else { + napi_create_promise(env, &context->deferred, &context->promise); + } + return true; +} + +NapiX509Crl::NapiX509Crl(HcfX509Crl *x509Crl) +{ + this->x509Crl_ = x509Crl; +} + +NapiX509Crl::~NapiX509Crl() +{ + OH_HCF_ObjDestroy(this->x509Crl_); +} + +void IsInvokedExecute(napi_env env, void *data) +{ + CfCtx *context = static_cast(data); + HcfX509Crl *x509Crl = context->crlClass->GetX509Crl(); + context->isRevoked = x509Crl->base.isRevoked((HcfCrl *)x509Crl, (HcfCertificate *)context->certificate); + context->errCode = HCF_SUCCESS; +} + +void IsInvokedComplete(napi_env env, napi_status status, void *data) +{ + CfCtx *context = static_cast(data); + napi_value result = nullptr; + if (context->isRevoked) { + napi_get_boolean(env, true, &result); + } else { + napi_get_boolean(env, false, &result); + } + ReturnResult(env, context, result); + FreeCryptoFwkCtx(env, context); +} + +static void GetEncodedExecute(napi_env env, void *data) +{ + CfCtx *context = static_cast(data); + HcfX509Crl *x509Crl = context->crlClass->GetX509Crl(); + HcfEncodingBlob *encodingBlob = (HcfEncodingBlob *)HcfMalloc(sizeof(HcfEncodingBlob), 0); + if (encodingBlob == nullptr) { + LOGE("malloc encoding blob failed!"); + context->errCode = HCF_ERR_MALLOC; + context->errMsg = "malloc encoding blob failed"; + return; + } + context->errCode = x509Crl->getEncoded(x509Crl, encodingBlob); + if (context->errCode != HCF_SUCCESS) { + LOGE("get encoded failed!"); + context->errMsg = "get encoded failed"; + } + context->encoded = encodingBlob; +} + +static void GetEncodedComplete(napi_env env, napi_status status, void *data) +{ + CfCtx *context = static_cast(data); + if (context->errCode != HCF_SUCCESS) { + ReturnResult(env, context, nullptr); + FreeCryptoFwkCtx(env, context); + return; + } + napi_value returnEncodingBlob = ConvertEncodingBlobToNapiValue(env, context->encoded); + ReturnResult(env, context, returnEncodingBlob); + FreeCryptoFwkCtx(env, context); +} + +static void VerifyExecute(napi_env env, void *data) +{ + CfCtx *context = static_cast(data); + HcfX509Crl *x509Crl = context->crlClass->GetX509Crl(); + context->errCode = x509Crl->verify(x509Crl, context->pubKey); + if (context->errCode != HCF_SUCCESS) { + LOGE("verify crl failed!"); + context->errMsg = "verify crl failed"; + } +} + +static void VerifyComplete(napi_env env, napi_status status, void *data) +{ + CfCtx *context = static_cast(data); + ReturnResult(env, context, NapiGetNull(env)); + FreeCryptoFwkCtx(env, context); +} + +void GetRevokedCertificateExecute(napi_env env, void *data) +{ + CfCtx *context = static_cast(data); + HcfX509Crl *x509Crl = context->crlClass->GetX509Crl(); + context->errCode = x509Crl->getRevokedCert(x509Crl, context->serialNumber, &context->crlEntry); + if (context->errCode != HCF_SUCCESS) { + LOGE("get revoked cert failed!"); + context->errMsg = "get revoked cert failed"; + } +} + +void GetRevokedCertificateComplete(napi_env env, napi_status status, void *data) +{ + CfCtx *context = static_cast(data); + if (context->errCode != HCF_SUCCESS) { + ReturnResult(env, context, nullptr); + FreeCryptoFwkCtx(env, context); + return; + } + napi_value instance = NapiX509CrlEntry::CreateX509CrlEntry(env); + NapiX509CrlEntry *x509CrlEntryClass = new NapiX509CrlEntry(context->crlEntry); + napi_wrap( + env, instance, x509CrlEntryClass, + [](napi_env env, void *data, void *hint) { + NapiX509CrlEntry *x509CrlEntryClass = (NapiX509CrlEntry *)data; + delete x509CrlEntryClass; + return; + }, + nullptr, nullptr); + ReturnResult(env, context, instance); + FreeCryptoFwkCtx(env, context); +} + +void GetRevokedCertificateWithCertExecute(napi_env env, void *data) +{ + CfCtx *context = static_cast(data); + HcfX509Crl *x509Crl = context->crlClass->GetX509Crl(); + context->errCode = x509Crl->getRevokedCertWithCert(x509Crl, context->certificate, &context->crlEntry); + if (context->errCode != HCF_SUCCESS) { + LOGE("get revoked cert with cert failed!"); + context->errMsg = "get revoked cert with cert failed"; + } +} + +void GetRevokedCertificateWithCertComplete(napi_env env, napi_status status, void *data) +{ + CfCtx *context = static_cast(data); + if (context->errCode != HCF_SUCCESS) { + ReturnResult(env, context, nullptr); + FreeCryptoFwkCtx(env, context); + return; + } + napi_value instance = NapiX509CrlEntry::CreateX509CrlEntry(env); + NapiX509CrlEntry *x509CrlEntryClass = new NapiX509CrlEntry(context->crlEntry); + napi_wrap( + env, instance, x509CrlEntryClass, + [](napi_env env, void *data, void *hint) { + NapiX509CrlEntry *x509CrlEntryClass = (NapiX509CrlEntry *)data; + delete x509CrlEntryClass; + return; + }, + nullptr, nullptr); + ReturnResult(env, context, instance); + FreeCryptoFwkCtx(env, context); +} + +void GetRevokedCertificatesExecute(napi_env env, void *data) +{ + CfCtx *context = static_cast(data); + HcfX509Crl *x509Crl = context->crlClass->GetX509Crl(); + HcfArray *array = (HcfArray *)HcfMalloc(sizeof(HcfArray), 0); + if (array == nullptr) { + LOGE("malloc array failed!"); + context->errCode = HCF_ERR_MALLOC; + context->errMsg = "malloc array failed"; + return; + } + context->errCode = x509Crl->getRevokedCerts(x509Crl, array); + if (context->errCode != HCF_SUCCESS) { + LOGE("get revoked certs failed!"); + context->errMsg = "get revoked certs failed"; + } + context->array = array; +} + +static napi_value GenerateCrlEntryArray(napi_env env, HcfArray *array) +{ + if (array == nullptr) { + LOGE("crl entry array is null!"); + return nullptr; + } + if (array->count == 0) { + LOGE("crl entry array count is 0!"); + return nullptr; + } + napi_value returnArray = nullptr; + napi_create_array(env, &returnArray); + for (uint32_t i = 0; i < array->count; i++) { + HcfBlob *blob = (HcfBlob *)(array->data + i); + HcfX509CrlEntry *entry = (HcfX509CrlEntry *)blob->data; + napi_value instance = NapiX509CrlEntry::CreateX509CrlEntry(env); + NapiX509CrlEntry *x509CrlEntryClass = new NapiX509CrlEntry(entry); + napi_wrap( + env, instance, x509CrlEntryClass, + [](napi_env env, void *data, void *hint) { + NapiX509CrlEntry *x509CrlEntryClass = (NapiX509CrlEntry *)data; + delete x509CrlEntryClass; + return; + }, + nullptr, nullptr); + napi_set_element(env, returnArray, i, instance); + } + return returnArray; +} + +void GetRevokedCertificatesComplete(napi_env env, napi_status status, void *data) +{ + CfCtx *context = static_cast(data); + if (context->errCode != HCF_SUCCESS) { + ReturnResult(env, context, nullptr); + FreeCryptoFwkCtx(env, context); + return; + } + napi_value returnArray = GenerateCrlEntryArray(env, context->array); + ReturnResult(env, context, returnArray); + FreeCryptoFwkCtx(env, context); +} + +void GetTBSCertListExecute(napi_env env, void *data) +{ + CfCtx *context = static_cast(data); + HcfX509Crl *x509Crl = context->crlClass->GetX509Crl(); + HcfBlob *blob = (HcfBlob *)HcfMalloc(sizeof(HcfBlob), 0); + if (blob == nullptr) { + LOGE("malloc blob failed!"); + context->errCode = HCF_ERR_MALLOC; + context->errMsg = "malloc blob failed"; + return; + } + context->errCode = x509Crl->getTbsInfo(x509Crl, blob); + if (context->errCode != HCF_SUCCESS) { + LOGE("get tbs info failed!"); + context->errMsg = "get tbs info failed"; + } + context->blob = blob; +} + +void GetTBSCertListComplete(napi_env env, napi_status status, void *data) +{ + CfCtx *context = static_cast(data); + if (context->errCode != HCF_SUCCESS) { + ReturnResult(env, context, nullptr); + FreeCryptoFwkCtx(env, context); + return; + } + napi_value returnBlob = ConvertBlobToNapiValue(env, context->blob); + ReturnResult(env, context, returnBlob); + FreeCryptoFwkCtx(env, context); +} + +napi_value NapiX509Crl::IsRevoked(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_TWO; + napi_value argv[ARGS_SIZE_TWO] = { 0 }; + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_TWO, false)) { + return nullptr; + } + + NapiX509Cert *x509Cert = nullptr; + napi_unwrap(env, argv[PARAM0], (void**)&x509Cert); + if (x509Cert == nullptr) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "x509 cert is null")); + LOGE("x509Cert is null!"); + return nullptr; + } + CfCtx *context = (CfCtx *)HcfMalloc(sizeof(CfCtx), 0); + if (context == nullptr) { + LOGE("malloc context failed!"); + return nullptr; + } + context->certificate = x509Cert->GetX509Cert(); + context->crlClass = this; + + if (!CreateCallbackAndPromise(env, context, argc, ARGS_SIZE_TWO, argv[PARAM1])) { + FreeCryptoFwkCtx(env, context); + return nullptr; + } + + napi_create_async_work( + env, nullptr, GetResourceName(env, "IsRevoked"), + IsInvokedExecute, + IsInvokedComplete, + (void *)context, + &context->asyncWork); + + napi_queue_async_work(env, context->asyncWork); + if (context->asyncType == ASYNC_TYPE_PROMISE) { + return context->promise; + } else { + return NapiGetNull(env); + } +} + +napi_value NapiX509Crl::GetType(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_ZERO; + napi_get_cb_info(env, info, &argc, nullptr, nullptr, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ZERO, true)) { + return nullptr; + } + + HcfX509Crl *x509Crl = GetX509Crl(); + const char *type = x509Crl->base.getType((HcfCrl *)x509Crl); + napi_value result = nullptr; + napi_create_string_utf8(env, type, strlen(type), &result); + return result; +} + +napi_value NapiX509Crl::GetEncoded(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_ONE; + napi_value argv[ARGS_SIZE_ONE] = { 0 }; + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ONE, false)) { + return nullptr; + } + + CfCtx *context = (CfCtx *)HcfMalloc(sizeof(CfCtx), 0); + if (context == nullptr) { + LOGE("malloc context failed!"); + return nullptr; + } + context->crlClass = this; + + if (!CreateCallbackAndPromise(env, context, argc, ARGS_SIZE_ONE, argv[PARAM0])) { + FreeCryptoFwkCtx(env, context); + return nullptr; + } + + napi_create_async_work( + env, nullptr, GetResourceName(env, "GetEncoded"), + GetEncodedExecute, + GetEncodedComplete, + (void *)context, + &context->asyncWork); + + napi_queue_async_work(env, context->asyncWork); + if (context->asyncType == ASYNC_TYPE_PROMISE) { + return context->promise; + } else { + return NapiGetNull(env); + } +} + +napi_value NapiX509Crl::Verify(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_TWO; + napi_value argv[ARGS_SIZE_TWO] = { 0 }; + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_TWO, false)) { + return nullptr; + } + + NapiPubKey *pubKey = nullptr; + napi_unwrap(env, argv[PARAM0], (void**)&pubKey); + if (pubKey == nullptr) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "public key is null")); + LOGE("pubKey is null!"); + return nullptr; + } + + CfCtx *context = (CfCtx *)HcfMalloc(sizeof(CfCtx), 0); + if (context == nullptr) { + LOGE("malloc context failed!"); + return nullptr; + } + context->pubKey = pubKey->GetPubKey(); + context->crlClass = this; + + if (!CreateCallbackAndPromise(env, context, argc, ARGS_SIZE_TWO, argv[PARAM1])) { + FreeCryptoFwkCtx(env, context); + return nullptr; + } + + napi_create_async_work( + env, nullptr, GetResourceName(env, "Verify"), + VerifyExecute, + VerifyComplete, + (void *)context, + &context->asyncWork); + + napi_queue_async_work(env, context->asyncWork); + if (context->asyncType == ASYNC_TYPE_PROMISE) { + return context->promise; + } else { + return NapiGetNull(env); + } +} + +napi_value NapiX509Crl::GetVersion(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_ZERO; + napi_get_cb_info(env, info, &argc, nullptr, nullptr, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ZERO, true)) { + return nullptr; + } + + HcfX509Crl *x509Crl = GetX509Crl(); + int version = x509Crl->getVersion(x509Crl); + napi_value result = nullptr; + napi_create_int32(env, version, &result); + return result; +} + +napi_value NapiX509Crl::GetIssuerDN(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_ZERO; + napi_get_cb_info(env, info, &argc, nullptr, nullptr, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ZERO, true)) { + return nullptr; + } + + HcfX509Crl *x509Crl = GetX509Crl(); + HcfBlob *blob = (HcfBlob *)HcfMalloc(sizeof(HcfBlob), 0); + if (blob == nullptr) { + LOGE("malloc blob failed!"); + return nullptr; + } + HcfResult ret = x509Crl->getIssuerName(x509Crl, blob); + if (ret != HCF_SUCCESS) { + napi_throw(env, GenerateBusinessError(env, ret, "get issuer name failed")); + LOGE("getIssuerDN failed!"); + HcfFree(blob); + blob = nullptr; + return nullptr; + } + napi_value returnBlob = ConvertBlobToNapiValue(env, blob); + HcfBlobDataFree(blob); + HcfFree(blob); + blob = nullptr; + return returnBlob; +} + +napi_value NapiX509Crl::GetThisUpdate(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_ZERO; + napi_get_cb_info(env, info, &argc, nullptr, nullptr, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ZERO, true)) { + return nullptr; + } + + HcfX509Crl *x509Crl = GetX509Crl(); + HcfBlob *blob = (HcfBlob *)HcfMalloc(sizeof(HcfBlob), 0); + if (blob == nullptr) { + LOGE("malloc blob failed!"); + return nullptr; + } + HcfResult ret = x509Crl->getLastUpdate(x509Crl, blob); + if (ret != HCF_SUCCESS) { + napi_throw(env, GenerateBusinessError(env, ret, "get last update failed")); + LOGE("getLastUpdate failed!"); + HcfFree(blob); + blob = nullptr; + return nullptr; + } + napi_value result = nullptr; + napi_create_string_utf8(env, (char *)blob->data, blob->len, &result); + HcfBlobDataFree(blob); + HcfFree(blob); + blob = nullptr; + return result; +} + +napi_value NapiX509Crl::GetNextUpdate(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_ZERO; + napi_get_cb_info(env, info, &argc, nullptr, nullptr, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ZERO, true)) { + return nullptr; + } + + HcfX509Crl *x509Crl = GetX509Crl(); + HcfBlob *blob = (HcfBlob *)HcfMalloc(sizeof(HcfBlob), 0); + if (blob == nullptr) { + LOGE("malloc blob failed!"); + return nullptr; + } + HcfResult ret = x509Crl->getNextUpdate(x509Crl, blob); + if (ret != HCF_SUCCESS) { + napi_throw(env, GenerateBusinessError(env, ret, "get next update failed")); + LOGE("getNextUpdate failed!"); + HcfFree(blob); + blob = nullptr; + return nullptr; + } + napi_value result = nullptr; + napi_create_string_utf8(env, (char *)blob->data, blob->len, &result); + HcfBlobDataFree(blob); + HcfFree(blob); + blob = nullptr; + return result; +} + +napi_value NapiX509Crl::GetRevokedCertificate(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_TWO; + napi_value argv[ARGS_SIZE_TWO] = { 0 }; + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_TWO, false)) { + return nullptr; + } + + CfCtx *context = (CfCtx *)HcfMalloc(sizeof(CfCtx), 0); + if (context == nullptr) { + LOGE("malloc context failed!"); + return nullptr; + } + context->crlClass = this; + + if (!GetInt32FromJSParams(env, argv[PARAM0], context->serialNumber)) { + LOGE("get serialNumber failed!"); + FreeCryptoFwkCtx(env, context); + return nullptr; + } + + if (!CreateCallbackAndPromise(env, context, argc, ARGS_SIZE_TWO, argv[PARAM1])) { + FreeCryptoFwkCtx(env, context); + return nullptr; + } + + napi_create_async_work( + env, nullptr, GetResourceName(env, "GetRevokedCertificate"), + GetRevokedCertificateExecute, + GetRevokedCertificateComplete, + (void *)context, + &context->asyncWork); + + napi_queue_async_work(env, context->asyncWork); + if (context->asyncType == ASYNC_TYPE_PROMISE) { + return context->promise; + } else { + return NapiGetNull(env); + } +} + +napi_value NapiX509Crl::GetRevokedCertificateWithCert(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_TWO; + napi_value argv[ARGS_SIZE_TWO] = { 0 }; + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_TWO, false)) { + return nullptr; + } + + NapiX509Cert *x509Cert = nullptr; + napi_unwrap(env, argv[PARAM0], (void**)&x509Cert); + if (x509Cert == nullptr) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "x509 cert is null")); + LOGE("x509Cert is null!"); + return nullptr; + } + + CfCtx *context = (CfCtx *)HcfMalloc(sizeof(CfCtx), 0); + if (context == nullptr) { + LOGE("malloc context failed!"); + return nullptr; + } + context->certificate = x509Cert->GetX509Cert(); + context->crlClass = this; + + if (!CreateCallbackAndPromise(env, context, argc, ARGS_SIZE_TWO, argv[PARAM1])) { + FreeCryptoFwkCtx(env, context); + return nullptr; + } + + napi_create_async_work( + env, nullptr, GetResourceName(env, "GetRevokedCertificateWithCert"), + GetRevokedCertificateWithCertExecute, + GetRevokedCertificateWithCertComplete, + (void *)context, + &context->asyncWork); + + napi_queue_async_work(env, context->asyncWork); + if (context->asyncType == ASYNC_TYPE_PROMISE) { + return context->promise; + } else { + return NapiGetNull(env); + } +} + +napi_value NapiX509Crl::GetRevokedCertificates(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_ONE; + napi_value argv[ARGS_SIZE_ONE] = { 0 }; + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ONE, false)) { + return nullptr; + } + + CfCtx *context = (CfCtx *)HcfMalloc(sizeof(CfCtx), 0); + if (context == nullptr) { + LOGE("malloc context failed!"); + return nullptr; + } + context->crlClass = this; + + if (!CreateCallbackAndPromise(env, context, argc, ARGS_SIZE_ONE, argv[PARAM0])) { + FreeCryptoFwkCtx(env, context); + return nullptr; + } + + napi_create_async_work( + env, nullptr, GetResourceName(env, "GetRevokedCertificates"), + GetRevokedCertificatesExecute, + GetRevokedCertificatesComplete, + (void *)context, + &context->asyncWork); + + napi_queue_async_work(env, context->asyncWork); + if (context->asyncType == ASYNC_TYPE_PROMISE) { + return context->promise; + } else { + return NapiGetNull(env); + } +} + +napi_value NapiX509Crl::GetTBSCertList(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_ONE; + napi_value argv[ARGS_SIZE_ONE] = { 0 }; + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ONE, false)) { + return nullptr; + } + + CfCtx *context = (CfCtx *)HcfMalloc(sizeof(CfCtx), 0); + if (context == nullptr) { + LOGE("malloc context failed!"); + return nullptr; + } + context->crlClass = this; + + if (!CreateCallbackAndPromise(env, context, argc, ARGS_SIZE_ONE, argv[PARAM0])) { + FreeCryptoFwkCtx(env, context); + return nullptr; + } + + napi_create_async_work( + env, nullptr, GetResourceName(env, "GetTBSCertList"), + GetTBSCertListExecute, + GetTBSCertListComplete, + (void *)context, + &context->asyncWork); + + napi_queue_async_work(env, context->asyncWork); + if (context->asyncType == ASYNC_TYPE_PROMISE) { + return context->promise; + } else { + return NapiGetNull(env); + } +} + +napi_value NapiX509Crl::GetSignature(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_ZERO; + napi_get_cb_info(env, info, &argc, nullptr, nullptr, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ZERO, true)) { + return nullptr; + } + + HcfX509Crl *x509Crl = GetX509Crl(); + HcfBlob *blob = (HcfBlob *)HcfMalloc(sizeof(HcfBlob), 0); + if (blob == nullptr) { + LOGE("malloc blob failed!"); + return nullptr; + } + HcfResult result = x509Crl->getSignature(x509Crl, blob); + if (result != HCF_SUCCESS) { + napi_throw(env, GenerateBusinessError(env, result, "get signature failed")); + LOGE("getSignature failed!"); + HcfFree(blob); + blob = nullptr; + return nullptr; + } + napi_value returnBlob = ConvertBlobToNapiValue(env, blob); + HcfBlobDataFree(blob); + HcfFree(blob); + blob = nullptr; + return returnBlob; +} + +napi_value NapiX509Crl::GetSigAlgName(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_ZERO; + napi_get_cb_info(env, info, &argc, nullptr, nullptr, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ZERO, true)) { + return nullptr; + } + + HcfX509Crl *x509Crl = GetX509Crl(); + HcfBlob *blob = (HcfBlob *)HcfMalloc(sizeof(HcfBlob), 0); + if (blob == nullptr) { + LOGE("malloc blob failed!"); + return nullptr; + } + HcfResult ret = x509Crl->getSignatureAlgName(x509Crl, blob); + if (ret != HCF_SUCCESS) { + napi_throw(env, GenerateBusinessError(env, ret, "get signature alg name failed")); + LOGE("getSigAlgName failed!"); + HcfFree(blob); + blob = nullptr; + return nullptr; + } + napi_value result = nullptr; + napi_create_string_utf8(env, (char *)blob->data, blob->len, &result); + HcfBlobDataFree(blob); + HcfFree(blob); + blob = nullptr; + return result; +} + +napi_value NapiX509Crl::GetSigAlgOID(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_ZERO; + napi_get_cb_info(env, info, &argc, nullptr, nullptr, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ZERO, true)) { + return nullptr; + } + + HcfX509Crl *x509Crl = GetX509Crl(); + HcfBlob *blob = (HcfBlob *)HcfMalloc(sizeof(HcfBlob), 0); + if (blob == nullptr) { + LOGE("malloc blob failed!"); + return nullptr; + } + HcfResult ret = x509Crl->getSignatureAlgOid(x509Crl, blob); + if (ret != HCF_SUCCESS) { + napi_throw(env, GenerateBusinessError(env, ret, "get signature alg oid failed")); + LOGE("getSigAlgOID failed!"); + HcfFree(blob); + blob = nullptr; + return nullptr; + } + napi_value result = nullptr; + napi_create_string_utf8(env, (char *)blob->data, blob->len, &result); + HcfBlobDataFree(blob); + HcfFree(blob); + blob = nullptr; + return result; +} + +napi_value NapiX509Crl::GetSigAlgParams(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_ZERO; + napi_get_cb_info(env, info, &argc, nullptr, nullptr, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ZERO, true)) { + return nullptr; + } + + HcfX509Crl *x509Crl = GetX509Crl(); + HcfBlob *blob = (HcfBlob *)HcfMalloc(sizeof(HcfBlob), 0); + if (blob == nullptr) { + LOGE("malloc blob failed!"); + return nullptr; + } + HcfResult result = x509Crl->getSignatureAlgParams(x509Crl, blob); + if (result != HCF_SUCCESS) { + napi_throw(env, GenerateBusinessError(env, result, "get signature alg params failed")); + LOGE("getSigAlgParams failed!"); + HcfFree(blob); + blob = nullptr; + return nullptr; + } + napi_value returnBlob = ConvertBlobToNapiValue(env, blob); + HcfBlobDataFree(blob); + HcfFree(blob); + blob = nullptr; + return returnBlob; +} + +static napi_value NapiIsRevoked(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509Crl *x509Crl = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509Crl)); + if (x509Crl == nullptr) { + LOGE("x509Crl is nullptr!"); + return nullptr; + } + return x509Crl->IsRevoked(env, info); +} + +static napi_value NapiGetType(napi_env env, napi_callback_info info) +{ + LOGI("napi get crl type called."); + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509Crl *x509Crl = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509Crl)); + if (x509Crl == nullptr) { + LOGE("x509Crl is nullptr!"); + return nullptr; + } + LOGI("unwrap x509 crl class success."); + return x509Crl->GetType(env, info); +} + +static napi_value NapiGetEncoded(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509Crl *x509Crl = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509Crl)); + if (x509Crl == nullptr) { + LOGE("x509Crl is nullptr!"); + return nullptr; + } + return x509Crl->GetEncoded(env, info); +} + +static napi_value NapiVerify(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509Crl *x509Crl = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509Crl)); + if (x509Crl == nullptr) { + LOGE("x509Crl is nullptr!"); + return nullptr; + } + return x509Crl->Verify(env, info); +} + +static napi_value NapiGetVersion(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509Crl *x509Crl = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509Crl)); + if (x509Crl == nullptr) { + LOGE("x509Crl is nullptr!"); + return nullptr; + } + return x509Crl->GetVersion(env, info); +} + +static napi_value NapiGetIssuerDN(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509Crl *x509Crl = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509Crl)); + if (x509Crl == nullptr) { + LOGE("x509Crl is nullptr!"); + return nullptr; + } + return x509Crl->GetIssuerDN(env, info); +} + +static napi_value NapiGetThisUpdate(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509Crl *x509Crl = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509Crl)); + if (x509Crl == nullptr) { + LOGE("x509Crl is nullptr!"); + return nullptr; + } + return x509Crl->GetThisUpdate(env, info); +} + +static napi_value NapiGetNextUpdate(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509Crl *x509Crl = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509Crl)); + if (x509Crl == nullptr) { + LOGE("x509Crl is nullptr!"); + return nullptr; + } + return x509Crl->GetNextUpdate(env, info); +} + +static napi_value NapiGetRevokedCertificate(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509Crl *x509Crl = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509Crl)); + if (x509Crl == nullptr) { + LOGE("x509Crl is nullptr!"); + return nullptr; + } + return x509Crl->GetRevokedCertificate(env, info); +} + +static napi_value NapiGetRevokedCertificateWithCert(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509Crl *x509Crl = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509Crl)); + if (x509Crl == nullptr) { + LOGE("x509Crl is nullptr!"); + return nullptr; + } + return x509Crl->GetRevokedCertificateWithCert(env, info); +} + +static napi_value NapiGetRevokedCertificates(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509Crl *x509Crl = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509Crl)); + if (x509Crl == nullptr) { + LOGE("x509Crl is nullptr!"); + return nullptr; + } + return x509Crl->GetRevokedCertificates(env, info); +} + +static napi_value NapiGetTBSCertList(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509Crl *x509Crl = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509Crl)); + if (x509Crl == nullptr) { + LOGE("x509Crl is nullptr!"); + return nullptr; + } + return x509Crl->GetTBSCertList(env, info); +} + +static napi_value NapiGetSignature(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509Crl *x509Crl = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509Crl)); + if (x509Crl == nullptr) { + LOGE("x509Crl is nullptr!"); + return nullptr; + } + return x509Crl->GetSignature(env, info); +} + +static napi_value NapiGetSigAlgName(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509Crl *x509Crl = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509Crl)); + if (x509Crl == nullptr) { + LOGE("x509Crl is nullptr!"); + return nullptr; + } + return x509Crl->GetSigAlgName(env, info); +} + +static napi_value NapiGetSigAlgOID(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509Crl *x509Crl = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509Crl)); + if (x509Crl == nullptr) { + LOGE("x509Crl is nullptr!"); + return nullptr; + } + return x509Crl->GetSigAlgOID(env, info); +} + +static napi_value NapiGetSigAlgParams(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509Crl *x509Crl = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509Crl)); + if (x509Crl == nullptr) { + LOGE("x509Crl is nullptr!"); + return nullptr; + } + return x509Crl->GetSigAlgParams(env, info); +} + +void NapiX509Crl::CreateX509CrlExecute(napi_env env, void *data) +{ + CfCtx *context = static_cast(data); + context->errCode = HcfX509CrlCreate(context->encodingBlob, &context->crl); +} + +void NapiX509Crl::CreateX509CrlComplete(napi_env env, napi_status status, void *data) +{ + CfCtx *context = static_cast(data); + if (context->errCode != HCF_SUCCESS) { + LOGE("call create X509Crl failed!"); + ReturnResult(env, context, nullptr); + FreeCryptoFwkCtx(env, context); + return; + } + napi_value instance = CreateX509Crl(env); + NapiX509Crl *x509CrlClass = new NapiX509Crl(context->crl); + napi_wrap( + env, instance, x509CrlClass, + [](napi_env env, void *data, void *hint) { + NapiX509Crl *crlClass = (NapiX509Crl *)data; + delete crlClass; + return; + }, + nullptr, nullptr); + ReturnResult(env, context, instance); + FreeCryptoFwkCtx(env, context); +} + +napi_value NapiX509Crl::NapiCreateX509Crl(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_TWO; + napi_value argv[ARGS_SIZE_TWO] = { 0 }; + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_TWO, false)) { + return nullptr; + } + + CfCtx *context = (CfCtx *)HcfMalloc(sizeof(CfCtx), 0); + if (context == nullptr) { + LOGE("malloc context failed!"); + return nullptr; + } + if (!GetEncodingBlobFromValue(env, argv[PARAM0], &context->encodingBlob)) { + LOGE("get encoding blob from data failed!"); + FreeCryptoFwkCtx(env, context); + return nullptr; + } + + if (!CreateCallbackAndPromise(env, context, argc, ARGS_SIZE_TWO, argv[PARAM1])) { + FreeCryptoFwkCtx(env, context); + return nullptr; + } + + napi_create_async_work( + env, nullptr, GetResourceName(env, "createX509Crl"), + CreateX509CrlExecute, + CreateX509CrlComplete, + (void *)context, + &context->asyncWork); + + napi_queue_async_work(env, context->asyncWork); + if (context->asyncType == ASYNC_TYPE_PROMISE) { + return context->promise; + } else { + return NapiGetNull(env); + } +} + +static napi_value X509CrlConstructor(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + return thisVar; +} + +void NapiX509Crl::DefineX509CrlJSClass(napi_env env, napi_value exports) +{ + napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("createX509Crl", NapiCreateX509Crl), + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); + + napi_property_descriptor x509CrlDesc[] = { + DECLARE_NAPI_FUNCTION("isRevoked", NapiIsRevoked), + DECLARE_NAPI_FUNCTION("getType", NapiGetType), + DECLARE_NAPI_FUNCTION("getEncoded", NapiGetEncoded), + DECLARE_NAPI_FUNCTION("verify", NapiVerify), + DECLARE_NAPI_FUNCTION("getVersion", NapiGetVersion), + DECLARE_NAPI_FUNCTION("getIssuerName", NapiGetIssuerDN), + DECLARE_NAPI_FUNCTION("getLastUpdate", NapiGetThisUpdate), + DECLARE_NAPI_FUNCTION("getNextUpdate", NapiGetNextUpdate), + DECLARE_NAPI_FUNCTION("getRevokedCert", NapiGetRevokedCertificate), + DECLARE_NAPI_FUNCTION("getRevokedCertWithCert", NapiGetRevokedCertificateWithCert), + DECLARE_NAPI_FUNCTION("getRevokedCerts", NapiGetRevokedCertificates), + DECLARE_NAPI_FUNCTION("getTbsInfo", NapiGetTBSCertList), + DECLARE_NAPI_FUNCTION("getSignature", NapiGetSignature), + DECLARE_NAPI_FUNCTION("getSignatureAlgName", NapiGetSigAlgName), + DECLARE_NAPI_FUNCTION("getSignatureAlgOid", NapiGetSigAlgOID), + DECLARE_NAPI_FUNCTION("getSignatureAlgParams", NapiGetSigAlgParams), + }; + napi_value constructor = nullptr; + napi_define_class(env, "X509Crl", NAPI_AUTO_LENGTH, X509CrlConstructor, nullptr, + sizeof(x509CrlDesc) / sizeof(x509CrlDesc[0]), x509CrlDesc, &constructor); + napi_create_reference(env, constructor, 1, &classRef_); +} + +napi_value NapiX509Crl::CreateX509Crl(napi_env env) +{ + napi_value constructor = nullptr; + napi_value instance = nullptr; + napi_get_reference_value(env, classRef_, &constructor); + napi_new_instance(env, constructor, 0, nullptr, &instance); + return instance; +} + +} // namespace CryptoFramework +} // namespace OHOS diff --git a/frameworks/js/napi/src/napi_x509_crl_entry.cpp b/frameworks/js/napi/src/napi_x509_crl_entry.cpp new file mode 100644 index 0000000..7026c45 --- /dev/null +++ b/frameworks/js/napi/src/napi_x509_crl_entry.cpp @@ -0,0 +1,444 @@ +/* + * Copyright (c) 2022 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 "napi_x509_crl_entry.h" + +#include "napi/native_node_api.h" +#include "napi/native_api.h" +#include "log.h" +#include "memory.h" +#include "utils.h" +#include "object_base.h" +#include "result.h" +#include "napi_crypto_framework_defines.h" +#include "napi_utils.h" + +namespace OHOS { +namespace CryptoFramework { + +napi_ref NapiX509CrlEntry::classRef_ = nullptr; + +struct CfCtx { + CfAsyncType asyncType = ASYNC_TYPE_CALLBACK; + napi_value promise = nullptr; + napi_ref callback = nullptr; + napi_deferred deferred = nullptr; + napi_async_work asyncWork = nullptr; + + NapiX509CrlEntry *crlEntryClass = nullptr; + + int32_t errCode = 0; + const char *errMsg = nullptr; + HcfEncodingBlob *encoded = nullptr; + HcfBlob *blob = nullptr; +}; + +static void FreeCryptoFwkCtx(napi_env env, CfCtx *context) +{ + if (context == nullptr) { + return; + } + + if (context->asyncWork != nullptr) { + napi_delete_async_work(env, context->asyncWork); + } + + if (context->callback != nullptr) { + napi_delete_reference(env, context->callback); + } + + HcfEncodingBlobDataFree(context->encoded); + HcfFree(context->encoded); + context->encoded = nullptr; + + HcfBlobDataFree(context->blob); + HcfFree(context->blob); + context->blob = nullptr; + + HcfFree(context); + context = nullptr; +} + +static void ReturnCallbackResult(napi_env env, CfCtx *context, napi_value result) +{ + napi_value businessError = nullptr; + if (context->errCode != HCF_SUCCESS) { + businessError = GenerateBusinessError(env, context->errCode, context->errMsg); + } + napi_value params[ARGS_SIZE_TWO] = { businessError, result }; + + napi_value func = nullptr; + napi_get_reference_value(env, context->callback, &func); + + napi_value recv = nullptr; + napi_value callFuncRet = nullptr; + napi_get_undefined(env, &recv); + napi_call_function(env, recv, func, ARGS_SIZE_TWO, params, &callFuncRet); +} + +static void ReturnPromiseResult(napi_env env, CfCtx *context, napi_value result) +{ + if (context->errCode == HCF_SUCCESS) { + napi_resolve_deferred(env, context->deferred, result); + } else { + napi_reject_deferred(env, context->deferred, GenerateBusinessError(env, context->errCode, context->errMsg)); + } +} + +static void ReturnResult(napi_env env, CfCtx *context, napi_value result) +{ + if (context->asyncType == ASYNC_TYPE_CALLBACK) { + ReturnCallbackResult(env, context, result); + } else { + ReturnPromiseResult(env, context, result); + } +} + +static bool CreateCallbackAndPromise(napi_env env, CfCtx *context, size_t argc, + size_t maxCount, napi_value callbackValue) +{ + context->asyncType = (argc == maxCount) ? ASYNC_TYPE_CALLBACK : ASYNC_TYPE_PROMISE; + if (context->asyncType == ASYNC_TYPE_CALLBACK) { + if (!GetCallbackFromJSParams(env, callbackValue, &context->callback)) { + LOGE("get callback failed!"); + return false; + } + } else { + napi_create_promise(env, &context->deferred, &context->promise); + } + return true; +} + +NapiX509CrlEntry::NapiX509CrlEntry(HcfX509CrlEntry *x509CrlEntry) +{ + this->x509CrlEntry_ = x509CrlEntry; +} + +NapiX509CrlEntry::~NapiX509CrlEntry() +{ + OH_HCF_ObjDestroy(this->x509CrlEntry_); +} + +static void GetEncodedExecute(napi_env env, void *data) +{ + CfCtx *context = static_cast(data); + HcfX509CrlEntry *x509CrlEntry = context->crlEntryClass->GetX509CrlEntry(); + HcfEncodingBlob *encodingBlob = (HcfEncodingBlob *)HcfMalloc(sizeof(HcfEncodingBlob), 0); + if (encodingBlob == nullptr) { + LOGE("malloc encoding blob failed!"); + context->errCode = HCF_ERR_MALLOC; + context->errMsg = "malloc encoding blob failed"; + return; + } + + context->errCode = x509CrlEntry->getEncoded(x509CrlEntry, encodingBlob); + if (context->errCode != HCF_SUCCESS) { + LOGE("get encoded failed!"); + context->errMsg = "get encoded failed"; + } + context->encoded = encodingBlob; +} + +static void GetEncodedComplete(napi_env env, napi_status status, void *data) +{ + CfCtx *context = static_cast(data); + if (context->errCode != HCF_SUCCESS) { + ReturnResult(env, context, nullptr); + FreeCryptoFwkCtx(env, context); + return; + } + napi_value returnEncodingBlob = ConvertEncodingBlobToNapiValue(env, context->encoded); + ReturnResult(env, context, returnEncodingBlob); + FreeCryptoFwkCtx(env, context); +} + +static void GetCertificateIssuerExecute(napi_env env, void *data) +{ + CfCtx *context = static_cast(data); + HcfX509CrlEntry *x509CrlEntry = context->crlEntryClass->GetX509CrlEntry(); + HcfBlob *blob = (HcfBlob *)HcfMalloc(sizeof(HcfBlob), 0); + if (blob == nullptr) { + LOGE("malloc blob failed!"); + context->errCode = HCF_ERR_MALLOC; + context->errMsg = "malloc blob failed"; + return; + } + + context->errCode = x509CrlEntry->getCertIssuer(x509CrlEntry, blob); + if (context->errCode != HCF_SUCCESS) { + LOGE("get cert issuer failed!"); + context->errMsg = "get cert issuer failed"; + } + context->blob = blob; +} + +static void GetCertificateIssuerComplete(napi_env env, napi_status status, void *data) +{ + CfCtx *context = static_cast(data); + if (context->errCode != HCF_SUCCESS) { + ReturnResult(env, context, nullptr); + FreeCryptoFwkCtx(env, context); + return; + } + napi_value returnBlob = ConvertBlobToNapiValue(env, context->blob); + ReturnResult(env, context, returnBlob); + FreeCryptoFwkCtx(env, context); +} + +static void GetRevocationDateExecute(napi_env env, void *data) +{ + CfCtx *context = static_cast(data); + HcfX509CrlEntry *x509CrlEntry = context->crlEntryClass->GetX509CrlEntry(); + HcfBlob *blob = (HcfBlob *)HcfMalloc(sizeof(HcfBlob), 0); + if (blob == nullptr) { + LOGE("malloc blob failed!"); + context->errCode = HCF_ERR_MALLOC; + context->errMsg = "malloc blob failed"; + return; + } + context->errCode = x509CrlEntry->getRevocationDate(x509CrlEntry, blob); + if (context->errCode != HCF_SUCCESS) { + LOGE("get revocation date failed!"); + context->errMsg = "get revocation date failed"; + } + context->blob = blob; +} + +static void GetRevocationDateComplete(napi_env env, napi_status status, void *data) +{ + CfCtx *context = static_cast(data); + if (context->errCode != HCF_SUCCESS) { + ReturnResult(env, context, nullptr); + FreeCryptoFwkCtx(env, context); + return; + } + HcfBlob *blob = context->blob; + napi_value result = nullptr; + napi_create_string_utf8(env, (char *)blob->data, blob->len, &result); + ReturnResult(env, context, result); + FreeCryptoFwkCtx(env, context); +} + +napi_value NapiX509CrlEntry::GetEncoded(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_ONE; + napi_value argv[ARGS_SIZE_ONE] = { 0 }; + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ONE, false)) { + return nullptr; + } + + CfCtx *context = (CfCtx *)HcfMalloc(sizeof(CfCtx), 0); + if (context == nullptr) { + LOGE("malloc context failed!"); + return nullptr; + } + context->crlEntryClass = this; + + if (!CreateCallbackAndPromise(env, context, argc, ARGS_SIZE_ONE, argv[PARAM0])) { + FreeCryptoFwkCtx(env, context); + return nullptr; + } + + napi_create_async_work( + env, nullptr, GetResourceName(env, "GetEncoded"), + GetEncodedExecute, + GetEncodedComplete, + (void *)context, + &context->asyncWork); + + napi_queue_async_work(env, context->asyncWork); + if (context->asyncType == ASYNC_TYPE_PROMISE) { + return context->promise; + } else { + return NapiGetNull(env); + } +} + +napi_value NapiX509CrlEntry::GetSerialNumber(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_ZERO; + napi_get_cb_info(env, info, &argc, nullptr, nullptr, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ZERO, true)) { + return nullptr; + } + + HcfX509CrlEntry *x509CrlEntry = GetX509CrlEntry(); + long serialNumber = x509CrlEntry->getSerialNumber(x509CrlEntry); + napi_value result = nullptr; + napi_create_int64(env, serialNumber, &result); + return result; +} + +napi_value NapiX509CrlEntry::GetCertificateIssuer(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_ONE; + napi_value argv[ARGS_SIZE_ONE] = { 0 }; + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ONE, false)) { + return nullptr; + } + + CfCtx *context = (CfCtx *)HcfMalloc(sizeof(CfCtx), 0); + if (context == nullptr) { + LOGE("malloc context failed!"); + return nullptr; + } + context->crlEntryClass = this; + + if (!CreateCallbackAndPromise(env, context, argc, ARGS_SIZE_ONE, argv[PARAM0])) { + FreeCryptoFwkCtx(env, context); + return nullptr; + } + + napi_create_async_work( + env, nullptr, GetResourceName(env, "GetCertificateIssuer"), + GetCertificateIssuerExecute, + GetCertificateIssuerComplete, + (void *)context, + &context->asyncWork); + + napi_queue_async_work(env, context->asyncWork); + if (context->asyncType == ASYNC_TYPE_PROMISE) { + return context->promise; + } else { + return NapiGetNull(env); + } +} + +napi_value NapiX509CrlEntry::GetRevocationDate(napi_env env, napi_callback_info info) +{ + size_t argc = ARGS_SIZE_ONE; + napi_value argv[ARGS_SIZE_ONE] = { 0 }; + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + if (!CheckArgsCount(env, argc, ARGS_SIZE_ONE, false)) { + return nullptr; + } + + CfCtx *context = (CfCtx *)HcfMalloc(sizeof(CfCtx), 0); + if (context == nullptr) { + LOGE("malloc context failed!"); + FreeCryptoFwkCtx(env, context); + return nullptr; + } + context->crlEntryClass = this; + + if (!CreateCallbackAndPromise(env, context, argc, ARGS_SIZE_ONE, argv[PARAM0])) { + FreeCryptoFwkCtx(env, context); + return nullptr; + } + + napi_create_async_work( + env, nullptr, GetResourceName(env, "GetRevocationDate"), + GetRevocationDateExecute, + GetRevocationDateComplete, + (void *)context, + &context->asyncWork); + + napi_queue_async_work(env, context->asyncWork); + if (context->asyncType == ASYNC_TYPE_PROMISE) { + return context->promise; + } else { + return NapiGetNull(env); + } +} + +static napi_value NapiGetEncoded(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509CrlEntry *x509CrlEntry = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509CrlEntry)); + if (x509CrlEntry == nullptr) { + LOGE("x509CrlEntry is nullptr!"); + return nullptr; + } + return x509CrlEntry->GetEncoded(env, info); +} + +static napi_value NapiGetSerialNumber(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509CrlEntry *x509CrlEntry = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509CrlEntry)); + if (x509CrlEntry == nullptr) { + LOGE("x509CrlEntry is nullptr!"); + return nullptr; + } + return x509CrlEntry->GetSerialNumber(env, info); +} + +static napi_value NapiGetCertificateIssuer(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509CrlEntry *x509CrlEntry = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509CrlEntry)); + if (x509CrlEntry == nullptr) { + LOGE("x509CrlEntry is nullptr!"); + return nullptr; + } + return x509CrlEntry->GetCertificateIssuer(env, info); +} + +static napi_value NapiGetRevocationDate(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NapiX509CrlEntry *x509CrlEntry = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&x509CrlEntry)); + if (x509CrlEntry == nullptr) { + LOGE("x509CrlEntry is nullptr!"); + return nullptr; + } + return x509CrlEntry->GetRevocationDate(env, info); +} + +static napi_value X509CrlEntryConstructor(napi_env env, napi_callback_info info) +{ + napi_value thisVar = nullptr; + napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + return thisVar; +} + +void NapiX509CrlEntry::DefineX509CrlEntryJSClass(napi_env env) +{ + napi_property_descriptor x509CrlEntryDesc[] = { + DECLARE_NAPI_FUNCTION("getEncoded", NapiGetEncoded), + DECLARE_NAPI_FUNCTION("getSerialNumber", NapiGetSerialNumber), + DECLARE_NAPI_FUNCTION("getCertIssuer", NapiGetCertificateIssuer), + DECLARE_NAPI_FUNCTION("getRevocationDate", NapiGetRevocationDate), + }; + napi_value constructor = nullptr; + napi_define_class(env, "X509CrlEntry", NAPI_AUTO_LENGTH, X509CrlEntryConstructor, nullptr, + sizeof(x509CrlEntryDesc) / sizeof(x509CrlEntryDesc[0]), x509CrlEntryDesc, &constructor); + napi_create_reference(env, constructor, 1, &classRef_); +} + +napi_value NapiX509CrlEntry::CreateX509CrlEntry(napi_env env) +{ + napi_value constructor = nullptr; + napi_value instance = nullptr; + napi_get_reference_value(env, classRef_, &constructor); + napi_new_instance(env, constructor, 0, nullptr, &instance); + return instance; +} + +} // namespace CryptoFramework +} // namespace OHOS diff --git a/frameworks/key/asy_key_generator.c b/frameworks/key/asy_key_generator.c new file mode 100644 index 0000000..6cf055c --- /dev/null +++ b/frameworks/key/asy_key_generator.c @@ -0,0 +1,257 @@ +/* + * Copyright (C) 2022 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.h" + +#include + +#include "asy_key_generator_spi.h" +#include "config.h" +#include "ecc_asy_key_generator_openssl.h" +#include "params_parser.h" +#include "rsa_asy_key_generator_openssl.h" +#include "log.h" +#include "memory.h" +#include "utils.h" + +typedef HcfResult (*HcfAsyKeyGeneratorSpiCreateFunc)(HcfAsyKeyGenParams *, HcfAsyKeyGeneratorSpi **); + +typedef struct { + HcfAsyKeyGenerator base; + + HcfAsyKeyGeneratorSpi *spiObj; + + char algoName[HCF_MAX_ALGO_NAME_LEN]; +} HcfAsyKeyGeneratorImpl; + +typedef struct { + HCF_ALG_VALUE algo; + + HcfAsyKeyGeneratorSpiCreateFunc createSpifunc; +} HcfAsyKeyGenAbility; + +static const HcfAsyKeyGenAbility ASY_KEY_GEN_ABILITY_SET[] = { + { HCF_ALG_RSA, HcfAsyKeyGeneratorSpiRsaCreate }, + { HCF_ALG_ECC, HcfAsyKeyGeneratorSpiEccCreate } +}; + +static HcfAsyKeyGeneratorSpiCreateFunc FindAbility(HcfAsyKeyGenParams *params) +{ + for (uint32_t i = 0; i < sizeof(ASY_KEY_GEN_ABILITY_SET) / sizeof(ASY_KEY_GEN_ABILITY_SET[0]); i++) { + if (ASY_KEY_GEN_ABILITY_SET[i].algo == params->algo) { + return ASY_KEY_GEN_ABILITY_SET[i].createSpifunc; + } + } + LOGE("Algo not support! [Algo]: %d", params->algo); + return NULL; +} + +static void SetPrimes(HCF_ALG_PARA_VALUE value, HcfAsyKeyGenParams *params) +{ + if (params == NULL) { + LOGE("params is null."); + return; + } + switch (value) { + case HCF_OPENSSL_PRIMES_2: + params->primes = (int32_t)HCF_RSA_PRIMES_SIZE_2; + break; + case HCF_OPENSSL_PRIMES_3: + params->primes = (int32_t)HCF_RSA_PRIMES_SIZE_3; + break; + case HCF_OPENSSL_PRIMES_4: + params->primes = (int32_t)HCF_RSA_PRIMES_SIZE_4; + break; + case HCF_OPENSSL_PRIMES_5: + params->primes = (int32_t)HCF_RSA_PRIMES_SIZE_5; + break; + default: + params->primes = (int32_t)HCF_RSA_PRIMES_SIZE_2; // default primes is 2 + LOGD("user default primes 2"); + break; + } + LOGD("Set primes:%d\n", params->primes); +} + +static void SetKeyType(HCF_ALG_PARA_VALUE value, HcfAsyKeyGenParams *params) +{ + switch (value) { + case HCF_ALG_ECC_224: + case HCF_ALG_ECC_256: + case HCF_ALG_ECC_384: + case HCF_ALG_ECC_512: + params->bits = value; + params->algo = HCF_ALG_ECC; + break; + case HCF_OPENSSL_RSA_512: + params->bits = (int32_t)HCF_RSA_KEY_SIZE_512; + params->algo = HCF_ALG_RSA; + break; + case HCF_OPENSSL_RSA_768: + params->bits = (int32_t)HCF_RSA_KEY_SIZE_768; + params->algo = HCF_ALG_RSA; + break; + case HCF_OPENSSL_RSA_1024: + params->bits = (int32_t)HCF_RSA_KEY_SIZE_1024; + params->algo = HCF_ALG_RSA; + break; + case HCF_OPENSSL_RSA_2048: + params->bits = (int32_t)HCF_RSA_KEY_SIZE_2048; + params->algo = HCF_ALG_RSA; + break; + case HCF_OPENSSL_RSA_3072: + params->bits = (int32_t)HCF_RSA_KEY_SIZE_3072; + params->algo = HCF_ALG_RSA; + break; + case HCF_OPENSSL_RSA_4096: + params->bits = (int32_t)HCF_RSA_KEY_SIZE_4096; + params->algo = HCF_ALG_RSA; + break; + case HCF_OPENSSL_RSA_8192: + params->bits = (int32_t)HCF_RSA_KEY_SIZE_8192; + params->algo = HCF_ALG_RSA; + break; + default: + LOGE("there is not matched algorithm."); + break; + } +} + +static HcfResult ParseAsyKeyGenParams(const HcfParaConfig* config, void *params) +{ + if (config == NULL || params == NULL) { + return HCF_INVALID_PARAMS; + } + HcfResult ret = HCF_SUCCESS; + HcfAsyKeyGenParams *paramsObj = (HcfAsyKeyGenParams *)params; + LOGI("Set Parameter: %s", config->tag); + switch (config->para_type) { + case HCF_ALG_KEY_TYPE: + SetKeyType(config->para_value, paramsObj); + break; + case HCF_ALG_PRIMES: + SetPrimes(config->para_value, paramsObj); + break; + default: + ret = HCF_INVALID_PARAMS; + break; + } + return ret; +} + +// export interfaces +static const char *GetAsyKeyGeneratorClass() +{ + return "HcfAsyKeyGenerator"; +} + +static const char *GetAlgoName(HcfAsyKeyGenerator *self) +{ + if (self == NULL) { + LOGE("The input self ptr is NULL!"); + return NULL; + } + if (!IsClassMatch((HcfObjectBase *)self, GetAsyKeyGeneratorClass())) { + return NULL; + } + return ((HcfAsyKeyGeneratorImpl *)self)->algoName; +} + +static HcfResult ConvertKey(HcfAsyKeyGenerator *self, HcfParamsSpec *params, HcfBlob *pubKeyBlob, + HcfBlob *priKeyBlob, HcfKeyPair **returnKeyPair) +{ + if (self == NULL) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetAsyKeyGeneratorClass())) { + return HCF_INVALID_PARAMS; + } + return ((HcfAsyKeyGeneratorImpl *)self)->spiObj->engineConvertKey( + ((HcfAsyKeyGeneratorImpl *)self)->spiObj, params, pubKeyBlob, priKeyBlob, returnKeyPair); +} + +static HcfResult GenerateKeyPair(HcfAsyKeyGenerator *self, HcfParamsSpec *params, + HcfKeyPair **returnKeyPair) +{ + if (self == NULL) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetAsyKeyGeneratorClass())) { + return HCF_INVALID_PARAMS; + } + return ((HcfAsyKeyGeneratorImpl *)self)->spiObj->engineGenerateKeyPair( + ((HcfAsyKeyGeneratorImpl *)self)->spiObj, returnKeyPair); +} + +static void DestroyAsyKeyGenerator(HcfObjectBase *self) +{ + if (self == NULL) { + return; + } + if (!IsClassMatch((HcfObjectBase *)self, GetAsyKeyGeneratorClass())) { + return; + } + HcfAsyKeyGeneratorImpl *impl = (HcfAsyKeyGeneratorImpl *)self; + OH_HCF_ObjDestroy(impl->spiObj); + impl->spiObj = NULL; + HcfFree(impl); +} + +HcfResult HcfAsyKeyGeneratorCreate(const char *algoName, HcfAsyKeyGenerator **returnObj) +{ + if ((!IsStrValid(algoName, HCF_MAX_ALGO_NAME_LEN)) || (returnObj == NULL)) { + return HCF_INVALID_PARAMS; + } + + HcfAsyKeyGenParams params = { 0 }; + if (ParseAndSetParameter(algoName, ¶ms, ParseAsyKeyGenParams) != HCF_SUCCESS) { + LOGE("Failed to parser parmas!"); + return HCF_INVALID_PARAMS; + } + + HcfAsyKeyGeneratorSpiCreateFunc createSpifunc = FindAbility(¶ms); + if (createSpifunc == NULL) { + return HCF_NOT_SUPPORT; + } + + HcfAsyKeyGeneratorImpl *returnGenerator = (HcfAsyKeyGeneratorImpl *)HcfMalloc(sizeof(HcfAsyKeyGeneratorImpl), 0); + if (returnGenerator == NULL) { + LOGE("Failed to allocate returnGenerator memory!"); + return HCF_ERR_MALLOC; + } + if (strcpy_s(returnGenerator->algoName, HCF_MAX_ALGO_NAME_LEN, algoName) != EOK) { + LOGE("Failed to copy algoName!"); + HcfFree(returnGenerator); + return HCF_ERR_COPY; + } + HcfAsyKeyGeneratorSpi *spiObj = NULL; + int32_t res = HCF_SUCCESS; + res = createSpifunc(¶ms, &spiObj); + if (res != HCF_SUCCESS) { + LOGE("Failed to create spi object!"); + HcfFree(returnGenerator); + return res; + } + returnGenerator->base.base.destroy = DestroyAsyKeyGenerator; + returnGenerator->base.base.getClass = GetAsyKeyGeneratorClass; + returnGenerator->base.convertKey = ConvertKey; + returnGenerator->base.generateKeyPair = GenerateKeyPair; + returnGenerator->base.getAlgoName = GetAlgoName; + returnGenerator->spiObj = spiObj; + *returnObj = (HcfAsyKeyGenerator *)returnGenerator; + return HCF_SUCCESS; +} diff --git a/frameworks/key/sym_key_generator.c b/frameworks/key/sym_key_generator.c new file mode 100644 index 0000000..af8f316 --- /dev/null +++ b/frameworks/key/sym_key_generator.c @@ -0,0 +1,222 @@ +/* + * Copyright (C) 2022 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_generator.h" +#include "sym_key_factory_spi.h" +#include "sym_common_defines.h" +#include "params_parser.h" +#include "utils.h" + +#include +#include "log.h" +#include "memory.h" +#include "result.h" +#include "config.h" + +#define AES_KEY_SIZE_128 128 +#define AES_KEY_SIZE_192 192 +#define AES_KEY_SIZE_256 256 +#define DES_KEY_SIZE_192 192 + +typedef HcfResult (*SymKeyGeneratorSpiCreateFunc)(SymKeyAttr *, OH_HCF_SymKeyGeneratorSpi **); + +typedef struct { + SymKeyGeneratorSpiCreateFunc createFunc; +} SymKeyGenFuncSet; + +typedef struct { + HCF_ALG_VALUE algo; + SymKeyGenFuncSet funcSet; +} SymKeyGenAbility; + +typedef struct { + HcfSymKeyGenerator base; + OH_HCF_SymKeyGeneratorSpi *spiObj; + char algoName[HCF_MAX_ALGO_NAME_LEN]; +} HcfSymmKeyGeneratorImpl; + +static const SymKeyGenAbility SYMKEY_ABILITY_SET[] = { + { HCF_ALG_AES, { HcfSymKeyGeneratorSpiCreate }}, + { HCF_ALG_DES, { HcfSymKeyGeneratorSpiCreate }} +}; + +static const SymKeyGenFuncSet *FindAbility(SymKeyAttr *attr) +{ + if (attr == NULL) { + return NULL; + } + for (uint32_t i = 0; i < sizeof(SYMKEY_ABILITY_SET); i++) { + if (SYMKEY_ABILITY_SET[i].algo == attr->algo) { + return &(SYMKEY_ABILITY_SET[i].funcSet); + } + } + LOGE("Algo not support! [Algo]: %d", attr->algo); + return NULL; +} + +static void SetKeyLength(HCF_ALG_PARA_VALUE value, void *attr) +{ + SymKeyAttr *keyAttr = (SymKeyAttr *)attr; + + switch (value) { + case HCF_ALG_AES_128: + keyAttr->algo = HCF_ALG_AES; + keyAttr->keySize = AES_KEY_SIZE_128; + break; + case HCF_ALG_AES_192: + keyAttr->algo = HCF_ALG_AES; + keyAttr->keySize = AES_KEY_SIZE_192; + break; + case HCF_ALG_AES_256: + keyAttr->algo = HCF_ALG_AES; + keyAttr->keySize = AES_KEY_SIZE_256; + break; + case HCF_ALG_3DES_192: + keyAttr->algo = HCF_ALG_DES; + keyAttr->keySize = DES_KEY_SIZE_192; + default: + break; + } +} + +static HcfResult OnSetSymKeyParameter(const HcfParaConfig* config, void *attr) +{ + if ((config == NULL) || (attr == NULL)) { + return HCF_INVALID_PARAMS; + } + HcfResult ret = HCF_SUCCESS; + LOGD("Set Parameter:%s\n", config->tag); + switch (config->para_type) { + case HCF_ALG_TYPE: + case HCF_ALG_KEY_TYPE: + SetKeyLength(config->para_value, attr); + break; + default: + ret = HCF_INVALID_PARAMS; + break; + } + return ret; +} + +static const char *GetSymKeyGeneratorClass() +{ + return "HcfSymKeyGenerator"; +} + +static const char *GetAlgoName(HcfSymKeyGenerator *self) +{ + if (self == NULL) { + LOGE("The input self ptr is NULL!"); + return NULL; + } + if (!IsClassMatch((HcfObjectBase *)self, GetSymKeyGeneratorClass())) { + LOGE("Class is not match!"); + return NULL; + } + return ((HcfSymmKeyGeneratorImpl *)self)->algoName; +} + +static void DestroySymmKeyGenerator(HcfObjectBase *base) +{ + if (base == NULL) { + return; + } + if (!IsClassMatch((HcfObjectBase *)base, GetSymKeyGeneratorClass())) { + LOGE("Class is not match."); + return; + } + HcfSymmKeyGeneratorImpl *impl = (HcfSymmKeyGeneratorImpl *)base; + if (impl->spiObj != NULL) { + OH_HCF_ObjDestroy((HcfObjectBase *)impl->spiObj); + } + HcfFree(impl); +} + +static HcfResult GenerateSymmKey(HcfSymKeyGenerator *self, HcfSymKey **symmKey) +{ + if ((self == NULL) || (symmKey == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + + if (!IsClassMatch((HcfObjectBase *)self, GetSymKeyGeneratorClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + HcfSymmKeyGeneratorImpl *impl = (HcfSymmKeyGeneratorImpl *)self; + + return impl->spiObj->engineGenerateSymmKey(impl->spiObj, symmKey); +} + +static HcfResult ConvertSymmKey(HcfSymKeyGenerator *self, const HcfBlob *key, HcfSymKey **symmKey) +{ + if ((self == NULL) || (symmKey == NULL) || !IsBlobValid(key)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetSymKeyGeneratorClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + HcfSymmKeyGeneratorImpl *impl = (HcfSymmKeyGeneratorImpl *)self; + + return impl->spiObj->engineConvertSymmKey(impl->spiObj, key, symmKey); +} + +HcfResult HcfSymKeyGeneratorCreate(const char *algoName, HcfSymKeyGenerator **generator) +{ + if (!IsStrValid(algoName, HCF_MAX_ALGO_NAME_LEN) || (generator == NULL)) { + LOGE("Invalid input params while creating symkey!"); + return HCF_INVALID_PARAMS; + } + + SymKeyAttr attr = {0}; + if (ParseAndSetParameter(algoName, (void *)&attr, OnSetSymKeyParameter) != HCF_SUCCESS) { + LOGE("ParseAndSetParameter Failed!"); + return HCF_NOT_SUPPORT; + } + + const SymKeyGenFuncSet *funcSet = FindAbility(&attr); + if (funcSet == NULL) { + LOGE("FindAbility Failed!"); + return HCF_NOT_SUPPORT; + } + HcfSymmKeyGeneratorImpl *returnGenerator = (HcfSymmKeyGeneratorImpl *)HcfMalloc(sizeof(HcfSymmKeyGeneratorImpl), 0); + if (returnGenerator == NULL) { + LOGE("Failed to allocate returnGenerator memory!"); + return HCF_ERR_MALLOC; + } + if (strcpy_s(returnGenerator->algoName, HCF_MAX_ALGO_NAME_LEN, algoName)) { + LOGE("Failed to copy algoName!"); + HcfFree(returnGenerator); + return HCF_ERR_COPY; + } + OH_HCF_SymKeyGeneratorSpi *spiObj = NULL; + int32_t res = funcSet->createFunc(&attr, &spiObj); + if (res != HCF_SUCCESS) { + LOGE("Failed to create spi object!"); + HcfFree(returnGenerator); + return res; + } + returnGenerator->base.generateSymKey = GenerateSymmKey; + returnGenerator->base.convertSymKey = ConvertSymmKey; + returnGenerator->base.base.destroy = DestroySymmKeyGenerator; + returnGenerator->base.base.getClass = GetSymKeyGeneratorClass; + returnGenerator->base.getAlgoName = GetAlgoName; + returnGenerator->spiObj = spiObj; + + *generator = (HcfSymKeyGenerator *)returnGenerator; + return HCF_SUCCESS; +} diff --git a/frameworks/rand/rand.c b/frameworks/rand/rand.c new file mode 100644 index 0000000..36ca734 --- /dev/null +++ b/frameworks/rand/rand.c @@ -0,0 +1,134 @@ +/* + * Copyright (C) 2022 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 "rand.h" +#include +#include "rand_spi.h" +#include "rand_openssl.h" +#include "log.h" +#include "config.h" +#include "memory.h" +#include "utils.h" + +typedef HcfResult (*HcfRandSpiCreateFunc)(HcfRandSpi **); + +typedef struct { + HcfRand base; + + HcfRandSpi *spiObj; + + const char *algoName; +} HcfRandImpl; + +typedef struct { + char *algoName; + + HcfRandSpiCreateFunc createSpifunc; +} HcfRandAbility; + +static const HcfRandAbility RAND_ABILITY_SET[] = { + { "OpensslRand", HcfRandSpiCreate } +}; + +static const char *GetRandClass(void) +{ + return "Rand"; +} + +static HcfRandSpiCreateFunc FindAbility(const char *algoName) +{ + for (uint32_t i = 0; i < (sizeof(RAND_ABILITY_SET) / sizeof(RAND_ABILITY_SET[0])); i++) { + if (strcmp(RAND_ABILITY_SET[i].algoName, algoName) == 0) { + return RAND_ABILITY_SET[i].createSpifunc; + } + } + LOGE("Algo not support! [Algo]: %s", algoName); + return NULL; +} + +static HcfResult GenerateRandom(HcfRand *self, int32_t numBytes, HcfBlob *random) +{ + if ((self == NULL) || (numBytes <= 0) || (random == NULL)) { + LOGE("Invalid params!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetRandClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfRandImpl *)self)->spiObj->engineGenerateRandom( + ((HcfRandImpl *)self)->spiObj, numBytes, random); +} + +static HcfResult SetSeed(HcfRand *self, HcfBlob *seed) +{ + if ((self == NULL) || (!IsBlobValid(seed))) { + LOGE("The input self ptr is NULL!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetRandClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + return ((HcfRandImpl *)self)->spiObj->engineSetSeed( + ((HcfRandImpl *)self)->spiObj, seed); +} + +static void HcfRandDestroy(HcfObjectBase *self) +{ + if (self == NULL) { + LOGE("The input self ptr is NULL!"); + return; + } + if (!IsClassMatch((HcfObjectBase *)self, GetRandClass())) { + LOGE("Class is not match."); + return; + } + HcfRandImpl *impl = (HcfRandImpl *)self; + OH_HCF_ObjDestroy(impl->spiObj); + HcfFree(impl); +} + +HcfResult HcfRandCreate(HcfRand **randApi) +{ + if (randApi == NULL) { + LOGE("Invalid input params while creating rand!"); + return HCF_INVALID_PARAMS; + } + HcfRandSpiCreateFunc createSpifunc = FindAbility("OpensslRand"); + if (createSpifunc == NULL) { + LOGE("Algo not supported!"); + return HCF_NOT_SUPPORT; + } + HcfRandImpl *returnRandApi = (HcfRandImpl *)HcfMalloc(sizeof(HcfRandImpl), 0); + if (returnRandApi == NULL) { + LOGE("Failed to allocate Rand Obj memory!"); + return HCF_ERR_MALLOC; + } + HcfRandSpi *spiObj = NULL; + HcfResult res = createSpifunc(&spiObj); + if (res != HCF_SUCCESS) { + LOGE("Failed to create spi object!"); + HcfFree(returnRandApi); + return res; + } + returnRandApi->base.base.getClass = GetRandClass; + returnRandApi->base.base.destroy = HcfRandDestroy; + returnRandApi->base.generateRandom = GenerateRandom; + returnRandApi->base.setSeed = SetSeed; + returnRandApi->spiObj = spiObj; + *randApi = (HcfRand *)returnRandApi; + return HCF_SUCCESS; +} \ No newline at end of file diff --git a/frameworks/spi/asy_key_generator_spi.h b/frameworks/spi/asy_key_generator_spi.h new file mode 100644 index 0000000..95f341f --- /dev/null +++ b/frameworks/spi/asy_key_generator_spi.h @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2022 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_ASY_KEY_GENERATOR_SPI_H +#define HCF_ASY_KEY_GENERATOR_SPI_H + +#include +#include "algorithm_parameter.h" +#include "result.h" +#include "key_pair.h" + +#define OPENSSL_ASY_KEYGEN_PARAMS_TYPE "OPENSSL.ASY.KEYGENPARAMS" + +#define OPENSSL_RSA_GENERATOR_CLASS "OPENSSL.RSA.KEYGENERATOR" + +#define OPENSSL_RSA_KEY_FORMAT "OPENSSL.RSA.KEYFORMAT.DEFAULT" + +#define OPENSSL_RSA_ALGORITHM "OPENSSL.RSA" + +#define OPENSSL_RSA_KEY_FORMAT "OPENSSL.RSA.KEYFORMAT.DEFAULT" + +typedef struct HcfAsyKeyGeneratorSpi HcfAsyKeyGeneratorSpi; + +struct HcfAsyKeyGeneratorSpi { + HcfObjectBase base; + + HcfResult (*engineGenerateKeyPair)(HcfAsyKeyGeneratorSpi *self, HcfKeyPair **returnObj); + + HcfResult (*engineConvertKey)(HcfAsyKeyGeneratorSpi *self, HcfParamsSpec *params, HcfBlob *pubKeyBlob, + HcfBlob *priKeyBlob, HcfKeyPair **returnKeyPair); +}; + +#endif diff --git a/frameworks/spi/cert_chain_validator_spi.h b/frameworks/spi/cert_chain_validator_spi.h new file mode 100644 index 0000000..77ffa10 --- /dev/null +++ b/frameworks/spi/cert_chain_validator_spi.h @@ -0,0 +1,30 @@ +/* + * Copyright (C) 2022 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_CERT_CHAIN_VALIDATOR_SPI_H +#define HCF_CERT_CHAIN_VALIDATOR_SPI_H + +#include "blob.h" +#include "object_base.h" +#include "result.h" + +typedef struct HcfCertChainValidatorSpi HcfCertChainValidatorSpi; + +struct HcfCertChainValidatorSpi { + HcfObjectBase base; + HcfResult (*engineValidate)(HcfCertChainValidatorSpi *self, const HcfArray *certsList); +}; + +#endif // HCF_CERT_CHAIN_VALIDATOR_SPI_H diff --git a/frameworks/spi/cipher_factory_spi.h b/frameworks/spi/cipher_factory_spi.h new file mode 100644 index 0000000..d53bb8a --- /dev/null +++ b/frameworks/spi/cipher_factory_spi.h @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2022 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_CIPHER_FACTORY_SPI_H +#define HCF_CIPHER_FACTORY_SPI_H + +#include +#include "cipher.h" +#include "algorithm_parameter.h" +#include "key.h" +#include "blob.h" +#include "result.h" +#include "params_parser.h" + +typedef struct OH_HCF_CipherGeneratorSpi OH_HCF_CipherGeneratorSpi; + +struct OH_HCF_CipherGeneratorSpi { + HcfObjectBase base; + + HcfResult (*init)(OH_HCF_CipherGeneratorSpi *self, enum HcfCryptoMode opMode, + HcfKey *key, HcfParamsSpec *params); + + HcfResult (*update)(OH_HCF_CipherGeneratorSpi *self, HcfBlob *input, HcfBlob *output); + + HcfResult (*doFinal)(OH_HCF_CipherGeneratorSpi *self, HcfBlob *input, HcfBlob *output); +}; + +#endif diff --git a/frameworks/spi/key_agreement_spi.h b/frameworks/spi/key_agreement_spi.h new file mode 100644 index 0000000..79debed --- /dev/null +++ b/frameworks/spi/key_agreement_spi.h @@ -0,0 +1,33 @@ +/* + * Copyright (C) 2022 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_KEY_AGREEMENT_SPI_H +#define HCF_KEY_AGREEMENT_SPI_H + +#include "blob.h" +#include "pri_key.h" +#include "pub_key.h" +#include "result.h" + +typedef struct HcfKeyAgreementSpi HcfKeyAgreementSpi; + +struct HcfKeyAgreementSpi { + HcfObjectBase base; + + HcfResult (*engineGenerateSecret)(HcfKeyAgreementSpi *self, HcfPriKey *priKey, + HcfPubKey *pubKey, HcfBlob *returnSecret); +}; + +#endif diff --git a/frameworks/spi/mac_spi.h b/frameworks/spi/mac_spi.h new file mode 100644 index 0000000..bea4a6e --- /dev/null +++ b/frameworks/spi/mac_spi.h @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2022 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_MAC_SPI_H +#define HCF_MAC_SPI_H + +#include +#include "result.h" +#include "sym_key.h" + +typedef struct HcfMacSpi HcfMacSpi; + +struct HcfMacSpi { + HcfObjectBase base; + // init the Mac with given key + HcfResult (*engineInitMac)(HcfMacSpi *self, const HcfSymKey *key); + // update mac with input datablob + HcfResult (*engineUpdateMac)(HcfMacSpi *self, HcfBlob *input); + // output mac in output datablob + HcfResult (*engineDoFinalMac)(HcfMacSpi *self, HcfBlob *output); + // get the length of chosen hash algo + uint32_t (*engineGetMacLength)(HcfMacSpi *self); +}; + +#endif \ No newline at end of file diff --git a/frameworks/spi/md_spi.h b/frameworks/spi/md_spi.h new file mode 100644 index 0000000..9fe1d1d --- /dev/null +++ b/frameworks/spi/md_spi.h @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2022 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_MD_SPI_H +#define HCF_MD_SPI_H + +#include +#include "result.h" +#include "blob.h" +#include "object_base.h" + +typedef struct HcfMdSpi HcfMdSpi; + +struct HcfMdSpi { + HcfObjectBase base; + + HcfResult (*engineUpdateMd)(HcfMdSpi *self, HcfBlob *input); + + HcfResult (*engineDoFinalMd)(HcfMdSpi *self, HcfBlob *output); + + uint32_t (*engineGetMdLength)(HcfMdSpi *self); +}; + +#endif \ No newline at end of file diff --git a/frameworks/spi/rand_spi.h b/frameworks/spi/rand_spi.h new file mode 100644 index 0000000..6c81b51 --- /dev/null +++ b/frameworks/spi/rand_spi.h @@ -0,0 +1,34 @@ +/* + * Copyright (C) 2022 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_RAND_SPI_H +#define HCF_RAND_SPI_H + +#include +#include "result.h" +#include "blob.h" +#include "object_base.h" + +typedef struct HcfRandSpi HcfRandSpi; + +struct HcfRandSpi { + HcfObjectBase base; + + HcfResult (*engineGenerateRandom)(HcfRandSpi *self, int32_t numBytes, HcfBlob *random); + + HcfResult (*engineSetSeed)(HcfRandSpi *self, HcfBlob *seed); +}; + +#endif \ No newline at end of file diff --git a/frameworks/spi/signature_spi.h b/frameworks/spi/signature_spi.h new file mode 100644 index 0000000..971a07a --- /dev/null +++ b/frameworks/spi/signature_spi.h @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2022 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_SIGNATURE_SPI_H +#define HCF_SIGNATURE_SPI_H + +#include +#include "algorithm_parameter.h" +#include "pri_key.h" +#include "pub_key.h" +#include "result.h" + +#define OPENSSL_RSA_SIGN_CLASS "OPENSSL.RSA.SIGN" + +#define OPENSSL_RSA_VERIFY_CLASS "OPENSSL.RSA.VERIFY" + +typedef struct HcfSignSpi HcfSignSpi; + +struct HcfSignSpi { + HcfObjectBase base; + + HcfResult (*engineInit)(HcfSignSpi *self, HcfParamsSpec *params, HcfPriKey *privateKey); + + HcfResult (*engineUpdate)(HcfSignSpi *self, HcfBlob *data); + + HcfResult (*engineSign)(HcfSignSpi *self, HcfBlob *data, HcfBlob *returnSignatureData); +}; + +typedef struct HcfVerifySpi HcfVerifySpi; + +struct HcfVerifySpi { + HcfObjectBase base; + + HcfResult (*engineInit)(HcfVerifySpi *self, HcfParamsSpec *params, HcfPubKey *publicKey); + + HcfResult (*engineUpdate)(HcfVerifySpi *self, HcfBlob *data); + + bool (*engineVerify)(HcfVerifySpi *self, HcfBlob *data, HcfBlob *signatureData); +}; + +#endif diff --git a/frameworks/spi/sym_key_factory_spi.h b/frameworks/spi/sym_key_factory_spi.h new file mode 100644 index 0000000..c8ff9dc --- /dev/null +++ b/frameworks/spi/sym_key_factory_spi.h @@ -0,0 +1,33 @@ +/* + * Copyright (C) 2022 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_SYM_KEY_FACTORY_SPI_H +#define HCF_SYM_KEY_FACTORY_SPI_H + +#include +#include "result.h" +#include "sym_key.h" + +typedef struct OH_HCF_SymKeyGeneratorSpi OH_HCF_SymKeyGeneratorSpi; + +struct OH_HCF_SymKeyGeneratorSpi { + HcfObjectBase base; + HcfResult (*engineGenerateSymmKey)(OH_HCF_SymKeyGeneratorSpi *self, HcfSymKey **symmKey); + HcfResult (*engineConvertSymmKey)(OH_HCF_SymKeyGeneratorSpi *self, const HcfBlob *key, HcfSymKey **symmKey); +}; +#define OPENSSL_SYM_GENERATOR_CLASS "OPENSSL.SYM.KEYGENERATOR" +#define OPENSSL_SYM_KEY_CLASS "OPENSSL.SYM.KEY" + +#endif // HCF_SYMM_KEY_FACTORY_SPI_H diff --git a/frameworks/spi/x509_certificate_spi.h b/frameworks/spi/x509_certificate_spi.h new file mode 100644 index 0000000..e7642cd --- /dev/null +++ b/frameworks/spi/x509_certificate_spi.h @@ -0,0 +1,68 @@ +/* + * Copyright (C) 2022 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_X509_CERTIFICATE_SPI_H +#define HCF_X509_CERTIFICATE_SPI_H + +#include "blob.h" +#include "object_base.h" +#include "pub_key.h" +#include "result.h" + +typedef struct HcfX509CertificateSpi HcfX509CertificateSpi; + +struct HcfX509CertificateSpi { + HcfObjectBase base; + + HcfResult (*engineVerify)(HcfX509CertificateSpi *self, HcfPubKey *key); + + HcfResult (*engineGetEncoded)(HcfX509CertificateSpi *self, HcfEncodingBlob *encodedByte); + + HcfResult (*engineGetPublicKey)(HcfX509CertificateSpi *self, HcfPubKey **keyOut); + + HcfResult (*engineCheckValidityWithDate)(HcfX509CertificateSpi *self, const char *date); + + long (*engineGetVersion)(HcfX509CertificateSpi *self); + + long (*engineGetSerialNumber)(HcfX509CertificateSpi *self); + + HcfResult (*engineGetIssuerName)(HcfX509CertificateSpi *self, HcfBlob *out); + + HcfResult (*engineGetSubjectName)(HcfX509CertificateSpi *self, HcfBlob *out); + + HcfResult (*engineGetNotBeforeTime)(HcfX509CertificateSpi *self, HcfBlob *outDate); + + HcfResult (*engineGetNotAfterTime)(HcfX509CertificateSpi *self, HcfBlob *outDate); + + HcfResult (*engineGetSignature)(HcfX509CertificateSpi *self, HcfBlob *sigOut); + + HcfResult (*engineGetSignatureAlgName)(HcfX509CertificateSpi *self, HcfBlob *outName); + + HcfResult (*engineGetSignatureAlgOid)(HcfX509CertificateSpi *self, HcfBlob *out); + + HcfResult (*engineGetSignatureAlgParams)(HcfX509CertificateSpi *self, HcfBlob *sigAlgParamsOut); + + HcfResult (*engineGetKeyUsage)(HcfX509CertificateSpi *self, HcfBlob *boolArr); + + HcfResult (*engineGetExtKeyUsage)(HcfX509CertificateSpi *self, HcfArray *keyUsageOut); + + int32_t (*engineGetBasicConstraints)(HcfX509CertificateSpi *self); + + HcfResult (*engineGetSubjectAltNames)(HcfX509CertificateSpi *self, HcfArray *outName); + + HcfResult (*engineGetIssuerAltNames)(HcfX509CertificateSpi *self, HcfArray *outName); +}; + +#endif // HCF_X509_CERTIFICATE_SPI_H diff --git a/frameworks/spi/x509_crl_spi.h b/frameworks/spi/x509_crl_spi.h new file mode 100644 index 0000000..97be744 --- /dev/null +++ b/frameworks/spi/x509_crl_spi.h @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2022 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_X509_CRL_SPI_H +#define HCF_X509_CRL_SPI_H + +#include "blob.h" +#include "object_base.h" +#include "pub_key.h" +#include "result.h" +#include "x509_certificate.h" +#include "x509_crl_entry.h" + +typedef struct HcfX509CrlSpi HcfX509CrlSpi; + +struct HcfX509CrlSpi { + HcfObjectBase base; + + const char *(*engineGetType)(HcfX509CrlSpi *self); + + bool (*engineIsRevoked)(HcfX509CrlSpi *self, const HcfCertificate *cert); + + HcfResult (*engineGetEncoded)(HcfX509CrlSpi *self, HcfEncodingBlob *encodedByte); + + HcfResult (*engineVerify)(HcfX509CrlSpi *self, HcfPubKey *key); + + long (*engineGetVersion)(HcfX509CrlSpi *self); + + HcfResult (*engineGetIssuerName)(HcfX509CrlSpi *self, HcfBlob *out); + + HcfResult (*engineGetLastUpdate)(HcfX509CrlSpi *self, HcfBlob *out); + + HcfResult (*engineGetNextUpdate)(HcfX509CrlSpi *self, HcfBlob *out); + + HcfResult (*engineGetRevokedCert)(HcfX509CrlSpi *self, long serialNumber, HcfX509CrlEntry **entryOut); + + HcfResult (*engineGetRevokedCertWithCert)(HcfX509CrlSpi *self, HcfX509Certificate *cert, + HcfX509CrlEntry **entryOut); + + HcfResult (*engineGetRevokedCerts)(HcfX509CrlSpi *self, HcfArray *entrysOut); + + HcfResult (*engineGetTbsInfo)(HcfX509CrlSpi *self, HcfBlob *tbsCertListOut); + + HcfResult (*engineGetSignature)(HcfX509CrlSpi *self, HcfBlob *signature); + + HcfResult (*engineGetSignatureAlgName)(HcfX509CrlSpi *self, HcfBlob *out); + + HcfResult (*engineGetSignatureAlgOid)(HcfX509CrlSpi *self, HcfBlob *out); + + HcfResult (*engineGetSignatureAlgParams)(HcfX509CrlSpi *self, HcfBlob *sigAlgParamOut); +}; + +#endif // HCF_X509_CERTIFICATE_SPI_H diff --git a/interfaces/innerkits/algorithm_parameter/algorithm_parameter.h b/interfaces/innerkits/algorithm_parameter/algorithm_parameter.h new file mode 100644 index 0000000..a1e535c --- /dev/null +++ b/interfaces/innerkits/algorithm_parameter/algorithm_parameter.h @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2022 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_ALGORITHM_PARAMETER_H +#define HCF_ALGORITHM_PARAMETER_H + +#include + +/** + * @brief Provides an HcfParamsSpec instance. + * + * @since 9 + * @version 1.0 + */ +typedef struct HcfParamsSpec HcfParamsSpec; + +/** + * @brief Provide transparent algorithm parameters. + * + * @since 9 + * @version 1.0 + */ +struct HcfParamsSpec { + /** Get the actual type of the current algorithm parameter. */ + const char *(*getType)(void); +}; + +#endif diff --git a/interfaces/innerkits/algorithm_parameter/detailed_ccm_params.h b/interfaces/innerkits/algorithm_parameter/detailed_ccm_params.h new file mode 100644 index 0000000..8e47503 --- /dev/null +++ b/interfaces/innerkits/algorithm_parameter/detailed_ccm_params.h @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2022 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_DETAILED_CCM_PARAMS_H +#define HCF_DETAILED_CCM_PARAMS_H + +#include +#include "algorithm_parameter.h" +#include "blob.h" + +typedef struct HcfCcmParamsSpec HcfCcmParamsSpec; + +struct HcfCcmParamsSpec { + HcfParamsSpec base; + HcfBlob iv; + HcfBlob aad; + HcfBlob tag; +}; + +#endif // HCF_DETAILED_CCM_PARAMS_H diff --git a/interfaces/innerkits/algorithm_parameter/detailed_gcm_params.h b/interfaces/innerkits/algorithm_parameter/detailed_gcm_params.h new file mode 100644 index 0000000..6349666 --- /dev/null +++ b/interfaces/innerkits/algorithm_parameter/detailed_gcm_params.h @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2022 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_DETAILED_GCM_PARAMS_H +#define HCF_DETAILED_GCM_PARAMS_H + +#include +#include "algorithm_parameter.h" +#include "blob.h" + +typedef struct HcfGcmParamsSpec HcfGcmParamsSpec; + +struct HcfGcmParamsSpec { + HcfParamsSpec base; + HcfBlob iv; + HcfBlob aad; + HcfBlob tag; +}; + +#endif // HCF_DETAILED_GCM_PARAMS_H diff --git a/interfaces/innerkits/algorithm_parameter/detailed_iv_params.h b/interfaces/innerkits/algorithm_parameter/detailed_iv_params.h new file mode 100644 index 0000000..b5f962f --- /dev/null +++ b/interfaces/innerkits/algorithm_parameter/detailed_iv_params.h @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2022 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_DETAILED_IV_PARAMS_H +#define HCF_DETAILED_IV_PARAMS_H + +#include "algorithm_parameter.h" +#include "blob.h" + +typedef struct HcfIvParamsSpec HcfIvParamsSpec; + +struct HcfIvParamsSpec { + HcfParamsSpec base; + HcfBlob iv; +}; + +#endif // HCF_DETAILED_IV_PARAMS_H diff --git a/interfaces/innerkits/certificate/cert_chain_validator.h b/interfaces/innerkits/certificate/cert_chain_validator.h new file mode 100644 index 0000000..4c18244 --- /dev/null +++ b/interfaces/innerkits/certificate/cert_chain_validator.h @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2022 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_CERT_CHAIN_VALIDATOR_H +#define HCF_CERT_CHAIN_VALIDATOR_H + +#include +#include +#include "blob.h" +#include "object_base.h" +#include "result.h" + +typedef struct HcfCertChainValidator HcfCertChainValidator; + +typedef struct { + /* data format: len-value-len-value..., size of len is 2 bytes. */ + uint8_t *data; + uint32_t dataLen; + uint8_t count; + enum EncodingFormat format; +} HcfCertChainData; + +struct HcfCertChainValidator { + struct HcfObjectBase base; + + /** verify the cert chain. */ + HcfResult (*validate)(HcfCertChainValidator *self, const HcfCertChainData *certChainData); + + /** Get algorithm name. */ + const char *(*getAlgorithm)(HcfCertChainValidator *self); +}; + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Generate cert chain validator instance. + */ +HcfResult HcfCertChainValidatorCreate(const char *algorithm, HcfCertChainValidator **pathValidator); + +#ifdef __cplusplus +} +#endif + +#endif // HCF_CERT_CHAIN_VALIDATOR_H diff --git a/interfaces/innerkits/certificate/certificate.h b/interfaces/innerkits/certificate/certificate.h new file mode 100644 index 0000000..c64b1aa --- /dev/null +++ b/interfaces/innerkits/certificate/certificate.h @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2022 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_CERTIFICATE_H +#define HCF_CERTIFICATE_H + +#include "blob.h" +#include "object_base.h" +#include "pub_key.h" +#include "result.h" + +typedef struct HcfCertificate HcfCertificate; + +struct HcfCertificate { + struct HcfObjectBase base; + + /** Verify that this certificate corresponding to the specified public key. */ + HcfResult (*verify)(HcfCertificate *self, HcfPubKey *key); + + /** Get the serialized cert data.*/ + HcfResult (*getEncoded)(HcfCertificate *self, HcfEncodingBlob *encodedByte); + + /** Get the public key from this certificate. */ + HcfResult (*getPublicKey)(HcfCertificate *self, HcfPubKey **keyOut); +}; + +#endif // HCF_CERTIFICATE_H diff --git a/interfaces/innerkits/certificate/crl.h b/interfaces/innerkits/certificate/crl.h new file mode 100644 index 0000000..870e0fd --- /dev/null +++ b/interfaces/innerkits/certificate/crl.h @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2022 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_CRL_H +#define HCF_CRL_H + +#include + +#include "certificate.h" + +typedef struct HcfCrl HcfCrl; + +struct HcfCrl { + /** HcfCrl inherit HcfObjectBase. */ + struct HcfObjectBase base; + + /** Check if the given certificate is on this CRL. */ + bool (*isRevoked)(HcfCrl *self, const HcfCertificate *cert); + + /** Returns the type of this CRL. */ + const char *(*getType)(HcfCrl *self); +}; + +#endif // HCF_CRL_H diff --git a/interfaces/innerkits/certificate/x509_certificate.h b/interfaces/innerkits/certificate/x509_certificate.h new file mode 100644 index 0000000..75b5b36 --- /dev/null +++ b/interfaces/innerkits/certificate/x509_certificate.h @@ -0,0 +1,99 @@ +/* + * Copyright (C) 2022 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_X509_CERTIFICATE_H +#define HCF_X509_CERTIFICATE_H + +#include "certificate.h" +#include "blob.h" +#include "result.h" + +typedef struct HcfX509Certificate HcfX509Certificate; + +struct HcfX509Certificate { + /** HcfCX509Certificate inherit HcfCertificate. */ + HcfCertificate base; + + /** Check whether the certificate is valid at the given time. + * time format: YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ + */ + HcfResult (*checkValidityWithDate)(HcfX509Certificate *self, const char *date); + + /** Get version number from certificate. */ + long (*getVersion)(HcfX509Certificate *self); + + /** Get serial number from certificate. */ + long (*getSerialNumber)(HcfX509Certificate *self); + + /** Get issuer distinguished name from certificate. */ + HcfResult (*getIssuerName)(HcfX509Certificate *self, HcfBlob *out); + + /** Get subject distinguished name from certificate. */ + HcfResult (*getSubjectName)(HcfX509Certificate *self, HcfBlob *out); + + /** Get the not before time within the validity period of the certificate. + * time format: YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ + */ + HcfResult (*getNotBeforeTime)(HcfX509Certificate *self, HcfBlob *outDate); + + /** Get the not after time within the validity period of the certificate. + * time format: YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ + */ + HcfResult (*getNotAfterTime)(HcfX509Certificate *self, HcfBlob *outDate); + + /** Get signature value from certificate. */ + HcfResult (*getSignature)(HcfX509Certificate *self, HcfBlob *sigOut); + + /** Get signature algorithm name from certificate. */ + HcfResult (*getSignatureAlgName)(HcfX509Certificate *self, HcfBlob *outName); + + /** Get signature algorithm oid from certificate. */ + HcfResult (*getSignatureAlgOid)(HcfX509Certificate *self, HcfBlob *out); + + /** Get the DER encoded signature algorithm parameters from the signature algorithm of the certificate. */ + HcfResult (*getSignatureAlgParams)(HcfX509Certificate *self, HcfBlob *sigAlgParamsOut); + + /** Get a Boolean array representing the bits of keyuse extension. + * The key usage extension defines the purpose of the key. */ + HcfResult (*getKeyUsage)(HcfX509Certificate *self, HcfBlob *boolArr); + + /** Get a const string list that represents the object identifier of the extkeyusage. */ + HcfResult (*getExtKeyUsage)(HcfX509Certificate *self, HcfArray *keyUsageOut); + + /** Get the path length of the certificate constraint from the key extensions(BasicConstraints). + * The BasicConstraints identify whether the issuer of the certificate is CA and the depth of the cert chain. + * Only when CA is set to true, pathLenConstraint is meaningful. + */ + int32_t (*getBasicConstraints)(HcfX509Certificate *self); + + /** Get subject alternative name from certificate. */ + HcfResult (*getSubjectAltNames)(HcfX509Certificate *self, HcfArray *outName); + + /** Get issuer alternative name from certificate. */ + HcfResult (*getIssuerAltNames)(HcfX509Certificate *self, HcfArray *outName); +}; + +#ifdef __cplusplus +extern "C" { +#endif + +HcfResult HcfX509CertificateCreate(const HcfEncodingBlob *inStream, HcfX509Certificate **returnObj); + +#ifdef __cplusplus +} +#endif + +#endif // HCF_X509_CERTIFICATE_H + diff --git a/interfaces/innerkits/certificate/x509_crl.h b/interfaces/innerkits/certificate/x509_crl.h new file mode 100644 index 0000000..9b069f1 --- /dev/null +++ b/interfaces/innerkits/certificate/x509_crl.h @@ -0,0 +1,85 @@ +/* + * Copyright (C) 2022 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_X509CRL_H +#define HCF_X509CRL_H + +#include "blob.h" +#include "crl.h" +#include "pub_key.h" +#include "x509_certificate.h" +#include "x509_crl_entry.h" + +typedef struct HcfX509Crl HcfX509Crl; + +struct HcfX509Crl { + /** HcfX509Crl inherit HcfCrl. */ + HcfCrl base; + + /** Get the der coding format. */ + HcfResult (*getEncoded)(HcfX509Crl *self, HcfEncodingBlob *encodedOut); + + /** Use the public key to verify the signature of CRL. */ + HcfResult (*verify)(HcfX509Crl *self, HcfPubKey *key); + + /** Get version number from CRL. */ + long (*getVersion)(HcfX509Crl *self); + + /** Get the issuer name from CRL. Issuer means the entity that signs and publishes the CRL. */ + HcfResult (*getIssuerName)(HcfX509Crl *self, HcfBlob *out); + + /** Get lastUpdate value from CRL. */ + HcfResult (*getLastUpdate)(HcfX509Crl *self, HcfBlob *out); + + /** Get nextUpdate value from CRL. */ + HcfResult (*getNextUpdate)(HcfX509Crl *self, HcfBlob *out); + + /** This method can be used to find CRL entries in indirect CRLs. */ + HcfResult (*getRevokedCert)(HcfX509Crl *self, long serialNumber, HcfX509CrlEntry **entryOut); + + /** This method can be used to find CRL entries in indirect cert. */ + HcfResult (*getRevokedCertWithCert)(HcfX509Crl *self, HcfX509Certificate *cert, + HcfX509CrlEntry **entryOut); + + /** Get all entries in this CRL. */ + HcfResult (*getRevokedCerts)(HcfX509Crl *self, HcfArray *entrysOut); + + /** Get the CRL information encoded by Der from this CRL. */ + HcfResult (*getTbsInfo)(HcfX509Crl *self, HcfBlob *tbsCertListOut); + + /** Get signature value from CRL. */ + HcfResult (*getSignature)(HcfX509Crl *self, HcfBlob *signature); + + /** Get the signature algorithm name of the CRL signature algorithm. */ + HcfResult (*getSignatureAlgName)(HcfX509Crl *self, HcfBlob *out); + + /** Get the signature algorithm oid string from CRL. */ + HcfResult (*getSignatureAlgOid)(HcfX509Crl *self, HcfBlob *out); + + /** Get the der encoded signature algorithm parameters from the CRL signature algorithm. */ + HcfResult (*getSignatureAlgParams)(HcfX509Crl *self, HcfBlob *sigAlgParamOut); +}; + +#ifdef __cplusplus +extern "C" { +#endif + +HcfResult HcfX509CrlCreate(const HcfEncodingBlob *inStream, HcfX509Crl **returnObj); + +#ifdef __cplusplus +} +#endif + +#endif // HCF_X509CRL_H \ No newline at end of file diff --git a/interfaces/innerkits/certificate/x509_crl_entry.h b/interfaces/innerkits/certificate/x509_crl_entry.h new file mode 100644 index 0000000..e106563 --- /dev/null +++ b/interfaces/innerkits/certificate/x509_crl_entry.h @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2022 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_X509_CRL_ENTRY_H +#define HCF_X509_CRL_ENTRY_H + +#include "blob.h" +#include "object_base.h" +#include "result.h" + +typedef struct HcfX509CrlEntry HcfX509CrlEntry; + +struct HcfX509CrlEntry { + /** HcfX509CrlEntry inherit HcfObjectBase. */ + struct HcfObjectBase base; + + /** Returns the ASN of this CRL entry 1 der coding form, i.e. internal sequence. */ + HcfResult (*getEncoded)(HcfX509CrlEntry *self, HcfEncodingBlob *encodedOut); + + /** Get the serial number from this x509crl entry. */ + long (*getSerialNumber)(HcfX509CrlEntry *self); + + /** Gets the issuer of the x509 certificate described by this entry. */ + HcfResult (*getCertIssuer)(HcfX509CrlEntry *self, HcfBlob *encodedOut); + + /** Get the revocation date from x509crl entry. */ + HcfResult (*getRevocationDate)(HcfX509CrlEntry *self, HcfBlob *out); +}; + +#endif // HCF_X509_CRL_ENTRY_H \ No newline at end of file diff --git a/interfaces/innerkits/common/blob.h b/interfaces/innerkits/common/blob.h new file mode 100644 index 0000000..34f7144 --- /dev/null +++ b/interfaces/innerkits/common/blob.h @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2022 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_BLOB_H +#define HCF_BLOB_H + +#include +#include + +typedef struct HcfBlob HcfBlob; +struct HcfBlob { + uint8_t *data; + size_t len; +}; + +enum EncodingFormat { + HCF_FORMAT_DER = 0, + HCF_FORMAT_PEM = 1, +}; + +typedef struct { + uint8_t *data; + size_t len; + enum EncodingFormat encodingFormat; +} HcfEncodingBlob; + +typedef struct { + HcfBlob *data; + enum EncodingFormat format; + uint32_t count; +} HcfArray; + +#ifdef __cplusplus +extern "C" { +#endif + +void HcfBlobDataFree(HcfBlob *blob); +void HcfBlobDataClearAndFree(HcfBlob *blob); +void HcfEncodingBlobDataFree(HcfEncodingBlob *blob); +void HcfArrayDataClearAndFree(HcfArray *array); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/interfaces/innerkits/common/object_base.h b/interfaces/innerkits/common/object_base.h new file mode 100644 index 0000000..3e0960d --- /dev/null +++ b/interfaces/innerkits/common/object_base.h @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2022 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_OBJECT_BASE_H +#define HCF_OBJECT_BASE_H + +typedef struct HcfObjectBase HcfObjectBase; + +struct HcfObjectBase { + const char *(*getClass)(void); + void (*destroy)(HcfObjectBase *self); +}; + +#define OH_HCF_ObjDestroy(base) \ + if ((base) != NULL) { \ + ((HcfObjectBase *)(base))->destroy((HcfObjectBase *)(base)); \ + } + +#endif // HCF_OBJECT_BASE_H diff --git a/interfaces/innerkits/common/result.h b/interfaces/innerkits/common/result.h new file mode 100644 index 0000000..b968498 --- /dev/null +++ b/interfaces/innerkits/common/result.h @@ -0,0 +1,48 @@ +/* + * Copyright (C) 2022 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_RESULT_H +#define HCF_RESULT_H + +typedef enum HcfResult { + /** Indicates success. */ + HCF_SUCCESS = 0, + /** Indicates that input params is invalid . */ + HCF_INVALID_PARAMS = -10001, + /** Indicates that function or algorithm is not supported. */ + HCF_NOT_SUPPORT = -10002, + + /** Indicates that memory malloc fails. */ + HCF_ERR_MALLOC = 20001, + /** Indicates that memory copy fails. */ + HCF_ERR_COPY = -20002, + + /** Indicates that third part has something wrong. */ + HCF_ERR_CRYPTO_OPERATION = -30001, + /* Indicates that cert signature check fails. */ + HCF_ERR_CERT_SIGNATURE_FAILURE = -30002, + /* Indicates that cert is not yet valid. */ + HCF_ERR_CERT_NOT_YET_VALID = -30003, + /* Indicates that cert has expired. */ + HCF_ERR_CERT_HAS_EXPIRED = -30004, + /* Indicates that we can not get the untrusted cert's issuer. */ + HCF_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY = -30005, + /* Key usage does not include certificate sign. */ + HCF_ERR_KEYUSAGE_NO_CERTSIGN = -30006, + /* Key usage does not include digital sign. */ + HCF_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE = -30007, +} HcfResult; + +#endif diff --git a/interfaces/innerkits/crypto_operation/cipher.h b/interfaces/innerkits/crypto_operation/cipher.h new file mode 100644 index 0000000..0454c3d --- /dev/null +++ b/interfaces/innerkits/crypto_operation/cipher.h @@ -0,0 +1,79 @@ +/* + * Copyright (C) 2022 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_CIPHER_H +#define HCF_CIPHER_H + +#include "blob.h" +#include "key.h" +#include "algorithm_parameter.h" + +enum HcfCryptoMode { + /** + * The value of aes and 3des encrypt operation + * @syscap SystemCapability.Security.CryptoFramework + * @since 9 + */ + ENCRYPT_MODE = 0, + + /** + * The value of aes and 3des decrypt operation + * @syscap SystemCapability.Security.CryptoFramework + * @since 9 + */ + DECRYPT_MODE = 1, +}; + +typedef struct HcfCipher HcfCipher; +/** + * @brief his class provides cipher algorithms for cryptographic operations, + * mainly including encrypt and decrypt. + * + * @since 9 + * @version 1.0 + */ +struct HcfCipher { + HcfObjectBase base; + + HcfResult (*init)(HcfCipher *self, enum HcfCryptoMode opMode, + HcfKey *key, HcfParamsSpec *params); + + HcfResult (*update)(HcfCipher *self, HcfBlob *input, HcfBlob *output); + + HcfResult (*doFinal)(HcfCipher *self, HcfBlob *input, HcfBlob *output); + + const char *(*getAlgorithm)(HcfCipher *self); +}; + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Generate a corresponding cryptographic operation cipher object according to the algorithm name. + * + * @param algoName Specifies the type of generated cipher object. + * @param returnObj The address of the pointer to the generated cipher object. + * @return Returns the status code of the execution. + * @since 9 + * @version 1.0 + */ +HcfResult HcfCipherCreate(const char *algoName, HcfCipher **returnObj); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/interfaces/innerkits/crypto_operation/key_agreement.h b/interfaces/innerkits/crypto_operation/key_agreement.h new file mode 100644 index 0000000..ccf9d6c --- /dev/null +++ b/interfaces/innerkits/crypto_operation/key_agreement.h @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2022 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_KEY_AGREEMENT_H +#define HCF_KEY_AGREEMENT_H + +#include +#include "algorithm_parameter.h" +#include "result.h" +#include "key_pair.h" + +typedef struct HcfKeyAgreement HcfKeyAgreement; + +struct HcfKeyAgreement { + HcfObjectBase base; + + HcfResult (*generateSecret)(HcfKeyAgreement *self, HcfPriKey *priKey, + HcfPubKey *pubKey, HcfBlob *returnSecret); + + const char *(*getAlgoName)(HcfKeyAgreement *self); +}; + +#ifdef __cplusplus +extern "C" { +#endif + +HcfResult HcfKeyAgreementCreate(const char *algoName, HcfKeyAgreement **returnObj); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/interfaces/innerkits/crypto_operation/mac.h b/interfaces/innerkits/crypto_operation/mac.h new file mode 100644 index 0000000..f3ecfdd --- /dev/null +++ b/interfaces/innerkits/crypto_operation/mac.h @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2022 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_MAC_H +#define HCF_MAC_H + +#include +#include "blob.h" +#include "result.h" +#include "sym_key.h" +#include "object_base.h" + +typedef struct HcfMac HcfMac; + +struct HcfMac { + HcfObjectBase base; + + HcfResult (*init)(HcfMac *self, const HcfSymKey *key); + + HcfResult (*update)(HcfMac *self, HcfBlob *input); + + HcfResult (*doFinal)(HcfMac *self, HcfBlob *output); + + uint32_t (*getMacLength)(HcfMac *self); + + const char *(*getAlgoName)(HcfMac *self); +}; + +#ifdef __cplusplus +extern "C" { +#endif + +HcfResult HcfMacCreate(const char *algoName, HcfMac **mac); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/interfaces/innerkits/crypto_operation/md.h b/interfaces/innerkits/crypto_operation/md.h new file mode 100644 index 0000000..8d93cb4 --- /dev/null +++ b/interfaces/innerkits/crypto_operation/md.h @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2022 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_MD_H +#define HCF_MD_H + +#include "blob.h" +#include "result.h" +#include "object_base.h" + +typedef struct HcfMd HcfMd; + +struct HcfMd { + HcfObjectBase base; + + HcfResult (*update)(HcfMd *self, HcfBlob *input); + + HcfResult (*doFinal)(HcfMd *self, HcfBlob *output); + + uint32_t (*getMdLength)(HcfMd *self); + + const char *(*getAlgoName)(HcfMd *self); +}; + +#ifdef __cplusplus +extern "C" { +#endif + +HcfResult HcfMdCreate(const char *algoName, HcfMd **md); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/interfaces/innerkits/crypto_operation/signature.h b/interfaces/innerkits/crypto_operation/signature.h new file mode 100644 index 0000000..ea5b2be --- /dev/null +++ b/interfaces/innerkits/crypto_operation/signature.h @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2022 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_SIGNATURE_H +#define HCF_SIGNATURE_H + +#include +#include +#include "algorithm_parameter.h" +#include "result.h" +#include "key_pair.h" + +typedef struct HcfSign HcfSign; + +struct HcfSign { + HcfObjectBase base; + + HcfResult (*init)(HcfSign *self, HcfParamsSpec *params, HcfPriKey *privateKey); + + HcfResult (*update)(HcfSign *self, HcfBlob *data); + + HcfResult (*sign)(HcfSign *self, HcfBlob *data, HcfBlob *returnSignatureData); + + const char *(*getAlgoName)(HcfSign *self); +}; + +typedef struct HcfVerify HcfVerify; + +struct HcfVerify { + HcfObjectBase base; + + HcfResult (*init)(HcfVerify *self, HcfParamsSpec *params, HcfPubKey *publicKey); + + HcfResult (*update)(HcfVerify *self, HcfBlob *data); + + bool (*verify)(HcfVerify *self, HcfBlob *data, HcfBlob *signatureData); + + const char *(*getAlgoName)(HcfVerify *self); +}; + +#ifdef __cplusplus +extern "C" { +#endif + +HcfResult HcfSignCreate(const char *algoName, HcfSign **returnObj); + +HcfResult HcfVerifyCreate(const char *algoName, HcfVerify **returnObj); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/interfaces/innerkits/key/asy_key_generator.h b/interfaces/innerkits/key/asy_key_generator.h new file mode 100644 index 0000000..4c22dd8 --- /dev/null +++ b/interfaces/innerkits/key/asy_key_generator.h @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2022 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_ASY_KEY_GENERATOR_H +#define HCF_ASY_KEY_GENERATOR_H + +#include +#include "algorithm_parameter.h" +#include "result.h" +#include "key_pair.h" + +enum HcfRsaKeySize { + HCF_RSA_KEY_SIZE_512 = 512, + HCF_RSA_KEY_SIZE_768 = 768, + HCF_RSA_KEY_SIZE_1024 = 1024, + HCF_RSA_KEY_SIZE_2048 = 2048, + HCF_RSA_KEY_SIZE_3072 = 3072, + HCF_RSA_KEY_SIZE_4096 = 4096, + HCF_RSA_KEY_SIZE_8192 = 8192, +}; + +enum HcfRsaPrimesSize { + HCF_RSA_PRIMES_SIZE_2 = 2, + HCF_RSA_PRIMES_SIZE_3 = 3, + HCF_RSA_PRIMES_SIZE_4 = 4, + HCF_RSA_PRIMES_SIZE_5 = 5, +}; + +typedef struct HcfAsyKeyGenerator HcfAsyKeyGenerator; + +struct HcfAsyKeyGenerator { + HcfObjectBase base; + + HcfResult (*generateKeyPair)(HcfAsyKeyGenerator *self, HcfParamsSpec *params, + HcfKeyPair **returnKeyPair); + + HcfResult (*convertKey)(HcfAsyKeyGenerator *self, HcfParamsSpec *params, HcfBlob *pubKeyBlob, + HcfBlob *priKeyBlob, HcfKeyPair **returnKeyPair); + + const char *(*getAlgoName)(HcfAsyKeyGenerator *self); +}; + +#ifdef __cplusplus +extern "C" { +#endif + +HcfResult HcfAsyKeyGeneratorCreate(const char *algoName, HcfAsyKeyGenerator **returnObj); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/interfaces/innerkits/key/key.h b/interfaces/innerkits/key/key.h new file mode 100644 index 0000000..e19b7d3 --- /dev/null +++ b/interfaces/innerkits/key/key.h @@ -0,0 +1,35 @@ +/* + * Copyright (C) 2022 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_KEY_H +#define HCF_KEY_H + +#include "blob.h" +#include "result.h" +#include "object_base.h" + +typedef struct HcfKey HcfKey; + +struct HcfKey { + HcfObjectBase base; + + const char *(*getAlgorithm)(HcfKey *self); + + HcfResult (*getEncoded)(HcfKey *self, HcfBlob *returnBlob); + + const char *(*getFormat)(HcfKey *self); +}; + +#endif diff --git a/interfaces/innerkits/key/key_pair.h b/interfaces/innerkits/key/key_pair.h new file mode 100644 index 0000000..658dd2d --- /dev/null +++ b/interfaces/innerkits/key/key_pair.h @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2022 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_KEY_PAIR_H +#define HCF_KEY_PAIR_H + +#include "pri_key.h" +#include "pub_key.h" + +typedef struct HcfKeyPair HcfKeyPair; + +struct HcfKeyPair { + HcfObjectBase base; + + HcfPriKey *priKey; + + HcfPubKey *pubKey; +}; + +#endif diff --git a/interfaces/innerkits/key/pri_key.h b/interfaces/innerkits/key/pri_key.h new file mode 100644 index 0000000..7e047ef --- /dev/null +++ b/interfaces/innerkits/key/pri_key.h @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2022 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_PRI_KEY_H +#define HCF_PRI_KEY_H + +#include "key.h" + +typedef struct HcfPriKey HcfPriKey; + +struct HcfPriKey { + HcfKey base; + + void (*clearMem)(HcfPriKey *self); +}; + +#endif diff --git a/interfaces/innerkits/key/pub_key.h b/interfaces/innerkits/key/pub_key.h new file mode 100644 index 0000000..871e024 --- /dev/null +++ b/interfaces/innerkits/key/pub_key.h @@ -0,0 +1,27 @@ +/* + * Copyright (C) 2022 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_PUB_KEY_H +#define HCF_PUB_KEY_H + +#include "key.h" + +typedef struct HcfPubKey HcfPubKey; + +struct HcfPubKey { + HcfKey base; +}; + +#endif diff --git a/interfaces/innerkits/key/sym_key.h b/interfaces/innerkits/key/sym_key.h new file mode 100644 index 0000000..2b0a2af --- /dev/null +++ b/interfaces/innerkits/key/sym_key.h @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2022 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_SYM_KEY_H +#define HCF_SYM_KEY_H + +#include "key.h" + +/** + * @brief Provides an encapsulated HcfSymKey instance. + * + * @since 9 + * @version 1.0 + */ +typedef struct HcfSymKey HcfSymKey; + +/** + * @brief Provides common properties for symmetric key objects. + * + * @since 9 + * @version 1.0 + */ +struct HcfSymKey { + HcfKey key; + + void (*clearMem)(HcfSymKey *self); +}; + +#endif diff --git a/interfaces/innerkits/key/sym_key_generator.h b/interfaces/innerkits/key/sym_key_generator.h new file mode 100644 index 0000000..9a2c244 --- /dev/null +++ b/interfaces/innerkits/key/sym_key_generator.h @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2022 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_SYM_KEY_GENERATOR_H +#define HCF_SYM_KEY_GENERATOR_H + +#include +#include "result.h" +#include "sym_key.h" + +/** + * @brief Provides a wrapped HcfSymKeyGenerator instance. + * + * @since 9 + * @version 1.0 + */ +typedef struct HcfSymKeyGenerator HcfSymKeyGenerator; + +/** + * @brief Provides generation capabilities for symmetric key objects. + * + * @since 9 + * @version 1.0 + */ +struct HcfSymKeyGenerator { + HcfObjectBase base; + + /** Generate symmetric key object */ + HcfResult (*generateSymKey)(HcfSymKeyGenerator *self, HcfSymKey **symKey); + + /** Convert byte data to symmetric key object */ + HcfResult (*convertSymKey)(HcfSymKeyGenerator *self, const HcfBlob *key, HcfSymKey **symKey); + + /** Get the algorithm name of the current these key generator objects */ + const char *(*getAlgoName)(HcfSymKeyGenerator *self); +}; + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Generate a symmetric key generator object based on the algorithm name. + * + * @param algoName Specifies the type of generated symmetric key generator object. + * @param returnObj return pointer to generate symmetric key generator object. + * @return Returns the status code of the execution + * @since 9 + * @version 1.0 + */ +HcfResult HcfSymKeyGeneratorCreate(const char *algoName, HcfSymKeyGenerator **returnObj); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/interfaces/innerkits/rand/rand.h b/interfaces/innerkits/rand/rand.h new file mode 100644 index 0000000..d272a09 --- /dev/null +++ b/interfaces/innerkits/rand/rand.h @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2022 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_RAND_H +#define HCF_RAND_H + +#include +#include "result.h" +#include "object_base.h" + +#include "blob.h" + +typedef struct HcfRand HcfRand; + +struct HcfRand { + HcfObjectBase base; + + HcfResult (*generateRandom)(HcfRand *self, int32_t numBytes, HcfBlob *random); + + HcfResult (*setSeed)(HcfRand *self, HcfBlob *seed); +}; + +#ifdef __cplusplus +extern "C" { +#endif + +HcfResult HcfRandCreate(HcfRand **random); + +#ifdef __cplusplus +} +#endif + +#endif \ No newline at end of file diff --git a/interfaces/kits/js/@ohos.security.cryptoFramework.d.ts b/interfaces/kits/js/@ohos.security.cryptoFramework.d.ts new file mode 100644 index 0000000..32278ae --- /dev/null +++ b/interfaces/kits/js/@ohos.security.cryptoFramework.d.ts @@ -0,0 +1,481 @@ +/* + * Copyright (c) 2022 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 {AsyncCallback, Callback} from './basic'; + +/** + * Provides a set of encryption and decryption algorithm library framework, shields the underlying differences, + * encapsulates the relevant algorithm library, and provides a unified functional interface upward. + * + * @sysCap SystemCapability.Security.CryptoFramework. + * @import import cryptoFramework from '@ohos.security.cryptoFramework' + * @permission + * @since 9 + */ +declare namespace cryptoFramework { + /** + * Enum for result code + * @since 9 + */ + enum Result { + /** Indicates that input params is invalid. + * @since 9 + */ + INVALID_PARAMS = 401, + + /** Indicates that function or algorithm is not supported. + * @since 9 + */ + NOT_SUPPORT = 801, + + /** Indicates the out of memory error. + * @since 9 + */ + ERR_OUT_OF_MEMORY = 17620001, + + /** Indicates that internal error. + * @since 9 + */ + ERR_INTERNAL_ERROR = 17620002, + + /** Indicates that crypto operation has something wrong. + * @since 9 + */ + ERR_CRYPTO_OPERATION = 17630001, + + /* Indicates that cert signature check fails. + * @since 9 + */ + ERR_CERT_SIGNATURE_FAILURE = 17630002, + + /* Indicates that cert is not yet valid. + * @since 9 + */ + ERR_CERT_NOT_YET_VALID = 17630003, + + /* Indicates that cert has expired. + * @since 9 + */ + ERR_CERT_HAS_EXPIRED = 17630004, + + /* Indicates that we can not get the untrusted cert's issuer. + * @since 9 + */ + ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY = 17630005, + + /* Key usage does not include certificate sign. + * @since 9 + */ + ERR_KEYUSAGE_NO_CERTSIGN = 17630006, + + /* Key usage does not include digital sign. + * @since 9 + */ + ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE = 17630007, + } + + interface DataBlob { + data : Uint8Array; + } + + interface DataArray { + data : Array; + } + + /** + * Enum for supported cert encoding format + * @since 9 + */ + enum EncodingFormat { + /** + * The value of cert DER format + * @since 9 + */ + FORMAT_DER = 0, + + /** + * The value of cert PEM format + * @since 9 + */ + FORMAT_PEM = 1, + } + + interface EncodingBlob { + data : Uint8Array; + encodingFormat : EncodingFormat; + } + + interface CertChainData { + data: Uint8Array; + count : number; + encodingFormat: EncodingFormat; + } + + interface ParamsSpec { + algoName : string; + } + + interface IvParamsSpec extends ParamsSpec { + iv : DataBlob; + } + + interface GcmParamsSpec extends ParamsSpec { + iv : DataBlob; + aad : DataBlob; + authTag : DataBlob; + } + + interface CcmParamsSpec extends ParamsSpec { + iv : DataBlob; + aad : DataBlob; + authTag : DataBlob; + } + + /** + * Enum for obtain the crypto operation. + * @since 9 + */ + enum CryptoMode { + /** + * The value of aes and 3des encrypt operation + * @since 9 + */ + ENCRYPT_MODE = 0, + + /** + * The value of aes and 3des decrypt operation + * @since 9 + */ + DECRYPT_MODE = 1, + } + + interface Key { + getEncoded() : DataBlob; + readonly format : string; + readonly algName : string; + } + + interface SymKey extends Key { + clearMem() : void; + } + + interface PriKey extends Key { + clearMem() : void; + } + + interface PubKey extends Key {} + + interface KeyPair { + readonly priKey : PriKey; + readonly pubKey : PubKey; + } + + interface Random { + generateRandom(len : number, callback: AsyncCallback) : void; + generateRandom(len : number) : Promise; + setSeed(seed : DataBlob, callback : AsyncCallback) : void; + setSeed(seed : DataBlob) : Promise; + } + + /** + * Provides the rand create func. + * + * @sysCap SystemCapability.Security.CryptoFramework. + * @import import cryptoFramework from '@ohos.security.cryptoFramework' + * @permission + * @since 9 + * @param callback Indicates the callback for the rand create result. + */ + function createRandom() : Random; + + interface AsyKeyGenerator { + generateKeyPair(callback : AsyncCallback) : void; + generateKeyPair() : Promise; + convertKey(pubKey : DataBlob, priKey : DataBlob, callback : AsyncCallback) : void; + convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise; + readonly algName : string; + } + + interface SymKeyGenerator { + generateSymKey(callback : AsyncCallback) : void; + generateSymKey() : Promise; + convertKey(key : DataBlob, callback : AsyncCallback) : void; + convertKey(key : DataBlob) : Promise; + readonly algName : string; + } + + /** + * Provides the asy key generator instance func. + * + * @sysCap SystemCapability.Security.CryptoFramework. + * @import import cryptoFramework from '@ohos.security.cryptoFramework' + * @permission + * @since 9 + * @param algName Indicates the algorithm name. + */ + function createAsyKeyGenerator(algName : string) : AsyKeyGenerator; + + /** + * Provides the sym key generator instance func. + * + * @sysCap SystemCapability.Security.CryptoFramework. + * @import import cryptoFramework from '@ohos.security.cryptoFramework' + * @permission + * @since 9 + * @param algName Indicates the algorithm name. + * @param callback Indicates the callback for get the sym key generator instance result. + */ + function createSymKeyGenerator(algName : string) : SymKeyGenerator; + + interface Mac { + init(key : SymKey, callback : AsyncCallback) : void; + init(key : SymKey) : Promise; + update(input : DataBlob, callback : AsyncCallback) : void; + update(input : DataBlob) : Promise; + doFinal(callback : AsyncCallback) : void; + doFinal() : Promise; + getMacLength() : number; + readonly algName : string; + } + + /** + * Provides the mac create func. + * + * @sysCap SystemCapability.Security.CryptoFramework. + * @import import cryptoFramework from '@ohos.security.cryptoFramework' + * @permission + * @since 9 + * @param algName Indicates the mac algorithm name. + * @param callback Indicates the callback for the mac create result. + */ + function createMac(algName : string) : Mac; + + interface Md { + update(input : DataBlob, callback : AsyncCallback) : void; + update(input : DataBlob) : Promise; + digest(callback : AsyncCallback) : void; + digest() : Promise; + getMdLength() : number; + readonly algName : string; + } + + /** + * Provides the md create func. + * + * @sysCap SystemCapability.Security.CryptoFramework. + * @import import cryptoFramework from '@ohos.security.cryptoFramework' + * @permission + * @since 9 + * @param algorithm Indicates the md algorithm. + * @param callback Indicates the callback for the md create result. + */ + function createMd(algName : string) : Md; + + interface Cipher { + init(opMode : CryptoMode, key : Key, params : ParamsSpec, callback : AsyncCallback) : void; + init(opMode : CryptoMode, key : Key, params : ParamsSpec) : Promise; + update(data : DataBlob, callback : AsyncCallback) : void; + update(data : DataBlob) : Promise; + doFinal(data : DataBlob, callback : AsyncCallback) : void; + doFinal(data : DataBlob) : Promise; + readonly algName : string; + } + + /** + * Provides the cipher create func. + * + * @sysCap SystemCapability.Security.CryptoFramework. + * @import import cryptoFramework from '@ohos.security.cryptoFramework' + * @permission + * @since 9 + * @param transformation Indicates the transform type. + * @param callback Indicates the callback for the cipher create result. + */ + function createCipher(transformation : string) : Cipher; + + interface Sign { + init(priKey : PriKey, callback : AsyncCallback) : void; + init(priKey : PriKey) : Promise; + update(data : DataBlob, callback : AsyncCallback) : void; + update(data : DataBlob) : Promise; + sign(data : DataBlob, callback : AsyncCallback) : void; + sign(data : DataBlob) : Promise; + readonly algName : string; + } + + interface Verify { + init(pubKey : PubKey, callback : AsyncCallback) : void; + init(pubKey : PubKey) : Promise; + update(data : DataBlob, callback : AsyncCallback) : void; + update(data : DataBlob) : Promise; + verify(data : DataBlob, signatureData : DataBlob, callback : AsyncCallback) : void; + verify(data : DataBlob, signatureData : DataBlob) : Promise; + readonly algName : string; + } + + /** + * Provides the sign func. + * + * @sysCap SystemCapability.Security.CryptoFramework. + * @import import cryptoFramework from '@ohos.security.cryptoFramework' + * @permission + * @since 9 + * @param algName Indicates the sign algorithm name. + */ + function createSign(algName : string) : Sign; + + /** + * Provides the verify func. + * + * @sysCap SystemCapability.Security.CryptoFramework. + * @import import cryptoFramework from '@ohos.security.cryptoFramework' + * @permission + * @since 9 + * @param algName Indicates the verify algorithm name. + */ + function createVerify(algName : string) : Verify; + + interface KeyAgreement { + generateSecret(priKey : PriKey, pubKey : PubKey, callback : AsyncCallback) : void; + generateSecret(priKey : PriKey, pubKey : PubKey) : Promise; + readonly algName : string; + } + + /** + * Provides the key agree func. + * + * @sysCap SystemCapability.Security.CryptoFramework. + * @import import cryptoFramework from '@ohos.security.cryptoFramework' + * @permission + * @since 9 + * @param algName Indicates the key agreement algorithm name. + */ + function createKeyAgreement(algName : string) : KeyAgreement; + + interface X509Cert { + verify(key : PubKey, callback : AsyncCallback) : void; + verify(key : PubKey) : Promise; + getEncoded(callback : AsyncCallback) : void; + getEncoded() : Promise; + getPublicKey(callback : AsyncCallback) : void; + getPublicKey() : Promise; + checkValidityWithDate(date: string, callback : AsyncCallback) : void; + checkValidityWithDate(date: string) : Promise; + getVersion() : number; + getSerialNumber() : number; + getIssuerName() : DataBlob; + getSubjectName() : DataBlob; + getNotBeforeTime() : string; + getNotAfterTime() : string; + getSignature() : DataBlob; + getSignatureAlgName() : string; + getSignatureAlgOid() : string; + getSignatureAlgParams() : DataBlob; + getKeyUsage() : DataBlob; + getExtKeyUsage() : DataArray; + getBasicConstraints() : number; + getSubjectAltNames() : DataArray; + getIssuerAltNames() : DataArray; + } + + /** + * Provides the x509 cert func. + * + * @sysCap SystemCapability.Security.CryptoFramework. + * @import import cryptoFramework from '@ohos.security.cryptoFramework' + * @permission + * @since 9 + * @param inStream Indicates the input cert data. + * @param callback Indicates the callback for the x509 cert create. + */ + function createX509Cert(inStream : EncodingBlob, callback : AsyncCallback) : void; + function createX509Cert(inStream : EncodingBlob) : Promise; + + interface X509CrlEntry { + getEncoded(callback : AsyncCallback) : void; + getEncoded() : Promise; + getSerialNumber() : number; + getCertIssuer(callback : AsyncCallback) : void; + getCertIssuer() : Promise; + getRevocationDate(callback : AsyncCallback) : void; + getRevocationDate() : Promise; + } + + interface X509Crl { + isRevoked(cert : X509Cert, callback : AsyncCallback) : void; + isRevoked(cert : X509Cert) : Promise; + getType() : string; + getEncoded(callback : AsyncCallback) : void; + getEncoded() : Promise; + verify(key : PubKey, callback : AsyncCallback) : void; + verify(key : PubKey) : Promise; + getVersion() : number; + getIssuerName() : DataBlob; + getLastUpdate() : string; + getNextUpdate() : string; + getRevokedCert(serialNumber : number, callback : AsyncCallback) : void; + getRevokedCert(serialNumber : number) : Promise; + getRevokedCertWithCert(cert : X509Cert, callback : AsyncCallback) : void; + getRevokedCertWithCert(cert : X509Cert) : Promise; + getRevokedCerts(callback : AsyncCallback>) : void; + getRevokedCerts() : Promise>; + getTbsInfo(callback : AsyncCallback) : void; + getTbsInfo() : Promise; + getSignature() : DataBlob; + getSignatureAlgName() : string; + getSignatureAlgOid() : string; + getSignatureAlgParams() : DataBlob; + } + + /** + * Provides the x509 CRL func. + * + * @sysCap SystemCapability.Security.CryptoFramework. + * @import import cryptoFramework from '@ohos.security.cryptoFramework' + * @permission + * @since 9 + * @param inStream Indicates the input CRL data. + * @param callback Indicates the callback for the x509 CRL create. + */ + function createX509Crl(inStream : EncodingBlob, callback : AsyncCallback) : void; + function createX509Crl(inStream : EncodingBlob) : Promise; + + /** + * Certification chain validator. + * @since 9 + * @syscap SystemCapability.Security.CryptoFramework + */ + + interface CertChainValidator { + validate(certChain : CertChainData, callback : AsyncCallback) : void; + validate(certChain : CertChainData) : Promise; + readonly algorithm : string; + } + + /** + * Provides the cert chain validator func. + * + * @sysCap SystemCapability.Security.CryptoFramework. + * @import import cryptoFramework from '@ohos.security.cryptoFramework' + * @permission + * @since 9 + * @param algorithm Indicates the cert chain validator type. + * @param callback Indicates the callback for the cert chain validator result. + */ + function createCertChainValidator(algorithm :string) : CertChainValidator; +} + +export default cryptoFramework; diff --git a/plugin/BUILD.gn b/plugin/BUILD.gn new file mode 100644 index 0000000..d41e665 --- /dev/null +++ b/plugin/BUILD.gn @@ -0,0 +1,52 @@ +# Copyright (C) 2022 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("//build/ohos.gni") +import("//base/security/crypto_framework/plugin/plugin.gni") +import("//base/security/crypto_framework/common/common.gni") + +config("plugin_config") { + include_dirs = [ + "//base/security/crypto_framework/interfaces/innerkits/algorithm_parameter", + "//base/security/crypto_framework/interfaces/innerkits/certificate", + "//base/security/crypto_framework/interfaces/innerkits/common", + "//base/security/crypto_framework/interfaces/innerkits/crypto_operation", + "//base/security/crypto_framework/interfaces/innerkits/key", + "//base/security/crypto_framework/interfaces/innerkits/rand", + "//base/security/crypto_framework/frameworks/spi", + ] +} + +ohos_shared_library("crypto_openssl_plugin_lib") { + subsystem_name = "security" + part_name = "crypto_framework" + public_configs = [ ":plugin_config" ] + include_dirs = [ + "//utils/native/base/include", + "//third_party/openssl/include/", + ] + include_dirs += plugin_inc_path + crypto_framwork_common_inc_path + + sources = plugin_files + + cflags = [ + "-fPIC", + "-Wall", + ] + + deps = [ + "//utils/native/base:utils", + "//third_party/openssl:libcrypto_shared", + "//base/security/crypto_framework/common:crypto_plugin_common", + ] +} \ No newline at end of file diff --git a/plugin/openssl_plugin/certificate/inc/x509_cert_chain_validator_openssl.h b/plugin/openssl_plugin/certificate/inc/x509_cert_chain_validator_openssl.h new file mode 100644 index 0000000..86d2103 --- /dev/null +++ b/plugin/openssl_plugin/certificate/inc/x509_cert_chain_validator_openssl.h @@ -0,0 +1,33 @@ +/* + * Copyright (C) 2022 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 "result.h" +#include "cert_chain_validator_spi.h" + +#ifndef X509_CERT_CHAIN_VALIDATOR_OEPNSSL_H +#define X509_CERT_CHAIN_VALIDATOR_OEPNSSL_H + + +#ifdef __cplusplus +extern "C" { +#endif + +HcfResult HcfCertChainValidatorSpiCreate(HcfCertChainValidatorSpi **spi); + +#ifdef __cplusplus +} +#endif + +#endif // X509_CERT_CHAIN_VALIDATOR_OEPNSSL_H \ No newline at end of file diff --git a/plugin/openssl_plugin/certificate/inc/x509_certificate_openssl.h b/plugin/openssl_plugin/certificate/inc/x509_certificate_openssl.h new file mode 100644 index 0000000..b6af4ba --- /dev/null +++ b/plugin/openssl_plugin/certificate/inc/x509_certificate_openssl.h @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2022 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 "x509_certificate_spi.h" + +#ifndef X509_CERTIFICATE_OEPNSSL_H +#define X509_CERTIFICATE_OEPNSSL_H + +#ifdef __cplusplus +extern "C" { +#endif + +HcfResult OpensslX509CertSpiCreate(const HcfEncodingBlob *inStream, HcfX509CertificateSpi **spi); + +#ifdef __cplusplus +} +#endif + +#endif // X509_CERTIFICATE_OEPNSSL_H \ No newline at end of file diff --git a/plugin/openssl_plugin/certificate/inc/x509_crl_entry_openssl.h b/plugin/openssl_plugin/certificate/inc/x509_crl_entry_openssl.h new file mode 100644 index 0000000..8cf36ba --- /dev/null +++ b/plugin/openssl_plugin/certificate/inc/x509_crl_entry_openssl.h @@ -0,0 +1,35 @@ +/* + * Copyright (C) 2022 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 "blob.h" +#include "result.h" +#include "x509_crl_entry.h" + +#ifndef X509_CRL_ENTRY_OEPNSSL_H +#define X509_CRL_ENTRY_OEPNSSL_H + +#ifdef __cplusplus +extern "C" { +#endif + +HcfResult HcfCX509CRLEntryCreate(X509_REVOKED *rev, HcfX509CrlEntry **crlEntryOut, HcfBlob *certIssuer); + +#ifdef __cplusplus +} +#endif + +#endif // X509_CRL_ENTRY_OEPNSSL_H \ No newline at end of file diff --git a/plugin/openssl_plugin/certificate/inc/x509_crl_openssl.h b/plugin/openssl_plugin/certificate/inc/x509_crl_openssl.h new file mode 100644 index 0000000..8382ff0 --- /dev/null +++ b/plugin/openssl_plugin/certificate/inc/x509_crl_openssl.h @@ -0,0 +1,34 @@ +/* + * Copyright (C) 2022 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 "blob.h" +#include "crl.h" +#include "result.h" +#include "x509_crl_spi.h" + +#ifndef X509_CRL_OEPNSSL_H +#define X509_CRL_OEPNSSL_H + +#ifdef __cplusplus +extern "C" { +#endif + +HcfResult HcfCX509CrlSpiCreate(const HcfEncodingBlob *inStream, HcfX509CrlSpi **spi); + +#ifdef __cplusplus +} +#endif + +#endif // X509_CRL_OEPNSSL_H \ No newline at end of file diff --git a/plugin/openssl_plugin/certificate/src/x509_cert_chain_validator_openssl.c b/plugin/openssl_plugin/certificate/src/x509_cert_chain_validator_openssl.c new file mode 100644 index 0000000..37447d7 --- /dev/null +++ b/plugin/openssl_plugin/certificate/src/x509_cert_chain_validator_openssl.c @@ -0,0 +1,243 @@ +/* + * Copyright (C) 2022 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 "x509_cert_chain_validator_openssl.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "blob.h" +#include "config.h" +#include "log.h" +#include "memory.h" +#include "plugin_defines.h" +#include "result.h" +#include "utils.h" +#include "openssl_common.h" + +#define X509_CERT_CHAIN_VALIDATOR_OPENSSL_CLASS "X509CertChainValidatorOpensslClass" + +typedef struct { + uint8_t *data; + size_t len; + X509 *x509; +} CertsInfo; + +static const char *GetX509CertChainValidatorClass(void) +{ + return X509_CERT_CHAIN_VALIDATOR_OPENSSL_CLASS; +} + +static void DestroyX509CertChainValidator(HcfObjectBase *self) +{ + if (self == NULL) { + LOGE("Invalid params!"); + return; + } + if (!IsClassMatch(self, GetX509CertChainValidatorClass())) { + LOGE("Class is not match."); + return; + } + HcfFree((HcfCertChainValidatorSpi *)self); +} + +static HcfResult InitX509Certs(const HcfArray *certsList, CertsInfo **certs) +{ + uint32_t certsInfoLen = sizeof(CertsInfo) * certsList->count; + CertsInfo *certsInfo = (CertsInfo *)HcfMalloc(certsInfoLen, 0); + if (certsInfo == NULL) { + LOGE("Failed to new memory for cert info."); + return HCF_ERR_MALLOC; + } + for (uint32_t i = 0; i < certsList->count; ++i) { + CertsInfo *info = &(certsInfo[i]); + info->data = certsList->data[i].data; + info->len = certsList->data[i].len; + } + *certs = certsInfo; + return HCF_SUCCESS; +} + +static void FreeX509Certs(CertsInfo **certs, uint32_t certNum) +{ + if (certs == NULL) { + LOGD("Input NULL certs, no need to free."); + return; + } + for (uint32_t i = 0; i < certNum; ++i) { + if ((*certs)[i].x509 != NULL) { + X509_free((*certs)[i].x509); + (*certs)[i].x509 = NULL; + } + } + HcfFree(*certs); + *certs = NULL; +} + +static X509 *GetX509Cert(const uint8_t *data, size_t len, enum EncodingFormat format) +{ + X509 *x509 = NULL; + BIO *bio = BIO_new_mem_buf(data, len); + if (bio == NULL) { + LOGE("Failed to new memory for bio."); + return NULL; + } + + if (format == HCF_FORMAT_DER) { + x509 = d2i_X509_bio(bio, NULL); + } else if (format == HCF_FORMAT_PEM) { + x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL); + } + + BIO_free(bio); + return x509; +} + +static HcfResult ConvertOpensslErrorMsg(int32_t errCode) +{ + switch (errCode) { + case X509_V_OK: + return HCF_SUCCESS; + case X509_V_ERR_CERT_SIGNATURE_FAILURE: + return HCF_ERR_CERT_SIGNATURE_FAILURE; + case X509_V_ERR_CERT_NOT_YET_VALID: + return HCF_ERR_CERT_NOT_YET_VALID; + case X509_V_ERR_CERT_HAS_EXPIRED: + return HCF_ERR_CERT_HAS_EXPIRED; + case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY: + return HCF_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY; + case X509_V_ERR_KEYUSAGE_NO_CERTSIGN: + return HCF_ERR_KEYUSAGE_NO_CERTSIGN; + case X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE: + return HCF_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE; + default: + break; + } + return HCF_ERR_CRYPTO_OPERATION; +} + +static HcfResult ValidateCertChainInner(CertsInfo *certs, uint32_t certNum) +{ + HcfResult res = HCF_SUCCESS; + X509_STORE *store = X509_STORE_new(); + X509_STORE_CTX *verifyCtx = X509_STORE_CTX_new(); + do { + if ((store == NULL) || (verifyCtx == NULL)) { + LOGE("Failed to verify cert chain init."); + res = HCF_ERR_MALLOC; + break; + } + + for (uint32_t i = certNum - 1; i > 0; i--) { // certs[certNum - 1] represents the 0th cert. + if (X509_STORE_add_cert(store, certs[i].x509) != HCF_OPENSSL_SUCCESS) { + LOGE("Failed to add cert to store."); + HcfPrintOpensslError(); + res = HCF_ERR_MALLOC; + break; + } + } + if (res != HCF_SUCCESS) { + break; + } + /* Do not check cert validity against current time. */ + X509_STORE_set_flags(store, X509_V_FLAG_NO_CHECK_TIME); + int32_t resOpenssl = X509_STORE_CTX_init(verifyCtx, store, certs[0].x509, NULL); + if (resOpenssl != HCF_OPENSSL_SUCCESS) { + LOGE("Failed to init verify ctx."); + res = HCF_ERR_CRYPTO_OPERATION; + HcfPrintOpensslError(); + break; + } + resOpenssl = X509_verify_cert(verifyCtx); + if (resOpenssl != HCF_OPENSSL_SUCCESS) { + int32_t errCode = X509_STORE_CTX_get_error(verifyCtx); + const char *pChError = X509_verify_cert_error_string(errCode); + LOGE("Failed to verify cert, openssl openssl error code = %d, error msg:%s.", errCode, pChError); + res = ConvertOpensslErrorMsg(errCode); + break; + } + } while (0); + + if (verifyCtx != NULL) { + X509_STORE_CTX_free(verifyCtx); + } + if (store != NULL) { + X509_STORE_free(store); + } + return res; +} + +static HcfResult ValidateCertChain(CertsInfo *certs, uint32_t certNum, enum EncodingFormat format) +{ + for (uint32_t i = 0; i < certNum; ++i) { + X509 *x509 = GetX509Cert(certs[i].data, certs[i].len, format); + if (x509 == NULL) { + LOGE("Failed to convert cert blob to x509."); + return HCF_ERR_CRYPTO_OPERATION; /* X509 will be freed by caller func. */ + } + certs[i].x509 = x509; + } + return ValidateCertChainInner(certs, certNum); +} + +static HcfResult Validate(HcfCertChainValidatorSpi *self, const HcfArray *certsList) +{ + if ((self == NULL) || (certsList == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertChainValidatorClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + CertsInfo *certs = NULL; + HcfResult res = InitX509Certs(certsList, &certs); + if (res != HCF_SUCCESS) { + LOGE("Failed to init certs, res = %d.", res); + return res; + } + res = ValidateCertChain(certs, certsList->count, certsList->format); + if (res != HCF_SUCCESS) { + LOGE("Failed to validate cert chain, res = %d.", res); + } + FreeX509Certs(&certs, certsList->count); + return res; +} + +HcfResult HcfCertChainValidatorSpiCreate(HcfCertChainValidatorSpi **spi) +{ + if (spi == NULL) { + LOGE("Invalid params, spi is null!"); + return HCF_INVALID_PARAMS; + } + HcfCertChainValidatorSpi *validator = (HcfCertChainValidatorSpi *)HcfMalloc(sizeof(HcfCertChainValidatorSpi), 0); + if (validator == NULL) { + LOGE("Failed to allocate certChain validator spi object memory!"); + return HCF_ERR_MALLOC; + } + validator->base.getClass = GetX509CertChainValidatorClass; + validator->base.destroy = DestroyX509CertChainValidator; + validator->engineValidate = Validate; + + *spi = validator; + return HCF_SUCCESS; +} \ No newline at end of file diff --git a/plugin/openssl_plugin/certificate/src/x509_certificate_openssl.c b/plugin/openssl_plugin/certificate/src/x509_certificate_openssl.c new file mode 100644 index 0000000..d628bb6 --- /dev/null +++ b/plugin/openssl_plugin/certificate/src/x509_certificate_openssl.c @@ -0,0 +1,945 @@ +/* + * Copyright (C) 2022 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 "x509_certificate_openssl.h" + +#include +#include +#include +#include +#include + +#include "config.h" +#include "log.h" +#include "memory.h" +#include "plugin_defines.h" +#include "result.h" +#include "utils.h" +#include "x509_certificate.h" +#include "openssl_class.h" +#include "openssl_common.h" + +#define INVALID_VERSION (-1) +#define INVALID_SERIAL_NUMBER (-1) +#define INVALID_CONSTRAINTS_LEN (-1) +#define X509_CERT_PUBLIC_KEY_OPENSSL_CLASS "X509CertPublicKeyOpensslClass" +#define OID_STR_MAX_LEN 128 +#define CHAR_TO_BIT_LEN 8 +#define MAX_DATE_STR_LEN 128 +#define FLAG_BIT_LEFT_NUM 0x07 + +typedef struct { + HcfPubKey base; + EVP_PKEY *pubKey; +} X509PubKeyOpensslImpl; + +static HcfResult DeepCopyDataToOut(const char *data, int32_t len, HcfBlob *out) +{ + out->data = (uint8_t *)HcfMalloc(len, 0); + if (out->data == NULL) { + LOGE("Failed to malloc for sig algorithm params!"); + return HCF_ERR_MALLOC; + } + if (memcpy_s(out->data, len, data, len) != EOK) { + LOGE("Failed to copy the sig algorithm params!"); + HcfFree(out->data); + out->data = NULL; + return HCF_ERR_COPY; + } + out->len = len; + return HCF_SUCCESS; +} + +static const char *GetX509CertClass(void) +{ + return X509_CERT_OPENSSL_CLASS; +} + +static void DestroyX509Openssl(HcfObjectBase *self) +{ + if (self == NULL) { + return; + } + if (!IsClassMatch(self, GetX509CertClass())) { + LOGE("Input wrong class type!"); + return; + } + HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self; + X509_free(realCert->x509); + realCert->x509 = NULL; + HcfFree(realCert); +} + +static const char *GetX509CertPubKeyClass(void) +{ + return X509_CERT_PUBLIC_KEY_OPENSSL_CLASS; +} + +static void DestroyX509PubKeyOpenssl(HcfObjectBase *self) +{ + if (self == NULL) { + return; + } + if (!IsClassMatch(self, GetX509CertPubKeyClass())) { + LOGE("Input wrong class type!"); + return; + } + X509PubKeyOpensslImpl *impl = (X509PubKeyOpensslImpl *)self; + if (impl->pubKey != NULL) { + EVP_PKEY_free(impl->pubKey); + impl->pubKey = NULL; + } + HcfFree(impl); +} + +static const char *GetPubKeyAlgorithm(HcfKey *self) +{ + (void)self; + LOGD("Not supported!"); + return NULL; +} + + +static HcfResult GetPubKeyEncoded(HcfKey *self, HcfBlob *returnBlob) +{ + (void)self; + (void)returnBlob; + LOGD("Not supported!"); + return HCF_NOT_SUPPORT; +} + +static const char *GetPubKeyFormat(HcfKey *self) +{ + (void)self; + LOGD("Not supported!"); + return NULL; +} + +static HcfResult VerifyX509Openssl(HcfX509CertificateSpi *self, HcfPubKey *key) +{ + if ((self == NULL) || (key == NULL)) { + LOGE("The input data is null!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertClass()) || + (!IsClassMatch((HcfObjectBase *)key, GetX509CertPubKeyClass()))) { + LOGE("Input wrong class type!"); + return HCF_INVALID_PARAMS; + } + HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self; + X509 *x509 = realCert->x509; + X509PubKeyOpensslImpl *keyImpl = (X509PubKeyOpensslImpl *)key; + EVP_PKEY *pubKey = keyImpl->pubKey; + if (X509_verify(x509, pubKey) != HCF_OPENSSL_SUCCESS) { + LOGE("Failed to verify x509 cert's signature."); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + return HCF_SUCCESS; +} + +static HcfResult GetEncodedX509Openssl(HcfX509CertificateSpi *self, HcfEncodingBlob *encodedByte) +{ + if ((self == NULL) || (encodedByte == NULL)) { + LOGE("The input data is null!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertClass())) { + LOGE("Input wrong class type!"); + return HCF_INVALID_PARAMS; + } + HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self; + X509 *x509 = realCert->x509; + int32_t length = i2d_X509(x509, NULL); + if ((length <= 0) || (x509 == NULL)) { + LOGE("Failed to convert internal x509 to der format!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + unsigned char *der = NULL; + (void)i2d_X509(x509, &der); + encodedByte->data = (uint8_t *)HcfMalloc(length, 0); + if (encodedByte->data == NULL) { + LOGE("Failed to malloc for x509 der data!"); + OPENSSL_free(der); + return HCF_ERR_MALLOC; + } + if (memcpy_s(encodedByte->data, length, der, length) != EOK) { + LOGE("Failed to copy the x509 der data!"); + OPENSSL_free(der); + HcfFree(encodedByte->data); + encodedByte->data = NULL; + return HCF_ERR_COPY; + } + OPENSSL_free(der); + encodedByte->len = length; + encodedByte->encodingFormat = HCF_FORMAT_DER; + return HCF_SUCCESS; +} + +static HcfResult GetPublicKeyX509Openssl(HcfX509CertificateSpi *self, HcfPubKey **keyOut) +{ + if ((self == NULL) || (keyOut == NULL)) { + LOGE("The input data is null!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertClass())) { + LOGE("Input wrong class type!"); + return HCF_INVALID_PARAMS; + } + HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self; + X509 *x509 = realCert->x509; + EVP_PKEY *pubKey = X509_get_pubkey(x509); + if (pubKey == NULL) { + LOGE("Failed to get publick key from x509 cert."); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + X509PubKeyOpensslImpl *keyImpl = (X509PubKeyOpensslImpl *)HcfMalloc(sizeof(X509PubKeyOpensslImpl), 0); + if (keyImpl == NULL) { + LOGE("Failed to malloc for public key obj!"); + EVP_PKEY_free(pubKey); + return HCF_ERR_MALLOC; + } + keyImpl->pubKey = pubKey; + keyImpl->base.base.base.destroy = DestroyX509PubKeyOpenssl; + keyImpl->base.base.base.getClass = GetX509CertPubKeyClass; + keyImpl->base.base.getEncoded = GetPubKeyEncoded; + keyImpl->base.base.getAlgorithm = GetPubKeyAlgorithm; + keyImpl->base.base.getFormat = GetPubKeyFormat; + *keyOut = (HcfPubKey *)keyImpl; + return HCF_SUCCESS; +} + +static HcfResult CompareDateWithCertTime(const X509 *x509, const ASN1_TIME *inputDate) +{ + ASN1_TIME *startDate = X509_get_notBefore(x509); + ASN1_TIME *expirationDate = X509_get_notAfter(x509); + if ((startDate == NULL) || (expirationDate == NULL)) { + LOGE("Date is null in x509 cert!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + HcfResult res = HCF_SUCCESS; + /* 0: equal in ASN1_TIME_compare, -1: a < b, 1: a > b, -2: error. */ + if (ASN1_TIME_compare(inputDate, startDate) < 0) { + LOGE("Date is not validate in x509 cert!"); + res = HCF_ERR_CERT_NOT_YET_VALID; + } else if (ASN1_TIME_compare(expirationDate, inputDate) < 0) { + LOGE("Date is expired in x509 cert!"); + res = HCF_ERR_CERT_HAS_EXPIRED; + } + return res; +} + +static HcfResult CheckValidityWithDateX509Openssl(HcfX509CertificateSpi *self, const char *date) +{ + if ((self == NULL) || (date == NULL)) { + LOGE("The input data is null!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertClass())) { + LOGE("Input wrong class type!"); + return HCF_INVALID_PARAMS; + } + HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self; + X509 *x509 = realCert->x509; + ASN1_TIME *asn1InputDate = ASN1_TIME_new(); + if (asn1InputDate == NULL) { + LOGE("Failed to malloc for asn1 time."); + return HCF_ERR_MALLOC; + } + if (ASN1_TIME_set_string(asn1InputDate, date) != HCF_OPENSSL_SUCCESS) { + LOGE("Failed to set time for asn1 time."); + HcfPrintOpensslError(); + ASN1_TIME_free(asn1InputDate); + return HCF_ERR_CRYPTO_OPERATION; + } + HcfResult res = CompareDateWithCertTime(x509, asn1InputDate); + ASN1_TIME_free(asn1InputDate); + return res; +} + +static long GetVersionX509Openssl(HcfX509CertificateSpi *self) +{ + if (self == NULL) { + LOGE("The input data is null!"); + return INVALID_VERSION; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertClass())) { + LOGE("Input wrong class type!"); + return INVALID_VERSION; + } + HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self; + X509 *x509 = realCert->x509; + return X509_get_version(x509) + 1; +} + +static long GetSerialNumberX509Openssl(HcfX509CertificateSpi *self) +{ + if (self == NULL) { + LOGE("The input data is null!"); + return INVALID_SERIAL_NUMBER; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertClass())) { + LOGE("Input wrong class type!"); + return INVALID_SERIAL_NUMBER; + } + HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self; + X509 *x509 = realCert->x509; + const ASN1_INTEGER *serial = X509_get0_serialNumber(x509); + if (serial == NULL) { + LOGE("Failed to get serial number!"); + return INVALID_SERIAL_NUMBER; + } + return ASN1_INTEGER_get(serial); +} + +static HcfResult GetIssuerDNX509Openssl(HcfX509CertificateSpi *self, HcfBlob *out) +{ + if ((self == NULL) || (out == NULL)) { + LOGE("[Get issuerDN openssl] The input data is null!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertClass())) { + LOGE("Input wrong class type!"); + return HCF_INVALID_PARAMS; + } + HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self; + X509 *x509 = realCert->x509; + X509_NAME *issuerName = X509_get_issuer_name(x509); + if (issuerName == NULL) { + LOGE("Failed to get x509 issuerName in openssl!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + char *issuer = (char *)HcfMalloc(HCF_MAX_STR_LEN + 1, 0); + if (issuer == NULL) { + LOGE("Failed to malloc for issuer buffer!"); + return HCF_ERR_MALLOC; + } + + HcfResult res = HCF_SUCCESS; + do { + X509_NAME_oneline(issuerName, issuer, HCF_MAX_STR_LEN); + size_t length = strlen(issuer) + 1; + if (length == 1) { + LOGE("Failed to get oneline issuerName in openssl!"); + res = HCF_ERR_CRYPTO_OPERATION; + HcfPrintOpensslError(); + break; + } + res = DeepCopyDataToOut(issuer, length, out); + } while (0); + HcfFree(issuer); + return res; +} + +static HcfResult GetSubjectDNX509Openssl(HcfX509CertificateSpi *self, HcfBlob *out) +{ + if ((self == NULL) || (out == NULL)) { + LOGE("[Get subjectDN openssl]The input data is null!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertClass())) { + LOGE("Input wrong class type!"); + return HCF_INVALID_PARAMS; + } + HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self; + X509 *x509 = realCert->x509; + X509_NAME *subjectName = X509_get_subject_name(x509); + if (subjectName == NULL) { + LOGE("Failed to get x509 subjectName in openssl!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + char *subject = (char *)HcfMalloc(HCF_MAX_STR_LEN + 1, 0); + if (subject == NULL) { + LOGE("Failed to malloc for subject buffer!"); + return HCF_ERR_MALLOC; + } + + HcfResult res = HCF_SUCCESS; + do { + X509_NAME_oneline(subjectName, subject, HCF_MAX_STR_LEN); + size_t length = strlen(subject) + 1; + if (length == 1) { + LOGE("Failed to get oneline subjectName in openssl!"); + HcfPrintOpensslError(); + res = HCF_ERR_CRYPTO_OPERATION; + break; + } + res = DeepCopyDataToOut(subject, length, out); + } while (0); + HcfFree(subject); + return res; +} + +static HcfResult GetNotBeforeX509Openssl(HcfX509CertificateSpi *self, HcfBlob *outDate) +{ + if ((self == NULL) || (outDate == NULL)) { + LOGE("Get not before, input is null!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertClass())) { + LOGE("Get not before, input wrong class type!"); + return HCF_INVALID_PARAMS; + } + HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self; + X509 *x509 = realCert->x509; + ASN1_TIME *notBeforeDate = X509_get_notBefore(x509); + if (notBeforeDate == NULL) { + LOGE("NotBeforeDate is null in x509 cert!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + if (ASN1_TIME_normalize(notBeforeDate) != HCF_OPENSSL_SUCCESS) { + LOGE("Failed to normalize notBeforeDate!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + const char *date = (const char *)(notBeforeDate->data); + if ((date == NULL) || (strlen(date) > HCF_MAX_STR_LEN)) { + LOGE("Failed to get notBeforeDate data!"); + return HCF_ERR_CRYPTO_OPERATION; + } + uint32_t length = strlen(date) + 1; + return DeepCopyDataToOut(date, length, outDate); +} + +static HcfResult GetNotAfterX509Openssl(HcfX509CertificateSpi *self, HcfBlob *outDate) +{ + if ((self == NULL) || (outDate == NULL)) { + LOGE("Get not after, input data is null!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertClass())) { + LOGE("Get not after, input wrong class type!"); + return HCF_INVALID_PARAMS; + } + HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self; + X509 *x509 = realCert->x509; + ASN1_TIME *notAfterDate = X509_get_notAfter(x509); + if (notAfterDate == NULL) { + LOGE("NotAfterDate is null in x509 cert!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + if (ASN1_TIME_normalize(notAfterDate) != HCF_OPENSSL_SUCCESS) { + LOGE("Failed to normalize notAfterDate!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + const char *date = (const char *)(notAfterDate->data); + if ((date == NULL) || (strlen(date) > HCF_MAX_STR_LEN)) { + LOGE("Failed to get notAfterDate data!"); + return HCF_ERR_CRYPTO_OPERATION; + } + uint32_t length = strlen(date) + 1; + return DeepCopyDataToOut(date, length, outDate); +} + +static HcfResult GetSignatureX509Openssl(HcfX509CertificateSpi *self, HcfBlob *sigOut) +{ + if ((self == NULL) || (sigOut == NULL)) { + LOGE("The input data is null!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertClass())) { + LOGE("Input wrong class type!"); + return HCF_INVALID_PARAMS; + } + HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self; + X509 *x509 = realCert->x509; + const ASN1_BIT_STRING *signature; + X509_get0_signature(&signature, NULL, x509); + if ((signature == NULL) || (signature->length == 0) || (signature->length > HCF_MAX_BUFFER_LEN)) { + LOGE("Failed to get x509 signature in openssl!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + sigOut->data = (uint8_t *)HcfMalloc(signature->length, 0); + if (sigOut->data == NULL) { + LOGE("Failed to malloc for signature data!"); + return HCF_ERR_MALLOC; + } + if (memcpy_s(sigOut->data, signature->length, signature->data, signature->length) != EOK) { + LOGE("Failed to copy the signature data!"); + HcfFree(sigOut->data); + sigOut->data = NULL; + return HCF_ERR_COPY; + } + sigOut->len = signature->length; + return HCF_SUCCESS; +} + +static HcfResult GetSigAlgNameX509Openssl(HcfX509CertificateSpi *self, HcfBlob *outName) +{ + if ((self == NULL) || (outName == NULL)) { + LOGE("[GetSigAlgName openssl] The input data is null!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertClass())) { + LOGE("[GetSigAlgName openssl] Input wrong class type!"); + return HCF_INVALID_PARAMS; + } + HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self; + X509 *x509 = realCert->x509; + const X509_ALGOR *alg; + X509_get0_signature(NULL, &alg, x509); + const ASN1_OBJECT *oidObj; + X509_ALGOR_get0(&oidObj, NULL, NULL, alg); + char oidStr[OID_STR_MAX_LEN] = { 0 }; + int32_t resLen = OBJ_obj2txt(oidStr, OID_STR_MAX_LEN, oidObj, 1); + if ((resLen < 0) || (resLen >= OID_STR_MAX_LEN)) { + LOGE("Failed to convert x509 object to text!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + const char *algName = GetAlgorithmName(oidStr); + if (algName == NULL) { + return HCF_ERR_CRYPTO_OPERATION; + } + uint32_t len = strlen(algName) + 1; + return DeepCopyDataToOut(algName, len, outName); +} + +static HcfResult GetSigAlgOidX509Openssl(HcfX509CertificateSpi *self, HcfBlob *out) +{ + if ((self == NULL) || (out == NULL)) { + LOGE("[GetSigAlgOID openssl] The input data is null!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertClass())) { + LOGE("[GetSigAlgOID openssl] Input wrong class type!"); + return HCF_INVALID_PARAMS; + } + HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self; + X509 *x509 = realCert->x509; + const X509_ALGOR *alg; + X509_get0_signature(NULL, &alg, x509); + const ASN1_OBJECT *oid; + X509_ALGOR_get0(&oid, NULL, NULL, alg); + char algOid[OID_STR_MAX_LEN] = { 0 }; + int32_t resLen = OBJ_obj2txt(algOid, OID_STR_MAX_LEN, oid, 1); + if ((resLen < 0) || (resLen >= OID_STR_MAX_LEN)) { + LOGE("Failed to convert x509 object to text!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + uint32_t len = strlen(algOid) + 1; + return DeepCopyDataToOut(algOid, len, out); +} + +static HcfResult GetSigAlgParamsX509Openssl(HcfX509CertificateSpi *self, HcfBlob *sigAlgParamsOut) +{ + if ((self == NULL) || (sigAlgParamsOut == NULL)) { + LOGE("[GetSigAlgParams openssl] The input data is null!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertClass())) { + LOGE("[GetSigAlgParams openssl] Input wrong class type!"); + return HCF_INVALID_PARAMS; + } + HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self; + X509 *x509 = realCert->x509; + const X509_ALGOR *alg; + X509_get0_signature(NULL, &alg, x509); + int32_t paramType = 0; + const void *paramValue = NULL; + X509_ALGOR_get0(NULL, ¶mType, ¶mValue, alg); + if (paramType == V_ASN1_UNDEF) { + LOGE("get_X509_ALGOR_parameter, no parameters!"); + return HCF_NOT_SUPPORT; + } + ASN1_TYPE *param = ASN1_TYPE_new(); + if (param == NULL) { + LOGE("Failed to malloc for asn1 type data!"); + return HCF_ERR_MALLOC; + } + if (ASN1_TYPE_set1(param, paramType, paramValue) != HCF_OPENSSL_SUCCESS) { + LOGE("Failed to set asn1 type in openssl!"); + HcfPrintOpensslError(); + ASN1_TYPE_free(param); + return HCF_ERR_CRYPTO_OPERATION; + } + unsigned char *out = NULL; + int32_t len = i2d_ASN1_TYPE(param, NULL); + if (len <= 0) { + LOGE("Failed to convert ASN1_TYPE!"); + HcfPrintOpensslError(); + ASN1_TYPE_free(param); + return HCF_ERR_CRYPTO_OPERATION; + } + (void)i2d_ASN1_TYPE(param, &out); + ASN1_TYPE_free(param); + HcfResult res = DeepCopyDataToOut((const char *)out, len, sigAlgParamsOut); + OPENSSL_free(out); + return res; +} + +static HcfResult ConvertASN1String2BoolArray(const ASN1_BIT_STRING *string, HcfBlob *boolArr) +{ + uint32_t length = ASN1_STRING_length(string) * CHAR_TO_BIT_LEN; + if (string->flags & ASN1_STRING_FLAG_BITS_LEFT) { + length -= string->flags & FLAG_BIT_LEFT_NUM; + } + boolArr->data = (uint8_t *)HcfMalloc(length, 0); + if (boolArr->data == NULL) { + LOGE("Failed to malloc for bit array data!"); + return HCF_ERR_MALLOC; + } + for (uint32_t i = 0; i < length; i++) { + boolArr->data[i] = ASN1_BIT_STRING_get_bit(string, i); + } + boolArr->len = length; + return HCF_SUCCESS; +} + +static HcfResult GetKeyUsageX509Openssl(HcfX509CertificateSpi *self, HcfBlob *boolArr) +{ + if ((self == NULL) || (boolArr == NULL)) { + LOGE("[GetKeyUsage openssl] The input data is null!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertClass())) { + LOGE("Input wrong class type!"); + return HCF_INVALID_PARAMS; + } + HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self; + X509 *x509 = realCert->x509; + + ASN1_BIT_STRING *keyUsage = (ASN1_BIT_STRING *)X509_get_ext_d2i(x509, NID_key_usage, NULL, NULL); + if ((keyUsage == NULL) || (keyUsage->length == 0)) { + LOGE("Failed to get x509 keyUsage in openssl!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + HcfResult res = ConvertASN1String2BoolArray(keyUsage, boolArr); + ASN1_BIT_STRING_free(keyUsage); + return res; +} + +static HcfResult DeepCopyExtendedKeyUsage(const STACK_OF(ASN1_OBJECT) *extUsage, + int32_t i, HcfArray *keyUsageOut) +{ + char usage[OID_STR_MAX_LEN] = { 0 }; + int32_t resLen = OBJ_obj2txt(usage, OID_STR_MAX_LEN, sk_ASN1_OBJECT_value(extUsage, i), 1); + if ((resLen < 0) || (resLen >= OID_STR_MAX_LEN)) { + LOGE("Failed to convert x509 object to text!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + uint32_t len = strlen(usage) + 1; + keyUsageOut->data[i].data = (uint8_t *)HcfMalloc(len, 0); + if (keyUsageOut->data[i].data == NULL) { + LOGE("Failed to malloc for key usage!"); + return HCF_ERR_MALLOC; + } + if (memcpy_s(keyUsageOut->data[i].data, len, usage, len) != EOK) { + LOGE("Failed to copy the key usage!"); + HcfFree(keyUsageOut->data[i].data); + keyUsageOut->data[i].data = NULL; + return HCF_ERR_COPY; + } + keyUsageOut->data[i].len = len; + return HCF_SUCCESS; +} + +static void DestroyArray(HcfArray *arr) +{ + if (arr == NULL) { + LOGD("The input array is null, no need to free."); + return; + } + for (uint32_t i = 0; i < arr->count; ++i) { + HcfFree(arr->data[i].data); + arr->data[i].data = NULL; + arr->data[i].len = 0; + } + arr->count = 0; + HcfFree(arr->data); + arr->data = NULL; +} + +static HcfResult GetExtendedKeyUsageX509Openssl(HcfX509CertificateSpi *self, HcfArray *keyUsageOut) +{ + if ((self == NULL) || (keyUsageOut == NULL)) { + LOGE("The input data is null!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertClass())) { + LOGE("Input wrong class type!"); + return HCF_INVALID_PARAMS; + } + HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self; + X509 *x509 = realCert->x509; + STACK_OF(ASN1_OBJECT) *extUsage = X509_get_ext_d2i(x509, NID_ext_key_usage, NULL, NULL); + if (extUsage == NULL) { + LOGE("Failed to get x509 extended keyUsage in openssl!"); + return HCF_ERR_CRYPTO_OPERATION; + } + HcfResult res = HCF_SUCCESS; + do { + int32_t size = sk_ASN1_OBJECT_num(extUsage); + if (size <= 0) { + LOGE("The extended key usage size in openssl is invalid!"); + HcfPrintOpensslError(); + res = HCF_ERR_CRYPTO_OPERATION; + break; + } + keyUsageOut->count = size; + int32_t blobSize = sizeof(HcfBlob) * size; + keyUsageOut->data = (HcfBlob *)HcfMalloc(blobSize, 0); + if (keyUsageOut->data == NULL) { + LOGE("Failed to malloc for keyUsageOut array!"); + res = HCF_ERR_MALLOC; + break; + } + for (int32_t i = 0; i < size; ++i) { + res = DeepCopyExtendedKeyUsage(extUsage, i, keyUsageOut); + if (res != HCF_SUCCESS) { + LOGE("Falied to copy extended key usage!"); + break; + } + } + } while (0); + if (res != HCF_SUCCESS) { + DestroyArray(keyUsageOut); + } + sk_ASN1_OBJECT_pop_free(extUsage, ASN1_OBJECT_free); + return res; +} + +static int32_t GetBasicConstraintsX509Openssl(HcfX509CertificateSpi *self) +{ + if (self == NULL) { + LOGE("The input data is null!"); + return INVALID_CONSTRAINTS_LEN; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertClass())) { + LOGE("Input wrong class type!"); + return INVALID_CONSTRAINTS_LEN; + } + HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self; + X509 *x509 = realCert->x509; + BASIC_CONSTRAINTS *constraints = (BASIC_CONSTRAINTS *)X509_get_ext_d2i(x509, NID_basic_constraints, NULL, NULL); + if (constraints == NULL) { + LOGE("Failed to get basic constraints in openssl!"); + return INVALID_CONSTRAINTS_LEN; + } + /* Path len is only valid for CA cert. */ + if (!constraints->ca) { + LOGI("The cert in not a CA!"); + return INVALID_CONSTRAINTS_LEN; + } + if ((constraints->pathlen == NULL) || (constraints->pathlen->type == V_ASN1_NEG_INTEGER)) { + LOGE("The cert path len is negative in openssl!"); + return INVALID_CONSTRAINTS_LEN; + } + long pathLen = ASN1_INTEGER_get(constraints->pathlen); + if ((pathLen < 0) || (pathLen > INT_MAX)) { + LOGE("Get the overflow path length in openssl!"); + return INVALID_CONSTRAINTS_LEN; + } + return (int32_t)pathLen; +} + +static HcfResult DeepCopyAlternativeNames(const STACK_OF(GENERAL_NAME) *altNames, int32_t i, HcfArray *outName) +{ + GENERAL_NAME *general = sk_GENERAL_NAME_value(altNames, i); + int32_t generalType = 0; + ASN1_STRING *ans1Str = GENERAL_NAME_get0_value(general, &generalType); + const char *str = (const char *)ASN1_STRING_get0_data(ans1Str); + if ((str == NULL) || (strlen(str) > HCF_MAX_STR_LEN)) { + LOGE("Failed to get x509 altNames string in openssl!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + uint32_t nameLen = strlen(str) + 1; + outName->data[i].data = (uint8_t *)HcfMalloc(nameLen, 0); + if (outName->data[i].data == NULL) { + LOGE("Failed to malloc for outName!"); + return HCF_ERR_MALLOC; + } + if (memcpy_s(outName->data[i].data, nameLen, str, nameLen) != EOK) { + LOGE("Failed to copy the outName!"); + HcfFree(outName->data[i].data); + outName->data[i].data = NULL; + return HCF_ERR_COPY; + } + outName->data[i].len = nameLen; + return HCF_SUCCESS; +} + +static HcfResult GetSubjectAltNamesX509Openssl(HcfX509CertificateSpi *self, HcfArray *outName) +{ + if ((self == NULL) || (outName == NULL)) { + LOGE("[GetSubjectAltNames openssl] The input data is null!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertClass())) { + LOGE("Input wrong class type!"); + return HCF_INVALID_PARAMS; + } + HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self; + X509 *x509 = realCert->x509; + STACK_OF(GENERAL_NAME) *subjectAltName = X509_get_ext_d2i(x509, NID_subject_alt_name, NULL, NULL); + if (subjectAltName == NULL) { + LOGE("Failed to get subjectAltName in openssl!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + HcfResult res = HCF_SUCCESS; + do { + int32_t size = sk_GENERAL_NAME_num(subjectAltName); + if (size <= 0) { + LOGE("The subjectAltName number in openssl is invalid!"); + HcfPrintOpensslError(); + res = HCF_ERR_CRYPTO_OPERATION; + break; + } + outName->count = size; + int32_t blobSize = sizeof(HcfBlob) * size; + outName->data = (HcfBlob *)HcfMalloc(blobSize, 0); + if (outName->data == NULL) { + LOGE("Failed to malloc for subjectAltName array!"); + res = HCF_ERR_MALLOC; + break; + } + for (int32_t i = 0; i < size; ++i) { + res = DeepCopyAlternativeNames(subjectAltName, i, outName); + if (res != HCF_SUCCESS) { + LOGE("Falied to copy subjectAltName!"); + break; + } + } + } while (0); + if (res != HCF_SUCCESS) { + DestroyArray(outName); + } + GENERAL_NAMES_free(subjectAltName); + return res; +} + +static HcfResult GetIssuerAltNamesX509Openssl(HcfX509CertificateSpi *self, HcfArray *outName) +{ + if ((self == NULL) || (outName == NULL)) { + LOGE("[GetIssuerAltNames openssl] The input data is null!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetX509CertClass())) { + LOGE("Input wrong class type!"); + return HCF_INVALID_PARAMS; + } + HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)self; + X509 *x509 = realCert->x509; + STACK_OF(GENERAL_NAME) *issuerAltName = X509_get_ext_d2i(x509, NID_issuer_alt_name, NULL, NULL); + if (issuerAltName == NULL) { + LOGE("Failed to get issuerAltName in openssl!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + HcfResult res = HCF_SUCCESS; + do { + int32_t size = sk_GENERAL_NAME_num(issuerAltName); + if (size <= 0) { + LOGE("The issuerAltName number in openssl is invalid!"); + HcfPrintOpensslError(); + res = HCF_ERR_CRYPTO_OPERATION; + break; + } + outName->count = size; + int32_t blobSize = sizeof(HcfBlob) * size; + outName->data = (HcfBlob *)HcfMalloc(blobSize, 0); + if (outName->data == NULL) { + LOGE("Failed to malloc for issuerAltName array!"); + res = HCF_ERR_MALLOC; + break; + } + for (int32_t i = 0; i < size; ++i) { + res = DeepCopyAlternativeNames(issuerAltName, i, outName); + if (res != HCF_SUCCESS) { + LOGE("Falied to copy issuerAltName!"); + break; + } + } + } while (0); + if (res != HCF_SUCCESS) { + DestroyArray(outName); + } + GENERAL_NAMES_free(issuerAltName); + return res; +} + +static X509 *CreateX509CertInner(const HcfEncodingBlob *encodingBlob) +{ + X509 *x509 = NULL; + BIO *bio = BIO_new_mem_buf(encodingBlob->data, encodingBlob->len); + if (bio == NULL) { + LOGE("Openssl bio new buf failed."); + return NULL; + } + LOGD("The input cert format is: %d.", encodingBlob->encodingFormat); + if (encodingBlob->encodingFormat == HCF_FORMAT_DER) { + x509 = d2i_X509_bio(bio, NULL); + } else if (encodingBlob->encodingFormat == HCF_FORMAT_PEM) { + x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL); + } + BIO_free(bio); + return x509; +} + +HcfResult OpensslX509CertSpiCreate(const HcfEncodingBlob *inStream, HcfX509CertificateSpi **spi) +{ + if ((inStream == NULL) || (inStream->data == NULL) || (spi == NULL)) { + LOGE("The input data blob is null!"); + return HCF_INVALID_PARAMS; + } + HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)HcfMalloc(sizeof(HcfOpensslX509Cert), 0); + if (realCert == NULL) { + LOGE("Failed to malloc for x509 instance!"); + return HCF_ERR_MALLOC; + } + realCert->x509 = CreateX509CertInner(inStream); + if (realCert->x509 == NULL) { + HcfFree(realCert); + LOGE("Failed to create x509 cert from input data!"); + return HCF_INVALID_PARAMS; + } + realCert->base.base.getClass = GetX509CertClass; + realCert->base.base.destroy = DestroyX509Openssl; + realCert->base.engineVerify = VerifyX509Openssl; + realCert->base.engineGetEncoded = GetEncodedX509Openssl; + realCert->base.engineGetPublicKey = GetPublicKeyX509Openssl; + realCert->base.engineCheckValidityWithDate = CheckValidityWithDateX509Openssl; + realCert->base.engineGetVersion = GetVersionX509Openssl; + realCert->base.engineGetSerialNumber = GetSerialNumberX509Openssl; + realCert->base.engineGetIssuerName = GetIssuerDNX509Openssl; + realCert->base.engineGetSubjectName = GetSubjectDNX509Openssl; + realCert->base.engineGetNotBeforeTime = GetNotBeforeX509Openssl; + realCert->base.engineGetNotAfterTime = GetNotAfterX509Openssl; + realCert->base.engineGetSignature = GetSignatureX509Openssl; + realCert->base.engineGetSignatureAlgName = GetSigAlgNameX509Openssl; + realCert->base.engineGetSignatureAlgOid = GetSigAlgOidX509Openssl; + realCert->base.engineGetSignatureAlgParams = GetSigAlgParamsX509Openssl; + realCert->base.engineGetKeyUsage = GetKeyUsageX509Openssl; + realCert->base.engineGetExtKeyUsage = GetExtendedKeyUsageX509Openssl; + realCert->base.engineGetBasicConstraints = GetBasicConstraintsX509Openssl; + realCert->base.engineGetSubjectAltNames = GetSubjectAltNamesX509Openssl; + realCert->base.engineGetIssuerAltNames = GetIssuerAltNamesX509Openssl; + *spi = (HcfX509CertificateSpi *)realCert; + return HCF_SUCCESS; +} diff --git a/plugin/openssl_plugin/certificate/src/x509_crl_entry_openssl.c b/plugin/openssl_plugin/certificate/src/x509_crl_entry_openssl.c new file mode 100644 index 0000000..d09f2cf --- /dev/null +++ b/plugin/openssl_plugin/certificate/src/x509_crl_entry_openssl.c @@ -0,0 +1,252 @@ +/* + * Copyright (C) 2022 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"x509_crl_entry_openssl.h" + +#include "securec.h" + +#include +#include + +#include "config.h" +#include "hcf_string.h" +#include "log.h" +#include "memory.h" +#include "openssl_common.h" +#include "utils.h" +#include "x509_crl.h" +#include "x509_crl_entry.h" +#include "x509_crl_openssl.h" + +#define OPENSSL_ERROR_SERIAL_NUMBER (-1) + +typedef struct { + HcfX509CrlEntry base; + X509_REVOKED *rev; + HcfBlob *certIssuer; +} HcfX509CRLEntryOpensslImpl; + +static const char *GetClass(void) +{ + return "HcfX509CRLEntryOpensslImpl.HcfX509CrlEntry"; +} + +static X509_REVOKED *GetSelfRev(const HcfX509CrlEntry *self) +{ + if (!IsClassMatch((HcfObjectBase *)self, GetClass())) { + LOGE("Input wrong class type!"); + return NULL; + } + return ((HcfX509CRLEntryOpensslImpl *)self)->rev; +} + +static HcfResult GetEncoded(HcfX509CrlEntry *self, HcfEncodingBlob *encodedOut) +{ + if ((self == NULL) || (encodedOut == NULL)) { + LOGE("Invalid Paramas for calling GetEncoded!"); + return HCF_INVALID_PARAMS; + } + X509_REVOKED *rev = GetSelfRev(self); + if (rev == NULL) { + LOGE("Rev is null!"); + return HCF_INVALID_PARAMS; + } + unsigned char *out = NULL; + int32_t length = i2d_X509_REVOKED(rev, &out); + if (length <= 0) { + LOGE("Do i2d_X509_REVOKED fail!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + encodedOut->data = (uint8_t *)HcfMalloc(length, 0); + if (encodedOut->data == NULL) { + LOGE("Failed to malloc for encodedOut!"); + OPENSSL_free(out); + return HCF_ERR_MALLOC; + } + if (memcpy_s(encodedOut->data, length, out, length) != EOK) { + LOGE("Failed to copy the encodedOut!"); + HcfFree(encodedOut->data); + encodedOut->data = NULL; + OPENSSL_free(out); + return HCF_ERR_COPY; + } + encodedOut->len = length; + encodedOut->encodingFormat = HCF_FORMAT_DER; + OPENSSL_free(out); + return HCF_SUCCESS; +} + +static long GetSerialNumber(HcfX509CrlEntry *self) +{ + if (self == NULL) { + LOGE("Invalid Paramas for calling GetSerialNumber!"); + return OPENSSL_ERROR_SERIAL_NUMBER; + } + X509_REVOKED *rev = GetSelfRev(self); + if (rev == NULL) { + LOGE("Rev is null!"); + return OPENSSL_ERROR_SERIAL_NUMBER; + } + const ASN1_INTEGER *serialNumber = X509_REVOKED_get0_serialNumber(rev); + if (serialNumber == NULL) { + LOGE("Get serial number fail!"); + HcfPrintOpensslError(); + return OPENSSL_ERROR_SERIAL_NUMBER; + } + return ASN1_INTEGER_get(serialNumber); +} + +static HcfResult GetCertIssuer(HcfX509CrlEntry *self, HcfBlob *encodedOut) +{ + if ((self == NULL) || (encodedOut == NULL)) { + LOGE("Invalid Paramas for calling GetCertIssuer!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetClass())) { + LOGE("Input wrong class type!"); + return HCF_INVALID_PARAMS; + } + HcfBlob *certIssuer = ((HcfX509CRLEntryOpensslImpl *)self)->certIssuer; + if (!IsBlobValid(certIssuer)) { + LOGE("Get certIssuer fail! No certIssuer in CRL entry."); + return HCF_NOT_SUPPORT; + } + uint32_t length = certIssuer->len; + encodedOut->data = (uint8_t *)HcfMalloc(length, 0); + if (encodedOut->data == NULL) { + LOGE("Failed to malloc for encodedOut!"); + return HCF_ERR_MALLOC; + } + if (memcpy_s(encodedOut->data, length, certIssuer->data, length) != EOK) { + LOGE("Failed to copy the encodedOut!"); + HcfFree(encodedOut->data); + encodedOut->data = NULL; + return HCF_ERR_COPY; + } + encodedOut->len = length; + return HCF_SUCCESS; +} + +static HcfResult GetRevocationDate(HcfX509CrlEntry *self, HcfBlob *out) +{ + if ((self == NULL) || (out == NULL)) { + LOGE("invalid Paramas for calling GetRevocationDate!"); + return HCF_INVALID_PARAMS; + } + X509_REVOKED *rev = GetSelfRev(self); + if (rev == NULL) { + LOGE("Rev is null!"); + return HCF_INVALID_PARAMS; + } + const ASN1_TIME *time = X509_REVOKED_get0_revocationDate(rev); + if (time == NULL) { + LOGE("Get revocation date fail!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + const char *revTime = (const char *)(time->data); + if ((revTime == NULL) || (strlen(revTime) > HCF_MAX_STR_LEN)) { + LOGE("Get revocation date from ASN1_TIME fail!"); + return HCF_ERR_CRYPTO_OPERATION; + } + uint32_t length = strlen(revTime) + 1; + out->data = (uint8_t *)HcfMalloc(length, 0); + if (out->data == NULL) { + LOGE("Failed to malloc for revTime!"); + return HCF_ERR_MALLOC; + } + if (memcpy_s(out->data, length, revTime, length) != EOK) { + LOGE("Failed to copy the revTime!"); + HcfFree(out->data); + out->data = NULL; + return HCF_ERR_COPY; + } + out->len = length; + return HCF_SUCCESS; +} + +static HcfResult DeepCopyCertIssuer(HcfX509CRLEntryOpensslImpl *returnCRLEntry, HcfBlob *certIssuer) +{ + returnCRLEntry->certIssuer = (HcfBlob *)HcfMalloc(sizeof(HcfBlob), 0); + if (returnCRLEntry->certIssuer == NULL) { + LOGE("Failed to malloc certIssuer!"); + return HCF_ERR_MALLOC; + } + size_t len = certIssuer->len; + returnCRLEntry->certIssuer->len = len; + returnCRLEntry->certIssuer->data = (uint8_t *)HcfMalloc(len, 0); + if (returnCRLEntry->certIssuer->data == NULL) { + LOGE("Failed to malloc certIssuer data!"); + return HCF_ERR_MALLOC; + } + if (memcpy_s(returnCRLEntry->certIssuer->data, len, certIssuer->data, len) != EOK) { + LOGE("Failed to copy the certIssuer data!"); + HcfFree(returnCRLEntry->certIssuer->data); + returnCRLEntry->certIssuer->data = NULL; + HcfFree(returnCRLEntry->certIssuer); + returnCRLEntry->certIssuer = NULL; + return HCF_ERR_COPY; + } + return HCF_SUCCESS; +} + +static void Destroy(HcfObjectBase *self) +{ + if (self == NULL) { + LOGE("Invalid Paramas!"); + return; + } + if (!IsClassMatch((HcfObjectBase *)self, GetClass())) { + LOGE("Input wrong class type!"); + return; + } + HcfX509CRLEntryOpensslImpl *realCrlEntry = (HcfX509CRLEntryOpensslImpl *)self; + realCrlEntry->rev = NULL; + if (realCrlEntry->certIssuer != NULL) { + HcfFree(realCrlEntry->certIssuer->data); + realCrlEntry->certIssuer->data = NULL; + HcfFree(realCrlEntry->certIssuer); + realCrlEntry->certIssuer = NULL; + } + HcfFree(realCrlEntry); +} + +HcfResult HcfCX509CRLEntryCreate(X509_REVOKED *rev, HcfX509CrlEntry **crlEntryOut, HcfBlob *certIssuer) +{ + if ((rev == NULL) || (crlEntryOut == NULL) || certIssuer == NULL) { + LOGE("Invalid Paramas!"); + return HCF_INVALID_PARAMS; + } + HcfX509CRLEntryOpensslImpl *returnCRLEntry = (HcfX509CRLEntryOpensslImpl *)HcfMalloc( + sizeof(HcfX509CRLEntryOpensslImpl), 0); + if (returnCRLEntry == NULL) { + LOGE("Failed to malloc for x509 entry instance!"); + return HCF_ERR_MALLOC; + } + returnCRLEntry->rev = rev; + returnCRLEntry->certIssuer = NULL; + returnCRLEntry->base.base.getClass = GetClass; + returnCRLEntry->base.base.destroy = Destroy; + returnCRLEntry->base.getEncoded = GetEncoded; + returnCRLEntry->base.getSerialNumber = GetSerialNumber; + returnCRLEntry->base.getCertIssuer = GetCertIssuer; + returnCRLEntry->base.getRevocationDate = GetRevocationDate; + if (DeepCopyCertIssuer(returnCRLEntry, certIssuer) != HCF_SUCCESS) { + LOGI("No cert issuer find or deep copy cert issuer fail!"); + } + *crlEntryOut = (HcfX509CrlEntry *)returnCRLEntry; + return HCF_SUCCESS; +} diff --git a/plugin/openssl_plugin/certificate/src/x509_crl_openssl.c b/plugin/openssl_plugin/certificate/src/x509_crl_openssl.c new file mode 100644 index 0000000..efd9f15 --- /dev/null +++ b/plugin/openssl_plugin/certificate/src/x509_crl_openssl.c @@ -0,0 +1,851 @@ +/* + * Copyright (C) 2022 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 "x509_crl_openssl.h" + +#include "securec.h" + +#include +#include +#include +#include +#include +#include + +#include "config.h" +#include "fwk_class.h" +#include "hcf_string.h" +#include "log.h" +#include "memory.h" +#include "openssl_class.h" +#include "openssl_common.h" +#include "utils.h" +#include "x509_crl.h" +#include "x509_crl_entry_openssl.h" +#include "x509_crl_spi.h" + +typedef struct { + HcfPubKey base; + EVP_PKEY *pubKey; +} X509PubKeyOpensslImpl; + +typedef struct { + HcfX509CrlSpi base; + X509_CRL *crl; + HcfBlob *certIssuer; +} HcfX509CRLOpensslImpl; + +#define OPENSSL_INVALID_VERSION (-1) +#define OPENSSL_ERROR 0 +#define TYPE_NAME "X509" +#define OID_LENGTH 128 +#define MAX_REV_NUM 256 +#define MAX_SIGNATURE_LEN 8192 + +static const char *GetClass(void) +{ + return X509_CRL_OPENSSL_CLASS; +} + +static const char *GetType(HcfX509CrlSpi *self) +{ + if (self == NULL) { + LOGE("Invalid Paramas!"); + return NULL; + } + if (!IsClassMatch((HcfObjectBase *)self, GetClass())) { + LOGE("Input wrong class type!"); + return NULL; + } + return TYPE_NAME; +} + +static X509_CRL *GetCrl(HcfX509CrlSpi *self) +{ + if (!IsClassMatch((HcfObjectBase *)self, GetClass())) { + LOGE("Input wrong class type!"); + return NULL; + } + return ((HcfX509CRLOpensslImpl *)self)->crl; +} + +static X509 *GetX509FromCertificate(const HcfCertificate *cert) +{ + if (!IsClassMatch((HcfObjectBase *)cert, HCF_X509_CERTIFICATE_CLASS)) { + LOGE("Input wrong openssl class type!"); + return NULL; + } + HcfX509CertificateImpl *impl = (HcfX509CertificateImpl *)cert; + if (!IsClassMatch((HcfObjectBase *)(impl->spiObj), X509_CERT_OPENSSL_CLASS)) { + LOGE("Input wrong openssl class type!"); + return NULL; + } + HcfOpensslX509Cert *realCert = (HcfOpensslX509Cert *)(impl->spiObj); + return realCert->x509; +} + +static bool IsRevoked(HcfX509CrlSpi *self, const HcfCertificate *cert) +{ + if ((self == NULL) || (cert == NULL)) { + LOGE("Invalid Paramas!"); + return false; + } + if (!IsClassMatch((HcfObjectBase *)self, GetClass())) { + LOGE("Input wrong class type!"); + return false; + } + X509 *certOpenssl = GetX509FromCertificate(cert); + if (certOpenssl == NULL) { + LOGE("Input Cert is wrong !"); + return false; + } + X509_CRL *crl = ((HcfX509CRLOpensslImpl *)self)->crl; + if (crl == NULL) { + LOGE("crl is null!"); + return false; + } + X509_REVOKED *rev = NULL; + int32_t res = X509_CRL_get0_by_cert(crl, &rev, certOpenssl); + return (res != 0); +} + +static HcfResult GetEncoded(HcfX509CrlSpi *self, HcfEncodingBlob *encodedOut) +{ + if ((self == NULL) || (encodedOut == NULL)) { + LOGE("Invalid Paramas!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetClass())) { + LOGE("Input wrong class type!"); + return HCF_INVALID_PARAMS; + } + unsigned char *out = NULL; + X509_CRL *crl = ((HcfX509CRLOpensslImpl *)self)->crl; + if (crl == NULL) { + LOGE("crl is null!"); + return HCF_INVALID_PARAMS; + } + int32_t length = i2d_X509_CRL(crl, &out); + if (length <= 0) { + LOGE("Do i2d_X509_CRL fail!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + encodedOut->data = (uint8_t *)HcfMalloc(length, 0); + if (encodedOut->data == NULL) { + LOGE("Failed to malloc for crl encoded data!"); + OPENSSL_free(out); + return HCF_ERR_MALLOC; + } + if (memcpy_s(encodedOut->data, length, out, length) != EOK) { + LOGE("Failed to copy the x509 encoded data!"); + OPENSSL_free(out); + HcfFree(encodedOut->data); + encodedOut->data = NULL; + return HCF_ERR_COPY; + } + OPENSSL_free(out); + encodedOut->len = length; + encodedOut->encodingFormat = HCF_FORMAT_DER; + return HCF_SUCCESS; +} + +static HcfResult Verify(HcfX509CrlSpi *self, HcfPubKey *key) +{ + if ((self == NULL) || (key == NULL)) { + LOGE("Invalid Paramas!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetClass()) || + (!IsClassMatch((HcfObjectBase *)key, OPENSSL_RSA_PUBKEY_CLASS))) { + LOGE("Input wrong class type!"); + return HCF_INVALID_PARAMS; + } + RSA *rsaPubkey = ((HcfOpensslRsaPubKey *)key)->pk; + if (rsaPubkey == NULL) { + LOGE("rsaPubkey is null!"); + return HCF_INVALID_PARAMS; + } + EVP_PKEY *pubKey = EVP_PKEY_new(); + if (pubKey == NULL) { + LOGE("pubKey is null!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + if (EVP_PKEY_assign_RSA(pubKey, rsaPubkey) <= 0) { + LOGE("Do EVP_PKEY_assign_RSA fail!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + X509_CRL *crl = ((HcfX509CRLOpensslImpl *)self)->crl; + if (crl == NULL) { + LOGE("crl is null!"); + return HCF_INVALID_PARAMS; + } + int32_t res = X509_CRL_verify(crl, pubKey); + if (res != HCF_OPENSSL_SUCCESS) { + LOGE("Verify fail!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + return HCF_SUCCESS; +} + +static long GetVersion(HcfX509CrlSpi *self) +{ + if (self == NULL) { + LOGE("Invalid Paramas!"); + return OPENSSL_INVALID_VERSION; + } + if (!IsClassMatch((HcfObjectBase *)self, GetClass())) { + LOGE("Input wrong class type!"); + return OPENSSL_INVALID_VERSION; + } + X509_CRL *crl = ((HcfX509CRLOpensslImpl *)self)->crl; + if (crl == NULL) { + LOGE("crl is null!"); + return OPENSSL_INVALID_VERSION; + } + return X509_CRL_get_version(crl) + 1; +} + +static HcfResult GetIssuerName(HcfX509CrlSpi *self, HcfBlob *out) +{ + if ((self == NULL) || (out == NULL)) { + LOGE("Invalid Paramas for calling GetIssuerName!"); + return HCF_INVALID_PARAMS; + } + X509_CRL *crl = GetCrl(self); + if (crl == NULL) { + LOGE("crl is null!"); + return HCF_INVALID_PARAMS; + } + X509_NAME *x509Name = X509_CRL_get_issuer(crl); + if (x509Name == NULL) { + LOGE("Get Issuer DN fail!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + const char *issuer = X509_NAME_oneline(x509Name, NULL, 0); + if ((issuer == NULL) || (strlen(issuer) > HCF_MAX_STR_LEN)) { + LOGE("X509Name convert char fail or issuer name is too long!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + uint32_t length = strlen(issuer) + 1; + out->data = (uint8_t *)HcfMalloc(length, 0); + if (out->data == NULL) { + LOGE("Failed to malloc for crl issuer data!"); + return HCF_ERR_MALLOC; + } + if (memcpy_s(out->data, length, issuer, length) != EOK) { + LOGE("Failed to copy the x509 issuer data!"); + HcfFree(out->data); + out->data = NULL; + return HCF_ERR_COPY; + } + out->len = length; + return HCF_SUCCESS; +} + +static HcfResult SetCertIssuer(HcfX509CrlSpi *self) +{ + ((HcfX509CRLOpensslImpl *)self)->certIssuer = (HcfBlob *)HcfMalloc(sizeof(HcfBlob), 0); + if (((HcfX509CRLOpensslImpl *)self)->certIssuer == NULL) { + LOGE("Failed to malloc for certIssuer!"); + return HCF_ERR_MALLOC; + } + HcfResult res = GetIssuerName(self, ((HcfX509CRLOpensslImpl *)self)->certIssuer); + if (res != HCF_SUCCESS) { + HcfFree(((HcfX509CRLOpensslImpl *)self)->certIssuer); + ((HcfX509CRLOpensslImpl *)self)->certIssuer = NULL; + } + return res; +} + +static HcfResult GetLastUpdate(HcfX509CrlSpi *self, HcfBlob *out) +{ + if ((self == NULL) || (out == NULL)) { + LOGE("Invalid Paramas for calling GetLastUpdate!"); + return HCF_INVALID_PARAMS; + } + X509_CRL *crl = GetCrl(self); + if (crl == NULL) { + LOGE("crl is null!"); + return HCF_INVALID_PARAMS; + } + const ASN1_TIME *time = X509_CRL_get0_lastUpdate(crl); + if (time == NULL) { + LOGE("Get this update time fail!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + const char *thisUpdate = (const char *)(time->data); + if (thisUpdate == NULL || strlen(thisUpdate) > HCF_MAX_STR_LEN) { + LOGE("ThisUpdate convert String fail, or thisUpdate is too long!"); + return HCF_ERR_CRYPTO_OPERATION; + } + uint32_t length = strlen(thisUpdate) + 1; + out->data = (uint8_t *)HcfMalloc(length, 0); + if (out->data == NULL) { + LOGE("Failed to malloc for thisUpdate!"); + return HCF_ERR_MALLOC; + } + if (memcpy_s(out->data, length, thisUpdate, length) != EOK) { + LOGE("Failed to copy the thisUpdate!"); + HcfFree(out->data); + out->data = NULL; + return HCF_ERR_COPY; + } + out->len = length; + return HCF_SUCCESS; +} + +static HcfResult GetNextUpdate(HcfX509CrlSpi *self, HcfBlob *out) +{ + if ((self == NULL) || (out == NULL)) { + LOGE("Invalid Paramas for calling GetNextUpdate!"); + return HCF_INVALID_PARAMS; + } + X509_CRL *crl = GetCrl(self); + if (crl == NULL) { + LOGE("crl is null!"); + return HCF_INVALID_PARAMS; + } + const ASN1_TIME *time = X509_CRL_get0_nextUpdate(crl); + if (time == NULL) { + LOGE("Get next update time fail!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + const char *nextUpdate = (const char *)(time->data); + if ((nextUpdate == NULL) || (strlen(nextUpdate) > HCF_MAX_STR_LEN)) { + LOGE("Get next update time is null, or nextUpdate is too long!"); + return HCF_ERR_CRYPTO_OPERATION; + } + uint32_t length = strlen(nextUpdate) + 1; + out->data = (uint8_t *)HcfMalloc(length, 0); + if (out->data == NULL) { + LOGE("Failed to malloc for nextUpdate!"); + return HCF_ERR_MALLOC; + } + if (memcpy_s(out->data, length, nextUpdate, length) != EOK) { + LOGE("Failed to copy the nextUpdate!"); + HcfFree(out->data); + out->data = NULL; + return HCF_ERR_COPY; + } + out->len = length; + return HCF_SUCCESS; +} + +static HcfResult GetRevokedCert(HcfX509CrlSpi *self, long serialNumber, HcfX509CrlEntry **entryOut) +{ + if ((self == NULL) || (entryOut == NULL)) { + LOGE("Invalid Paramas!"); + return HCF_INVALID_PARAMS; + } + X509_CRL *crl = GetCrl(self); + if (crl == NULL) { + LOGE("crl is null!"); + return HCF_INVALID_PARAMS; + } + ASN1_INTEGER *serial = ASN1_INTEGER_new(); + if (serial == NULL) { + LOGE("Serial init fail!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + if (!ASN1_INTEGER_set(serial, serialNumber)) { + LOGE("Set serial number fail!"); + HcfPrintOpensslError(); + ASN1_INTEGER_free(serial); + return HCF_ERR_CRYPTO_OPERATION; + } + X509_REVOKED *rev = NULL; + int32_t opensslRes = X509_CRL_get0_by_serial(crl, &rev, serial); + ASN1_INTEGER_free(serial); + if (opensslRes != HCF_OPENSSL_SUCCESS) { + LOGE("Get revoked certificate fail, res : %d!", opensslRes); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + HcfResult res = HcfCX509CRLEntryCreate(rev, entryOut, ((HcfX509CRLOpensslImpl *)self)->certIssuer); + if (res != HCF_SUCCESS) { + LOGE("X509 CRL entry create fail, res : %d!", res); + X509_REVOKED_free(rev); + return res; + } + return HCF_SUCCESS; +} + +static HcfResult GetRevokedCertWithCert(HcfX509CrlSpi *self, HcfX509Certificate *cert, + HcfX509CrlEntry **entryOut) +{ + if ((self == NULL) || (cert == NULL) || (entryOut == NULL)) { + LOGE("Invalid Paramas!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetClass())) { + LOGE("Input wrong class type!"); + return HCF_INVALID_PARAMS; + } + X509 *certOpenssl = GetX509FromCertificate((HcfCertificate *)cert); + if (certOpenssl == NULL) { + LOGE("Input Cert is wrong !"); + return HCF_INVALID_PARAMS; + } + X509_CRL *crl = ((HcfX509CRLOpensslImpl *)self)->crl; + if (crl == NULL) { + LOGE("crl is null!"); + return HCF_INVALID_PARAMS; + } + X509_REVOKED *revokedRet = NULL; + int32_t opensslRes = X509_CRL_get0_by_cert(crl, &revokedRet, certOpenssl); + if (opensslRes != HCF_OPENSSL_SUCCESS) { + LOGE("Get revoked certificate with cert fail, res : %d!", opensslRes); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + HcfResult res = HcfCX509CRLEntryCreate(revokedRet, entryOut, ((HcfX509CRLOpensslImpl *)self)->certIssuer); + if (res != HCF_SUCCESS) { + LOGE("X509 CRL entry create fail, res : %d!", res); + X509_REVOKED_free(revokedRet); + return res; + } + return HCF_SUCCESS; +} + +static HcfResult DeepCopyRevokedCertificates(HcfX509CrlSpi *self, const STACK_OF(X509_REVOKED) *entrys, + int32_t i, HcfArray *entrysOut) +{ + X509_REVOKED *rev = sk_X509_REVOKED_value(entrys, i); + if (rev == NULL) { + LOGE("sk_X509_REVOKED_value fail!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + HcfX509CrlEntry *crlEntry = NULL; + HcfResult res = HcfCX509CRLEntryCreate(rev, &crlEntry, ((HcfX509CRLOpensslImpl *)self)->certIssuer); + if (res != HCF_SUCCESS || crlEntry == NULL) { + LOGE("X509 CRL entry create fail, res : %d!", res); + return res; + } + entrysOut->data[i].data = (uint8_t *)crlEntry; + entrysOut->data[i].len = sizeof(HcfX509CrlEntry); + return HCF_SUCCESS; +} + +static void DestroyCRLEntryArray(HcfArray *arr) +{ + if (arr == NULL) { + LOGD("The input array is null, no need to free."); + return; + } + for (uint32_t i = 0; i < arr->count; ++i) { + if ((arr->data[i].data == NULL) || (arr->data[i].len = 0)) { + continue; + } + HcfX509CrlEntry *crlEntry = (HcfX509CrlEntry *)(arr->data[i].data); + crlEntry->base.destroy((HcfObjectBase *)crlEntry); + arr->data[i].data = NULL; + arr->data[i].len = 0; + } + HcfFree(arr->data); + arr->data = NULL; +} + +static HcfResult GetRevokedCerts(HcfX509CrlSpi *self, HcfArray *entrysOut) +{ + if ((self == NULL) || (entrysOut == NULL)) { + LOGE("Invalid Paramas!"); + return HCF_INVALID_PARAMS; + } + X509_CRL *crl = GetCrl(self); + if (crl == NULL) { + LOGE("crl is null!"); + return HCF_INVALID_PARAMS; + } + STACK_OF(X509_REVOKED) *entrys = X509_CRL_get_REVOKED(crl); + if (entrys == NULL) { + LOGE("Get revoked certificates fail!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + int32_t revokedNum = sk_X509_REVOKED_num(entrys); + if ((revokedNum < 0) || (revokedNum > MAX_REV_NUM)) { + LOGE("Get revoked invalid number!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + uint32_t blobSize = sizeof(HcfBlob) * revokedNum; + entrysOut->data = (HcfBlob *)HcfMalloc(blobSize, 0); + if (entrysOut->data == NULL) { + LOGE("Failed to malloc for entrysOut array!"); + return HCF_ERR_MALLOC; + } + entrysOut->count = revokedNum; + for (int32_t i = 0; i < revokedNum; i++) { + if (DeepCopyRevokedCertificates(self, entrys, i, entrysOut) != HCF_SUCCESS) { + LOGE("Falied to copy revoked certificates!"); + DestroyCRLEntryArray(entrysOut); + return HCF_ERR_MALLOC; + } + } + return HCF_SUCCESS; +} + +static HcfResult GetTbsList(HcfX509CrlSpi *self, HcfBlob *tbsCertListOut) +{ + if ((self == NULL) || (tbsCertListOut == NULL)) { + LOGE("Invalid Paramas!"); + return HCF_INVALID_PARAMS; + } + X509_CRL *crl = GetCrl(self); + if (crl == NULL) { + LOGE("crl is null!"); + return HCF_INVALID_PARAMS; + } + unsigned char *tbs = NULL; + int32_t length = i2d_re_X509_CRL_tbs(crl, &tbs); + if ((length <= 0) || (tbs == NULL)) { + LOGE("Get TBS certList fail!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + tbsCertListOut->data = (uint8_t *)HcfMalloc(length, 0); + if (tbsCertListOut->data == NULL) { + LOGE("Failed to malloc for tbs!"); + OPENSSL_free(tbs); + return HCF_ERR_MALLOC; + } + if (memcpy_s(tbsCertListOut->data, length, tbs, length) != EOK) { + LOGE("Failed to copy the tbs!"); + HcfFree(tbsCertListOut->data); + tbsCertListOut->data = NULL; + OPENSSL_free(tbs); + return HCF_ERR_COPY; + } + OPENSSL_free(tbs); + tbsCertListOut->len = length; + return HCF_SUCCESS; +} + +static HcfResult GetSignature(HcfX509CrlSpi *self, HcfBlob *signature) +{ + if ((self == NULL) || (signature == NULL)) { + LOGE("Invalid Paramas!"); + return HCF_INVALID_PARAMS; + } + X509_CRL *crl = GetCrl(self); + if (crl == NULL) { + LOGE("crl is null!"); + return HCF_INVALID_PARAMS; + } + const ASN1_BIT_STRING *ASN1Signature = NULL; + X509_CRL_get0_signature(((HcfX509CRLOpensslImpl *)self)->crl, &ASN1Signature, NULL); + if (ASN1Signature == NULL) { + LOGE("Get signature is null!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + int32_t signatureLen = ASN1_STRING_length(ASN1Signature); + if (signatureLen <= 0) { + LOGE("Get signature length is invalid!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + const unsigned char *signatureStr = ASN1_STRING_get0_data(ASN1Signature); + if ((signatureStr == NULL) || (signatureLen > MAX_SIGNATURE_LEN)) { + LOGE("ASN1 get string fail, or signature length is too long!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + signature->data = (uint8_t *)HcfMalloc(signatureLen, 0); + if (signature->data == NULL) { + LOGE("Failed to malloc for signature!"); + return HCF_ERR_MALLOC; + } + if (memcpy_s(signature->data, signatureLen, signatureStr, signatureLen) != EOK) { + LOGE("Failed to copy the signature!"); + HcfFree(signature->data); + signature->data = NULL; + return HCF_ERR_COPY; + } + signature->len = signatureLen; + return HCF_SUCCESS; +} + +static HcfResult getSignatureAlgOidInner(X509_CRL *crl, HcfBlob *oidOut) +{ + const X509_ALGOR *palg = NULL; + X509_CRL_get0_signature(crl, NULL, &palg); + if (palg == NULL) { + LOGE("alg is null!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + const ASN1_OBJECT *oid = NULL; + X509_ALGOR_get0(&oid, NULL, NULL, palg); + if (oid == NULL) { + LOGE("oid is null!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + char *output = (char *)HcfMalloc(OID_LENGTH, 0); + if (output == NULL) { + LOGE("Failed to malloc the output!"); + return HCF_ERR_MALLOC; + } + int32_t resLen = OBJ_obj2txt(output, OID_LENGTH, oid, 1); + if (resLen < 0) { + LOGE("Failed to do OBJ_obj2txt!"); + HcfPrintOpensslError(); + HcfFree(output); + return HCF_ERR_CRYPTO_OPERATION; + } + uint32_t length = strlen(output) + 1; + oidOut->data = (uint8_t *)HcfMalloc(length, 0); + if (oidOut->data == NULL) { + LOGE("Failed to malloc for oidOut!"); + HcfFree(output); + return HCF_ERR_MALLOC; + } + if (memcpy_s(oidOut->data, length, output, length) != EOK) { + LOGE("Failed to copy the oidOut!"); + HcfFree(oidOut->data); + oidOut->data = NULL; + HcfFree(output); + return HCF_ERR_COPY; + } + HcfFree(output); + oidOut->len = length; + return HCF_SUCCESS; +} + +static HcfResult getSignatureAlgOid(HcfX509CrlSpi *self, HcfBlob *oidOut) +{ + if ((self == NULL) || (oidOut == NULL)) { + LOGE("Invalid Paramas!"); + return HCF_INVALID_PARAMS; + } + X509_CRL *crl = GetCrl(self); + if (crl == NULL) { + LOGE("crl is null!"); + return HCF_INVALID_PARAMS; + } + return getSignatureAlgOidInner(crl, oidOut); +} + +static HcfResult GetSignatureAlgName(HcfX509CrlSpi *self, HcfBlob *algNameOut) +{ + if ((self == NULL) || (algNameOut == NULL)) { + LOGE("Invalid Paramas!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetClass())) { + LOGE("Input wrong class type!"); + return HCF_INVALID_PARAMS; + } + HcfBlob *oidOut = (HcfBlob *)HcfMalloc(sizeof(HcfBlob), 0); + HcfResult res = getSignatureAlgOid(self, oidOut); + if (res != HCF_SUCCESS) { + LOGE("Get signature algor oid failed!"); + HcfFree(oidOut); + return res; + } + const char *algName = GetAlgorithmName((const char*)(oidOut->data)); + HcfFree(oidOut->data); + HcfFree(oidOut); + if (algName == NULL) { + LOGE("Can not find algorithmName!"); + return HCF_ERR_CRYPTO_OPERATION; + } + uint32_t length = strlen(algName) + 1; + algNameOut->data = (uint8_t *)HcfMalloc(length, 0); + if (algNameOut->data == NULL) { + LOGE("Failed to malloc for algName!"); + return HCF_ERR_MALLOC; + } + if (memcpy_s(algNameOut->data, length, algName, length) != EOK) { + LOGE("Failed to copy the algName!"); + HcfFree(algNameOut->data); + algNameOut->data = NULL; + return HCF_ERR_COPY; + } + algNameOut->len = length; + return HCF_SUCCESS; +} + +static HcfResult GetSignatureAlgParamsInner(X509_CRL *crl, HcfBlob *sigAlgParamOut) +{ + const X509_ALGOR *palg = NULL; + X509_CRL_get0_signature(crl, NULL, &palg); + if (palg == NULL) { + LOGE("Get alg is null!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + int32_t param_type = 0; + const void *param_value = NULL; + X509_ALGOR_get0(NULL, ¶m_type, ¶m_value, palg); + if (param_type == V_ASN1_UNDEF) { + LOGE("get_X509_ALGOR_parameter, no parameters!"); + HcfPrintOpensslError(); + return HCF_NOT_SUPPORT; + } + ASN1_TYPE *param = ASN1_TYPE_new(); + if (ASN1_TYPE_set1(param, param_type, param_value) != HCF_OPENSSL_SUCCESS) { + LOGE("Set type fail!"); + ASN1_TYPE_free(param); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + unsigned char *outParams = NULL; + int32_t length = i2d_ASN1_TYPE(param, &outParams); + ASN1_TYPE_free(param); + if (length <= 0) { + LOGE("Do i2d_ASN1_TYPE fail!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + sigAlgParamOut->data = (uint8_t *)HcfMalloc(length, 0); + if (sigAlgParamOut->data == NULL) { + LOGE("Failed to malloc for sigAlgParam!"); + OPENSSL_free(outParams); + return HCF_ERR_MALLOC; + } + if (memcpy_s(sigAlgParamOut->data, length, outParams, length) != EOK) { + LOGE("Failed to copy the sigAlgParamOut!"); + HcfFree(sigAlgParamOut->data); + sigAlgParamOut->data = NULL; + OPENSSL_free(outParams); + return HCF_ERR_COPY; + } + sigAlgParamOut->len = length; + OPENSSL_free(outParams); + return HCF_SUCCESS; +} + +static HcfResult GetSignatureAlgParams(HcfX509CrlSpi *self, HcfBlob *sigAlgParamOut) +{ + if ((self == NULL) || (sigAlgParamOut == NULL)) { + LOGE("Invalid Paramas!"); + return HCF_INVALID_PARAMS; + } + X509_CRL *crl = GetCrl(self); + if (crl == NULL) { + LOGE("crl is null!"); + return HCF_INVALID_PARAMS; + } + return GetSignatureAlgParamsInner(crl, sigAlgParamOut); +} + +static void Destroy(HcfObjectBase *self) +{ + if (self == NULL) { + return; + } + if (!IsClassMatch(self, GetClass())) { + LOGE("Input wrong class type!"); + return; + } + HcfX509CRLOpensslImpl *realCrl = (HcfX509CRLOpensslImpl *)self; + X509_CRL_free(realCrl->crl); + realCrl->crl = NULL; + if (realCrl->certIssuer != NULL) { + HcfFree(realCrl->certIssuer->data); + realCrl->certIssuer->data = NULL; + HcfFree(realCrl->certIssuer); + realCrl->certIssuer = NULL; + } + HcfFree(realCrl); +} + +static X509_CRL *ParseX509CRL(const HcfEncodingBlob *inStream) +{ + if ((inStream->data == NULL) || (inStream->len <= 0)) { + LOGE("Invalid Paramas!"); + return NULL; + } + BIO *bio = BIO_new_mem_buf(inStream->data, inStream->len); + if (bio == NULL) { + LOGE("bio get null!"); + HcfPrintOpensslError(); + return NULL; + } + X509_CRL *crlOut = NULL; + switch (inStream->encodingFormat) { + case HCF_FORMAT_DER: + crlOut = d2i_X509_CRL_bio(bio, NULL); + break; + case HCF_FORMAT_PEM: + crlOut = PEM_read_bio_X509_CRL(bio, NULL, NULL, NULL); + break; + default: + LOGE("Not support format!"); + break; + } + if (crlOut == NULL) { + LOGE("Parse X509 CRL fail!"); + HcfPrintOpensslError(); + return NULL; + } + return crlOut; +} + +HcfResult HcfCX509CrlSpiCreate(const HcfEncodingBlob *inStream, HcfX509CrlSpi **spi) +{ + if ((inStream == NULL) || (inStream->data == NULL) || (spi == NULL)) { + LOGE("Invalid Paramas!"); + return HCF_INVALID_PARAMS; + } + HcfX509CRLOpensslImpl *returnCRL = (HcfX509CRLOpensslImpl *)HcfMalloc(sizeof(HcfX509CRLOpensslImpl), 0); + if (returnCRL == NULL) { + LOGE("Failed to malloc for x509 instance!"); + return HCF_ERR_MALLOC; + } + X509_CRL *crl = ParseX509CRL(inStream); + if (crl == NULL) { + LOGE("Failed to Parse x509 CRL!"); + HcfFree(returnCRL); + return HCF_INVALID_PARAMS; + } + returnCRL->crl = crl; + returnCRL->certIssuer = NULL; + returnCRL->base.base.getClass = GetClass; + returnCRL->base.base.destroy = Destroy; + returnCRL->base.engineIsRevoked = IsRevoked; + returnCRL->base.engineGetType = GetType; + returnCRL->base.engineGetEncoded = GetEncoded; + returnCRL->base.engineVerify = Verify; + returnCRL->base.engineGetVersion = GetVersion; + returnCRL->base.engineGetIssuerName = GetIssuerName; + returnCRL->base.engineGetLastUpdate = GetLastUpdate; + returnCRL->base.engineGetNextUpdate = GetNextUpdate; + returnCRL->base.engineGetRevokedCert = GetRevokedCert; + returnCRL->base.engineGetRevokedCertWithCert = GetRevokedCertWithCert; + returnCRL->base.engineGetRevokedCerts = GetRevokedCerts; + returnCRL->base.engineGetTbsInfo = GetTbsList; + returnCRL->base.engineGetSignature = GetSignature; + returnCRL->base.engineGetSignatureAlgName = GetSignatureAlgName; + returnCRL->base.engineGetSignatureAlgOid = getSignatureAlgOid; + returnCRL->base.engineGetSignatureAlgParams = GetSignatureAlgParams; + if (SetCertIssuer((HcfX509CrlSpi *)returnCRL) != HCF_SUCCESS) { + LOGI("No cert issuer find or set cert issuer fail!"); + } + *spi = (HcfX509CrlSpi *)returnCRL; + return HCF_SUCCESS; +} \ No newline at end of file diff --git a/plugin/openssl_plugin/common/inc/openssl_class.h b/plugin/openssl_plugin/common/inc/openssl_class.h new file mode 100644 index 0000000..818e451 --- /dev/null +++ b/plugin/openssl_plugin/common/inc/openssl_class.h @@ -0,0 +1,103 @@ +/* + * Copyright (C) 2022 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_OEPNSSL_CLASS_H +#define HCF_OEPNSSL_CLASS_H + +#include "pub_key.h" +#include "pri_key.h" +#include "key_pair.h" +#include "x509_certificate_spi.h" +#include "x509_crl_entry.h" +#include "x509_crl.h" +#include "x509_crl_spi.h" + +#include +#include +#include +#include +#include + +typedef struct { + HcfPubKey base; + + int32_t curveId; + + EC_POINT *pk; +} HcfOpensslEccPubKey; +#define HCF_OPENSSL_ECC_PUB_KEY_CLASS "OPENSSL.ECC.PUB_KEY" + +typedef struct { + HcfPriKey base; + + int32_t curveId; + + BIGNUM *sk; +} HcfOpensslEccPriKey; +#define HCF_OPENSSL_ECC_PRI_KEY_CLASS "OPENSSL.ECC.PRI_KEY" + +typedef struct { + HcfKeyPair base; +} HcfOpensslEccKeyPair; +#define HCF_OPENSSL_ECC_KEY_PAIR_CLASS "OPENSSL.ECC.KEY_PAIR" + +typedef struct { + HcfPubKey base; + + uint32_t bits; + + RSA *pk; +} HcfOpensslRsaPubKey; +#define OPENSSL_RSA_PUBKEY_CLASS "OPENSSL.RSA.PUB_KEY" + +typedef struct { + HcfPriKey base; + + uint32_t bits; + + RSA *sk; +} HcfOpensslRsaPriKey; +#define OPENSSL_RSA_PRIKEY_CLASS "OPENSSL.RSA.PRI_KEY" + +typedef struct { + HcfKeyPair base; +} HcfOpensslRsaKeyPair; +#define OPENSSL_RSA_KEYPAIR_CLASS "OPENSSL.RSA.KEY_PAIR" + +typedef struct { + HcfX509CertificateSpi base; + X509 *x509; +} HcfOpensslX509Cert; +#define X509_CERT_OPENSSL_CLASS "X509CertOpensslClass" + +typedef struct { + HcfX509CrlEntry base; + X509_REVOKED *rev; + HcfBlob *certIssuer; +} HcfX509CRLEntryOpensslImpl; +#define X509_CRL_ENTRY_OPENSSL_CLASS "X509CrlEntryOpensslClass" + +typedef struct { + HcfX509Crl base; + HcfX509CrlSpi *spiObj; + const char *certType; +} HcfX509CrlImpl; +#define X509_CRL_OPENSSL_CLASS "X509CrlOpensslClass" + +#define OPENSSL_RSA_CIPHER_CLASS "OPENSSL.RSA.CIPHER" +#define OPENSSL_3DES_CIPHER_CLASS "OPENSSL.3DES.CIPHER" +#define OPENSSL_AES_CIPHER_CLASS "OPENSSL.AES.CIPHER" + +#endif diff --git a/plugin/openssl_plugin/common/inc/openssl_common.h b/plugin/openssl_plugin/common/inc/openssl_common.h new file mode 100644 index 0000000..0ac660d --- /dev/null +++ b/plugin/openssl_plugin/common/inc/openssl_common.h @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2022 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_OPENSSL_COMMON_H +#define HCF_OPENSSL_COMMON_H + +#include +#include +#include +#include +#include + +#define HCF_OPENSSL_SUCCESS 1 /* openssl return 1: success */ +#define HCF_BITS_PER_BYTE 8 + +#ifdef __cplusplus +extern "C" { +#endif + +const char *GetAlgorithmName(const char *oid); +int32_t GetOpensslCurveId(int32_t keyLen, int32_t *returnCurveId); +const EVP_MD *GetOpensslDigestAlg(uint32_t alg); +void HcfPrintOpensslError(void); + +int32_t GetOpensslPadding(int32_t padding, int32_t *opensslPadding); + +int32_t GetRealPrimes(int32_t primesFlag); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/plugin/openssl_plugin/common/inc/plugin_defines.h b/plugin/openssl_plugin/common/inc/plugin_defines.h new file mode 100644 index 0000000..ded7efc --- /dev/null +++ b/plugin/openssl_plugin/common/inc/plugin_defines.h @@ -0,0 +1,16 @@ +/* + * Copyright (C) 2022 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. + */ + +#define HCF_OPENSSL_SUCCESS 1 // openssl interface return 1, means success. \ No newline at end of file diff --git a/plugin/openssl_plugin/common/inc/rsa_openssl_common.h b/plugin/openssl_plugin/common/inc/rsa_openssl_common.h new file mode 100644 index 0000000..c81ac18 --- /dev/null +++ b/plugin/openssl_plugin/common/inc/rsa_openssl_common.h @@ -0,0 +1,33 @@ +/* + * Copyright (C) 2022 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 "openssl/rsa.h" +#include "result.h" +#include "stdbool.h" + +typedef enum { + INITIALIZED, + UNINITIALIZED +} InitFlag; + +#ifdef __cplusplus +extern "C" { +#endif + +HcfResult DuplicateRsa(const RSA *rsa, bool needPrivate, RSA **dupRsa); + +#ifdef __cplusplus +} +#endif \ No newline at end of file diff --git a/plugin/openssl_plugin/common/src/openssl_common.c b/plugin/openssl_plugin/common/src/openssl_common.c new file mode 100644 index 0000000..6dbc36e --- /dev/null +++ b/plugin/openssl_plugin/common/src/openssl_common.c @@ -0,0 +1,180 @@ +/* + * Copyright (C) 2022 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 "openssl_common.h" + +#include +#include +#include "config.h" +#include "log.h" +#include "result.h" +#include "params_parser.h" + +#define PRIMES_2 2 +#define PRIMES_3 3 +#define PRIMES_4 4 +#define PRIMES_5 5 + +typedef struct { + char *oid; + char *algorithmName; +} OidToAlgorithmName; + +static const OidToAlgorithmName OID_TO_NAME_MAP[] = { + { "1.2.840.113549.1.1.2", "MD2withRSA" }, + { "1.2.840.113549.1.1.4", "MD5withRSA" }, + { "1.2.840.113549.1.1.5", "SHA1withRSA" }, + { "1.2.840.10040.4.3", "SHA1withDSA" }, + { "1.2.840.10045.4.1", "SHA1withECDSA" }, + { "1.2.840.113549.1.1.14", "SHA224withRSA" }, + { "1.2.840.113549.1.1.11", "SHA256withRSA" }, + { "1.2.840.113549.1.1.12", "SHA384withRSA" }, + { "1.2.840.113549.1.1.13", "SHA512withRSA" }, + { "2.16.840.1.101.3.4.3.1", "SHA224withDSA" }, + { "2.16.840.1.101.3.4.3.2", "SHA256withDSA" }, + { "1.2.840.10045.4.3.1", "SHA224withECDSA" }, + { "1.2.840.10045.4.3.2", "SHA256withECDSA" }, + { "1.2.840.10045.4.3.3", "SHA384withECDSA" }, + { "1.2.840.10045.4.3.4", "SHA512withECDSA" } +}; + +const char *GetAlgorithmName(const char *oid) +{ + if (oid == NULL) { + LOGE("Oid is null!"); + return NULL; + } + for (uint32_t i = 0; i < sizeof(OID_TO_NAME_MAP); i++) { + if (strcmp(OID_TO_NAME_MAP[i].oid, oid) == 0) { + return OID_TO_NAME_MAP[i].algorithmName; + } + } + LOGE("Can not find algorithmName! [oid]: %s", oid); + return NULL; +} + +int32_t GetOpensslCurveId(int32_t keyLen, int32_t *returnCurveId) +{ + switch (keyLen) { + case HCF_ALG_ECC_224: + *returnCurveId = NID_secp224r1; + break; + case HCF_ALG_ECC_256: + *returnCurveId = NID_X9_62_prime256v1; + break; + case HCF_ALG_ECC_384: + *returnCurveId = NID_secp384r1; + break; + case HCF_ALG_ECC_512: + *returnCurveId = NID_secp521r1; + break; + default: + LOGE("invalid key size."); + return HCF_INVALID_PARAMS; + } + + return HCF_SUCCESS; +} + +const EVP_MD *GetOpensslDigestAlg(uint32_t alg) +{ + switch (alg) { + case HCF_OPENSSL_DIGEST_NONE: + return NULL; + case HCF_OPENSSL_DIGEST_MD5: + LOGI("set EVP_md5"); + return EVP_md5(); + case HCF_OPENSSL_DIGEST_SHA1: + LOGI("set EVP_sha1"); + return EVP_sha1(); + case HCF_OPENSSL_DIGEST_SHA224: + LOGI("set EVP_sha224"); + return EVP_sha224(); + case HCF_OPENSSL_DIGEST_SHA256: + LOGI("set EVP_sha256"); + return EVP_sha256(); + case HCF_OPENSSL_DIGEST_SHA384: + LOGI("set EVP_sha384"); + return EVP_sha384(); + case HCF_OPENSSL_DIGEST_SHA512: + LOGI("set EVP_sha512"); + return EVP_sha512(); + default: + LOGE("Invalid digest num is %u.", alg); + return NULL; + } +} + +void HcfPrintOpensslError(void) +{ + char szErr[LOG_PRINT_MAX_LEN] = {0}; + unsigned long errCode; + + errCode = ERR_get_error(); + ERR_error_string_n(errCode, szErr, LOG_PRINT_MAX_LEN); + + LOGE("[Openssl]: engine fail, error code = %lu, error string = %s", errCode, szErr); +} + +int32_t GetOpensslPadding(int32_t padding, int32_t *opensslPadding) +{ + switch (padding) { + case HCF_ALG_NOPADDING: + LOGI("set RSA_NO_PADDING"); + *opensslPadding = RSA_NO_PADDING; + return HCF_SUCCESS; + + case HCF_OPENSSL_RSA_PKCS1_PADDING: + LOGI("set RSA_PKCS1_PADDING"); + *opensslPadding = RSA_PKCS1_PADDING; + return HCF_SUCCESS; + + case HCF_OPENSSL_RSA_PKCS1_OAEP_PADDING: + LOGI("set RSA_PKCS1_OAEP_PADDING"); + *opensslPadding = RSA_PKCS1_OAEP_PADDING; + return HCF_SUCCESS; + + case HCF_OPENSSL_RSA_PSS_PADDING: + LOGI("set RSA_PKCS1_PSS_PADDING"); + *opensslPadding = RSA_PKCS1_PSS_PADDING; + return HCF_SUCCESS; + + default: + LOGE("Invalid framwork padding = %d", padding); + return HCF_INVALID_PARAMS; + } +} + +int32_t GetRealPrimes(int32_t primesFlag) +{ + switch (primesFlag) { + case HCF_OPENSSL_PRIMES_2: + LOGI("set primes 2"); + return PRIMES_2; + case HCF_OPENSSL_PRIMES_3: + LOGI("set primes 3"); + return PRIMES_3; + case HCF_OPENSSL_PRIMES_4: + LOGI("set primes 4"); + return PRIMES_4; + case HCF_OPENSSL_PRIMES_5: + LOGI("set primes 5"); + return PRIMES_5; + default: + LOGI("set default primes 2"); + return PRIMES_2; + } +} + diff --git a/plugin/openssl_plugin/common/src/rsa_openssl_common.c b/plugin/openssl_plugin/common/src/rsa_openssl_common.c new file mode 100644 index 0000000..55450ae --- /dev/null +++ b/plugin/openssl_plugin/common/src/rsa_openssl_common.c @@ -0,0 +1,110 @@ +/* + * Copyright (C) 2022 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 "rsa_openssl_common.h" +#include "log.h" +#include "plugin_defines.h" + +static HcfResult DuplicateBigNumFromRSA(BIGNUM **n, BIGNUM **e, BIGNUM **d, bool needPrivate, const RSA *rsa) +{ + const BIGNUM *tmpN = NULL, *tmpE = NULL, *tmpD = NULL; + RSA_get0_key(rsa, &tmpN, &tmpE, &tmpD); + if (tmpN == NULL || tmpE == NULL || (needPrivate && tmpD == NULL)) { + LOGE("Rsa get bignum n e d fail."); + return HCF_ERR_CRYPTO_OPERATION; + } + BIGNUM *retN = NULL, *retE = NULL, *retD = NULL; + retN = BN_dup(tmpN); + if (retN == NULL) { + LOGE("Dup n fail"); + goto ERR; + } + retE = BN_dup(tmpE); + if (retE == NULL) { + LOGE("Dup e fail"); + goto ERR; + } + if (needPrivate) { + retD = BN_dup(tmpD); + if (retD == NULL) { + LOGE("Dup d fail"); + goto ERR; + } + } + *n = retN; + *e = retE; + *d = retD; + + return HCF_SUCCESS; +ERR: + BN_clear_free(retN); + BN_clear_free(retE); + BN_clear_free(retD); + return HCF_ERR_CRYPTO_OPERATION; +} + +static HcfResult InitRsaStruct(BIGNUM *n, BIGNUM *e, BIGNUM *d, const bool needPrivateExponent, RSA **rsa) +{ + HcfResult ret = HCF_ERR_CRYPTO_OPERATION; + if (rsa == NULL || n == NULL || e == NULL) { + LOGE("InitRsaStruct params error."); + ret = HCF_INVALID_PARAMS; + goto ERR; + } + // private key need d, public key can't set key + if ((needPrivateExponent && d == NULL) || (!needPrivateExponent && d != NULL)) { + LOGE("The input BigNum is invalid."); + ret = HCF_INVALID_PARAMS; + goto ERR; + } + *rsa = RSA_new(); + if (*rsa == NULL) { + LOGE("New RSA fail"); + ret = HCF_ERR_MALLOC; + goto ERR; + } + if (RSA_set0_key(*rsa, n, e, d) != HCF_OPENSSL_SUCCESS) { + LOGE("RSA_set0_key fail."); + RSA_free(*rsa); + *rsa = NULL; + ret = HCF_ERR_CRYPTO_OPERATION; + goto ERR; + } + return HCF_SUCCESS; +ERR: + BN_clear_free(n); + BN_clear_free(e); + BN_clear_free(d); + return ret; +} + +HcfResult DuplicateRsa(const RSA *rsa, bool needPrivate, RSA **dupRsa) +{ + if (rsa == NULL || dupRsa == NULL) { + LOGE("Rsa or dupRsa is NULL."); + return HCF_INVALID_PARAMS; + } + BIGNUM *n = NULL; + BIGNUM *e = NULL; + BIGNUM *d = NULL; + if (DuplicateBigNumFromRSA(&n, &e, &d, needPrivate, rsa) != HCF_SUCCESS) { + LOGE("duplicate pk bignum fail"); + return HCF_ERR_CRYPTO_OPERATION; + } + if (InitRsaStruct(n, e, d, needPrivate, dupRsa) != HCF_SUCCESS) { + LOGE("Generate PriKey fail."); + return HCF_ERR_CRYPTO_OPERATION; + } + return HCF_SUCCESS; +} \ No newline at end of file diff --git a/plugin/openssl_plugin/crypto_operation/aes/inc/aes_openssl.h b/plugin/openssl_plugin/crypto_operation/aes/inc/aes_openssl.h new file mode 100644 index 0000000..157e38b --- /dev/null +++ b/plugin/openssl_plugin/crypto_operation/aes/inc/aes_openssl.h @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2022 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_AES_OPENSSL_H +#define HCF_AES_OPENSSL_H + +#include +#include "params_parser.h" +#include "cipher_factory_spi.h" +#include + +typedef struct { + EVP_CIPHER_CTX *ctx; + enum HcfCryptoMode enc; + /* EVP_CIPH_GCM_MODE, EVP_CIPH_CCM_MODE need AEAD */ + bool aead; + uint32_t updateLen; + unsigned char *iv; + uint32_t ivLen; + /* GCM, CCM only */ + unsigned char *aad; + uint32_t aadLen; + unsigned char *tag; + uint32_t tagLen; +} CipherData; + +#ifdef __cplusplus +extern "C" { +#endif + +HcfResult HcfCipherDesGeneratorSpiCreate(CipherAttr *attr, OH_HCF_CipherGeneratorSpi **generator); + +HcfResult HcfCipherAesGeneratorSpiCreate(CipherAttr *attr, OH_HCF_CipherGeneratorSpi **generator); + +#ifdef __cplusplus +} +#endif + +#endif + diff --git a/plugin/openssl_plugin/crypto_operation/aes/inc/aes_openssl_common.h b/plugin/openssl_plugin/crypto_operation/aes/inc/aes_openssl_common.h new file mode 100644 index 0000000..e64407e --- /dev/null +++ b/plugin/openssl_plugin/crypto_operation/aes/inc/aes_openssl_common.h @@ -0,0 +1,63 @@ +/* + * Copyright (C) 2022 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. + */ + +/* + * Copyright (C) 2022 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_AES_OPENSSL_COMMON_H +#define HCF_AES_OPENSSL_COMMON_H + +#include "detailed_iv_params.h" +#include "detailed_ccm_params.h" +#include "detailed_gcm_params.h" + + +#include "aes_openssl.h" + +#include + +#ifdef __cplusplus +extern "C" { +#endif +const unsigned char *GetIv(HcfParamsSpec *params); + +int32_t GetIvLen(HcfParamsSpec *params); + +int32_t GetGcmTagLen(HcfParamsSpec *params); + +int32_t GetCcmTagLen(HcfParamsSpec *params); + +void *GetGcmTag(HcfParamsSpec *params); + +void *GetCcmTag(HcfParamsSpec *params); + +void FreeCipherData(CipherData **data); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/plugin/openssl_plugin/crypto_operation/aes/src/cipher_3des_openssl.c b/plugin/openssl_plugin/crypto_operation/aes/src/cipher_3des_openssl.c new file mode 100644 index 0000000..bdab451 --- /dev/null +++ b/plugin/openssl_plugin/crypto_operation/aes/src/cipher_3des_openssl.c @@ -0,0 +1,296 @@ +/* + * Copyright (C) 2022 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 "log.h" +#include "blob.h" +#include "memory.h" +#include "result.h" +#include "utils.h" +#include "securec.h" +#include "aes_openssl_common.h" +#include "sym_common_defines.h" +#include "openssl_common.h" +#include "openssl_class.h" + +#define DES_BLOCK_SIZE 8 + +typedef struct { + OH_HCF_CipherGeneratorSpi base; + CipherAttr attr; + CipherData *cipherData; +} HcfCipherDesGeneratorSpiOpensslImpl; + +static const char *GetDesGeneratorClass() +{ + return OPENSSL_3DES_CIPHER_CLASS; +} + +static const EVP_CIPHER *DefautCiherType() +{ + return EVP_des_ede3_ecb(); +} + +static const EVP_CIPHER *GetCipherType(HcfCipherDesGeneratorSpiOpensslImpl *impl) +{ + switch (impl->attr.mode) { + case HCF_ALG_MODE_ECB: + return EVP_des_ede3_ecb(); + case HCF_ALG_MODE_CBC: + return EVP_des_ede3_cbc(); + case HCF_ALG_MODE_OFB: + return EVP_des_ede3_ofb(); + case HCF_ALG_MODE_CFB: + case HCF_ALG_MODE_CFB64: + return EVP_des_ede3_cfb64(); + case HCF_ALG_MODE_CFB1: + return EVP_des_ede3_cfb1(); + case HCF_ALG_MODE_CFB8: + return EVP_des_ede3_cfb8(); + default: + break; + } + return DefautCiherType(); +} + +static HcfResult InitCipherData(enum HcfCryptoMode opMode, CipherData **cipherData) +{ + HcfResult ret = HCF_INVALID_PARAMS; + + *cipherData = (CipherData *)HcfMalloc(sizeof(CipherData), 0); + if (*cipherData == NULL) { + LOGE("malloc failed!"); + return HCF_ERR_MALLOC; + } + + (*cipherData)->enc = opMode; + (*cipherData)->ctx = EVP_CIPHER_CTX_new(); + if ((*cipherData)->ctx == NULL) { + HcfPrintOpensslError(); + LOGE("Failed to allocate ctx memroy!"); + goto clearup; + } + + ret = HCF_SUCCESS; + return ret; +clearup: + FreeCipherData(cipherData); + return ret; +} + +static HcfResult EngineCipherInit(OH_HCF_CipherGeneratorSpi *self, enum HcfCryptoMode opMode, + HcfKey *key, HcfParamsSpec *params) +{ + if ((self == NULL) || (key == NULL)) { /* params maybe is null */ + LOGE("Invalid input parameter!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((const HcfObjectBase *)self, GetDesGeneratorClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((const HcfObjectBase *)key, OPENSSL_SYM_KEY_CLASS)) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + + HcfCipherDesGeneratorSpiOpensslImpl *cipherImpl = (HcfCipherDesGeneratorSpiOpensslImpl *)self; + SymKeyImpl *keyImpl = (SymKeyImpl *)key; + + int32_t enc = (opMode == ENCRYPT_MODE) ? 1 : 0; + + if (InitCipherData(opMode, &(cipherImpl->cipherData)) != HCF_SUCCESS) { + LOGE("InitCipherData failed"); + return HCF_INVALID_PARAMS; + } + HcfResult ret = HCF_ERR_CRYPTO_OPERATION; + CipherData *data = cipherImpl->cipherData; + if (EVP_CipherInit(data->ctx, GetCipherType(cipherImpl), NULL, NULL, enc) != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + LOGE("cipher init failed!"); + goto clearup; + } + if (EVP_CipherInit(data->ctx, NULL, keyImpl->keyMaterial.data, GetIv(params), enc) != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + LOGE("cipher init key and iv failed!"); + goto clearup; + } + int32_t padding = (cipherImpl->attr.paddingMode == HCF_ALG_NOPADDING) ? 0 : EVP_PADDING_PKCS7; + if (EVP_CIPHER_CTX_set_padding(data->ctx, padding) != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + LOGE("set padding!"); + goto clearup; + } + return HCF_SUCCESS; +clearup: + FreeCipherData(&(cipherImpl->cipherData)); + return ret; +} + +static HcfResult AllocateOutput(HcfBlob *input, HcfBlob *output) +{ + uint32_t outLen = 0; + if (IsBlobValid(input)) { + outLen += input->len; + } + outLen += DES_BLOCK_SIZE; + if (outLen == 0) { + LOGE("output size is invaild!"); + return HCF_INVALID_PARAMS; + } + output->data = (uint8_t *)HcfMalloc(outLen, 0); + if (output->data == NULL) { + LOGE("malloc output failed!"); + return HCF_ERR_MALLOC; + } + output->len = outLen; + return HCF_SUCCESS; +} + +static HcfResult EngineUpdate(OH_HCF_CipherGeneratorSpi *self, HcfBlob *input, HcfBlob *output) +{ + if ((self == NULL) || (input == NULL) || (output == NULL)) { + LOGE("Invalid input parameter!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((const HcfObjectBase *)self, GetDesGeneratorClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + + HcfCipherDesGeneratorSpiOpensslImpl *cipherImpl = (HcfCipherDesGeneratorSpiOpensslImpl *)self; + CipherData *data = cipherImpl->cipherData; + if (data == NULL) { + LOGE("cipherData is null!"); + return HCF_INVALID_PARAMS; + } + HcfResult res = AllocateOutput(input, output); + if (res != HCF_SUCCESS) { + LOGE("AllocateOutput failed!"); + goto clearup; + } + + int32_t ret = EVP_CipherUpdate(data->ctx, output->data, (int *)&output->len, + input->data, input->len); + if (ret != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + LOGE("cipher update failed!"); + res = HCF_ERR_CRYPTO_OPERATION; + goto clearup; + } + res = HCF_SUCCESS; +clearup: + if (res != HCF_SUCCESS) { + HcfBlobDataFree(output); + FreeCipherData(&(cipherImpl->cipherData)); + } + return res; +} + +static HcfResult DesDoFinal(CipherData *data, HcfBlob *input, HcfBlob *output) +{ + int32_t ret; + uint32_t len = 0; + + if (IsBlobValid(input)) { + ret = EVP_CipherUpdate(data->ctx, output->data, (int *)&output->len, + input->data, input->len); + if (ret != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + LOGE("cipher update failed!"); + return HCF_ERR_CRYPTO_OPERATION; + } + len += output->len; + } + ret = EVP_CipherFinal_ex(data->ctx, output->data + len, (int *)&output->len); + if (ret != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + LOGE("cipher final filed!"); + return HCF_ERR_CRYPTO_OPERATION; + } + output->len += len; + return HCF_SUCCESS; +} + +static HcfResult EngineDoFinal(OH_HCF_CipherGeneratorSpi *self, HcfBlob *input, HcfBlob *output) +{ + if ((self == NULL) || (output == NULL)) { /* input maybe is null */ + LOGE("Invalid input parameter!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((const HcfObjectBase *)self, GetDesGeneratorClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + HcfCipherDesGeneratorSpiOpensslImpl *cipherImpl = (HcfCipherDesGeneratorSpiOpensslImpl *)self; + CipherData *data = cipherImpl->cipherData; + if (data == NULL) { + LOGE("cipherData is null!"); + return HCF_INVALID_PARAMS; + } + + HcfResult res = AllocateOutput(input, output); + if (res != HCF_SUCCESS) { + LOGE("AllocateOutput failed!"); + goto clearup; + } + res = DesDoFinal(data, input, output); + if (res != HCF_SUCCESS) { + LOGE("DesDoFinal failed!"); + } +clearup: + if (res != HCF_SUCCESS) { + HcfBlobDataFree(output); + } + FreeCipherData(&(cipherImpl->cipherData)); + return res; +} + +static void EngineDesGeneratorDestroy(HcfObjectBase *self) +{ + if (self == NULL) { + return; + } + if (!IsClassMatch(self, GetDesGeneratorClass())) { + LOGE("Class is not match."); + return; + } + HcfCipherDesGeneratorSpiOpensslImpl *impl = (HcfCipherDesGeneratorSpiOpensslImpl *)self; + FreeCipherData(&(impl->cipherData)); + HcfFree(impl); +} + +HcfResult HcfCipherDesGeneratorSpiCreate(CipherAttr *attr, OH_HCF_CipherGeneratorSpi **generator) +{ + if ((attr == NULL) || (generator == NULL)) { + LOGE("Invalid input parameter!"); + return HCF_INVALID_PARAMS; + } + HcfCipherDesGeneratorSpiOpensslImpl *returnImpl = (HcfCipherDesGeneratorSpiOpensslImpl *)HcfMalloc( + sizeof(HcfCipherDesGeneratorSpiOpensslImpl), 0); + if (returnImpl == NULL) { + LOGE("Failed to allocate returnImpl memroy!"); + return HCF_ERR_MALLOC; + } + (void)memcpy_s(&returnImpl->attr, sizeof(CipherAttr), attr, sizeof(CipherAttr)); + returnImpl->base.init = EngineCipherInit; + returnImpl->base.update = EngineUpdate; + returnImpl->base.doFinal = EngineDoFinal; + returnImpl->base.base.destroy = EngineDesGeneratorDestroy; + returnImpl->base.base.getClass = GetDesGeneratorClass; + + *generator = (OH_HCF_CipherGeneratorSpi *)returnImpl; + return HCF_SUCCESS; +} diff --git a/plugin/openssl_plugin/crypto_operation/aes/src/cipher_aes_common.c b/plugin/openssl_plugin/crypto_operation/aes/src/cipher_aes_common.c new file mode 100644 index 0000000..e416e1c --- /dev/null +++ b/plugin/openssl_plugin/crypto_operation/aes/src/cipher_aes_common.c @@ -0,0 +1,105 @@ +/* + * Copyright (C) 2022 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 "aes_openssl_common.h" + +#include "log.h" +#include "memory.h" +#include "result.h" + +const unsigned char *GetIv(HcfParamsSpec *params) +{ + if (params == NULL) { + return NULL; + } + HcfIvParamsSpec *spec = (HcfIvParamsSpec *)params; + uint8_t *iv = spec->iv.data; + return (const unsigned char *)iv; +} + +int32_t GetIvLen(HcfParamsSpec *params) +{ + if (params == NULL) { + return 0; + } + HcfIvParamsSpec *spec = (HcfIvParamsSpec *)params; + size_t ivLen = spec->iv.len; + return (int)ivLen; +} + +int32_t GetGcmTagLen(HcfParamsSpec *params) +{ + if (params == NULL) { + return 0; + } + HcfGcmParamsSpec *spec = (HcfGcmParamsSpec *)params; + size_t tagLen = spec->tag.len; + return (int)tagLen; +} + +int32_t GetCcmTagLen(HcfParamsSpec *params) +{ + if (params == NULL) { + return 0; + } + HcfCcmParamsSpec *spec = (HcfCcmParamsSpec *)params; + size_t tagLen = spec->tag.len; + return (int)tagLen; +} + +void *GetGcmTag(HcfParamsSpec *params) +{ + if (params == NULL) { + return NULL; + } + HcfGcmParamsSpec *spec = (HcfGcmParamsSpec *)params; + uint8_t *tag = spec->tag.data; + return (void *)tag; +} + +void *GetCcmTag(HcfParamsSpec *params) +{ + if (params == NULL) { + return NULL; + } + HcfCcmParamsSpec *spec = (HcfCcmParamsSpec *)params; + uint8_t *tag = spec->tag.data; + return (void *)tag; +} + +void FreeCipherData(CipherData **data) +{ + if (data == NULL || *data == NULL) { + return; + } + if ((*data)->ctx != NULL) { + EVP_CIPHER_CTX_free((*data)->ctx); + (*data)->ctx = NULL; + } + if ((*data)->aad != NULL) { + HcfFree((*data)->aad); + (*data)->aad = NULL; + } + if ((*data)->iv != NULL) { + HcfFree((*data)->iv); + (*data)->iv = NULL; + } + if ((*data)->tag != NULL) { + HcfFree((*data)->tag); + (*data)->tag = NULL; + } + HcfFree(*data); + *data = NULL; +} diff --git a/plugin/openssl_plugin/crypto_operation/aes/src/cipher_aes_openssl.c b/plugin/openssl_plugin/crypto_operation/aes/src/cipher_aes_openssl.c new file mode 100644 index 0000000..99fd586 --- /dev/null +++ b/plugin/openssl_plugin/crypto_operation/aes/src/cipher_aes_openssl.c @@ -0,0 +1,779 @@ +/* + * Copyright (C) 2022 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 "securec.h" +#include "blob.h" +#include "log.h" +#include "memory.h" +#include "result.h" +#include "utils.h" +#include "aes_openssl_common.h" +#include "sym_common_defines.h" +#include "openssl_common.h" +#include "openssl_class.h" + +#define MAX_AAD_LEN 2048 +#define GCM_IV_LEN 12 +#define CCM_IV_MIN_LEN 7 +#define CCM_IV_MAX_LEN 13 +#define AES_BLOCK_SIZE 16 +#define GCM_TAG_SIZE 16 +#define CCM_TAG_SIZE 12 + +typedef struct { + OH_HCF_CipherGeneratorSpi base; + CipherAttr attr; + CipherData *cipherData; +} HcfCipherAesGeneratorSpiOpensslImpl; + +static const char *GetAesGeneratorClass() +{ + return OPENSSL_AES_CIPHER_CLASS; +} + +static const EVP_CIPHER *DefautCiherType() +{ + return EVP_aes_128_ecb(); +} + +static const EVP_CIPHER *CipherEcbType(HCF_ALG_PARA_VALUE value) +{ + switch (value) { + case HCF_ALG_AES_128: + return EVP_aes_128_ecb(); + case HCF_ALG_AES_192:; + return EVP_aes_192_ecb(); + case HCF_ALG_AES_256: + return EVP_aes_256_ecb(); + default: + break; + } + return EVP_aes_128_ecb(); +} + +static const EVP_CIPHER *CipherCbcType(HCF_ALG_PARA_VALUE value) +{ + switch (value) { + case HCF_ALG_AES_128: + return EVP_aes_128_cbc(); + case HCF_ALG_AES_192:; + return EVP_aes_192_cbc(); + case HCF_ALG_AES_256: + return EVP_aes_256_cbc(); + default: + break; + } + return EVP_aes_128_cbc(); +} + +static const EVP_CIPHER *CipherCtrType(HCF_ALG_PARA_VALUE value) +{ + switch (value) { + case HCF_ALG_AES_128: + return EVP_aes_128_ctr(); + case HCF_ALG_AES_192:; + return EVP_aes_192_ctr(); + case HCF_ALG_AES_256: + return EVP_aes_256_ctr(); + default: + break; + } + return EVP_aes_128_ctr(); +} + +static const EVP_CIPHER *CipherOfbType(HCF_ALG_PARA_VALUE value) +{ + switch (value) { + case HCF_ALG_AES_128: + return EVP_aes_128_ofb(); + case HCF_ALG_AES_192:; + return EVP_aes_192_ofb(); + case HCF_ALG_AES_256: + return EVP_aes_256_ofb(); + default: + break; + } + return EVP_aes_128_ofb(); +} + +static const EVP_CIPHER *CipherCfbType(HCF_ALG_PARA_VALUE value) +{ + switch (value) { + case HCF_ALG_AES_128: + return EVP_aes_128_cfb(); + case HCF_ALG_AES_192:; + return EVP_aes_192_cfb(); + case HCF_ALG_AES_256: + return EVP_aes_256_cfb(); + default: + break; + } + return EVP_aes_128_cfb(); +} + +static const EVP_CIPHER *CipherCfb1Type(HCF_ALG_PARA_VALUE value) +{ + switch (value) { + case HCF_ALG_AES_128: + return EVP_aes_128_cfb1(); + case HCF_ALG_AES_192:; + return EVP_aes_192_cfb1(); + case HCF_ALG_AES_256: + return EVP_aes_256_cfb1(); + default: + break; + } + return EVP_aes_128_cfb1(); +} + +static const EVP_CIPHER *CipherCfb128Type(HCF_ALG_PARA_VALUE value) +{ + switch (value) { + case HCF_ALG_AES_128: + return EVP_aes_128_cfb128(); + case HCF_ALG_AES_192:; + return EVP_aes_192_cfb128(); + case HCF_ALG_AES_256: + return EVP_aes_256_cfb128(); + default: + break; + } + return EVP_aes_128_cfb128(); +} + +static const EVP_CIPHER *CipherCfb8Type(HCF_ALG_PARA_VALUE value) +{ + switch (value) { + case HCF_ALG_AES_128: + return EVP_aes_128_cfb8(); + case HCF_ALG_AES_192:; + return EVP_aes_192_cfb8(); + case HCF_ALG_AES_256: + return EVP_aes_256_cfb8(); + default: + break; + } + return EVP_aes_128_cfb8(); +} + + +static const EVP_CIPHER *CipherCcmType(HCF_ALG_PARA_VALUE value) +{ + switch (value) { + case HCF_ALG_AES_128: + return EVP_aes_128_ccm(); + case HCF_ALG_AES_192:; + return EVP_aes_192_ccm(); + case HCF_ALG_AES_256: + return EVP_aes_256_ccm(); + default: + break; + } + return EVP_aes_128_ccm(); +} + +static const EVP_CIPHER *CipherGcmType(HCF_ALG_PARA_VALUE value) +{ + switch (value) { + case HCF_ALG_AES_128: + return EVP_aes_128_gcm(); + case HCF_ALG_AES_192:; + return EVP_aes_192_gcm(); + case HCF_ALG_AES_256: + return EVP_aes_256_gcm(); + default: + break; + } + return EVP_aes_128_gcm(); +} + +static const EVP_CIPHER *GetCipherType(HcfCipherAesGeneratorSpiOpensslImpl *impl) +{ + switch (impl->attr.mode) { + case HCF_ALG_MODE_ECB: + return CipherEcbType(impl->attr.keySize); + case HCF_ALG_MODE_CBC: + return CipherCbcType(impl->attr.keySize); + case HCF_ALG_MODE_CTR: + return CipherCtrType(impl->attr.keySize); + case HCF_ALG_MODE_OFB: + return CipherOfbType(impl->attr.keySize); + case HCF_ALG_MODE_CFB: + return CipherCfbType(impl->attr.keySize); + case HCF_ALG_MODE_CFB1: + return CipherCfb1Type(impl->attr.keySize); + case HCF_ALG_MODE_CFB8: + return CipherCfb8Type(impl->attr.keySize); + case HCF_ALG_MODE_CFB128: + return CipherCfb128Type(impl->attr.keySize); + case HCF_ALG_MODE_CCM: + return CipherCcmType(impl->attr.keySize); + case HCF_ALG_MODE_GCM: + return CipherGcmType(impl->attr.keySize); + default: + break; + } + return DefautCiherType(); +} + +static bool IsGcmParamsValid(HcfGcmParamsSpec *params) +{ + if (params == NULL) { + LOGE("params is null!"); + return false; + } + if ((params->aad.data == NULL) || (params->aad.len == 0) || (params->aad.len > MAX_AAD_LEN)) { + LOGE("aad is invalid!"); + return false; + } + if ((params->iv.data == NULL) || (params->iv.len != GCM_IV_LEN)) { + LOGE("iv is invalid!"); + return false; + } + if ((params->tag.data == NULL) || (params->tag.len == 0)) { + LOGE("tag is invalid!"); + return false; + } + return true; +} + +static bool IsCcmParamsValid(HcfCcmParamsSpec *params) +{ + if (params == NULL) { + LOGE("params is null!"); + return false; + } + if ((params->aad.data == NULL) || (params->aad.len == 0) || (params->aad.len > MAX_AAD_LEN)) { + LOGE("aad is invalid!"); + return false; + } + if ((params->iv.data == NULL) || (params->iv.len < CCM_IV_MIN_LEN) || (params->iv.len > CCM_IV_MAX_LEN)) { + LOGE("iv is invalid!"); + return false; + } + if ((params->tag.data == NULL) || (params->tag.len == 0)) { + LOGE("tag is invalid!"); + return false; + } + return true; +} + +static HcfResult InitAadAndTagFromGcmParams(enum HcfCryptoMode opMode, HcfGcmParamsSpec *params, CipherData *data) +{ + if (!IsGcmParamsValid(params)) { + LOGE("gcm params is invalid!"); + return HCF_INVALID_PARAMS; + } + + data->aad = (uint8_t *)HcfMalloc(params->aad.len, 0); + if (data->aad == NULL) { + LOGE("aad malloc failed!"); + return HCF_ERR_MALLOC; + } + (void)memcpy_s(data->aad, params->aad.len, params->aad.data, params->aad.len); + data->aadLen = params->aad.len; + data->aead = true; + data->tagLen = params->tag.len; + if (opMode == ENCRYPT_MODE) { + return HCF_SUCCESS; + } + data->tag = (uint8_t *)HcfMalloc(params->tag.len, 0); + if (data->tag == NULL) { + HcfFree(data->aad); + data->aad = NULL; + LOGE("tag malloc failed!"); + return HCF_ERR_MALLOC; + } + (void)memcpy_s(data->tag, params->tag.len, params->tag.data, params->tag.len); + return HCF_SUCCESS; +} + +static HcfResult InitAadAndTagFromCcmParams(enum HcfCryptoMode opMode, HcfCcmParamsSpec *params, CipherData *data) +{ + if (!IsCcmParamsValid(params)) { + LOGE("gcm params is invalid!"); + return HCF_INVALID_PARAMS; + } + + data->aad = (uint8_t *)HcfMalloc(params->aad.len, 0); + if (data->aad == NULL) { + LOGE("aad malloc failed!"); + return HCF_ERR_MALLOC; + } + (void)memcpy_s(data->aad, params->aad.len, params->aad.data, params->aad.len); + data->aadLen = params->aad.len; + data->aead = true; + data->tagLen = params->tag.len; + if (opMode == ENCRYPT_MODE) { + return HCF_SUCCESS; + } + data->tag = (uint8_t *)HcfMalloc(params->tag.len, 0); + if (data->tag == NULL) { + HcfFree(data->aad); + data->aad = NULL; + LOGE("tag malloc failed!"); + return HCF_ERR_MALLOC; + } + (void)memcpy_s(data->tag, params->tag.len, params->tag.data, params->tag.len); + return HCF_SUCCESS; +} + +static HcfResult InitCipherData(OH_HCF_CipherGeneratorSpi *self, enum HcfCryptoMode opMode, + HcfParamsSpec *params, CipherData **cipherData) +{ + HcfResult ret = HCF_ERR_MALLOC; + *cipherData = (CipherData *)HcfMalloc(sizeof(CipherData), 0); + if (*cipherData == NULL) { + LOGE("malloc is failed!"); + return ret; + } + HcfCipherAesGeneratorSpiOpensslImpl *cipherImpl = (HcfCipherAesGeneratorSpiOpensslImpl *)self; + HCF_ALG_PARA_VALUE mode = cipherImpl->attr.mode; + + (*cipherData)->enc = opMode; + (*cipherData)->ctx = EVP_CIPHER_CTX_new(); + if ((*cipherData)->ctx == NULL) { + HcfPrintOpensslError(); + LOGE("Failed to allocate ctx memroy!"); + goto clearup; + } + + ret = HCF_SUCCESS; + if (mode == HCF_ALG_MODE_GCM) { + ret = InitAadAndTagFromGcmParams(opMode, (HcfGcmParamsSpec *)params, *cipherData); + } else if (mode == HCF_ALG_MODE_CCM) { + ret = InitAadAndTagFromCcmParams(opMode, (HcfCcmParamsSpec *)params, *cipherData); + } + if (ret != HCF_SUCCESS) { + LOGE("gcm or ccm init failed!"); + goto clearup; + } + return ret; +clearup: + FreeCipherData(cipherData); + return ret; +} + +static HcfResult EngineCipherInit(OH_HCF_CipherGeneratorSpi *self, enum HcfCryptoMode opMode, + HcfKey *key, HcfParamsSpec *params) +{ + if ((self == NULL) || (key == NULL)) { /* params maybe is null */ + LOGE("Invalid input parameter!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((const HcfObjectBase *)self, GetAesGeneratorClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((const HcfObjectBase *)key, OPENSSL_SYM_KEY_CLASS)) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + HcfCipherAesGeneratorSpiOpensslImpl *cipherImpl = (HcfCipherAesGeneratorSpiOpensslImpl *)self; + SymKeyImpl *keyImpl = (SymKeyImpl *)key; + int enc = (opMode == ENCRYPT_MODE) ? 1 : 0; + + if (InitCipherData(self, opMode, params, &(cipherImpl->cipherData)) != HCF_SUCCESS) { + LOGE("InitCipherData failed!"); + return HCF_INVALID_PARAMS; + } + CipherData *data = cipherImpl->cipherData; + HcfResult ret = HCF_ERR_CRYPTO_OPERATION; + if (EVP_CipherInit(data->ctx, GetCipherType(cipherImpl), keyImpl->keyMaterial.data, GetIv(params), enc) != + HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + LOGE("EVP_CipherInit failed!"); + goto clearup; + } + int32_t padding = (cipherImpl->attr.paddingMode == HCF_ALG_NOPADDING) ? 0 : EVP_PADDING_PKCS7; + + if (EVP_CIPHER_CTX_set_padding(data->ctx, padding) != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + LOGE("set padding failed!"); + goto clearup; + } + + if (opMode == ENCRYPT_MODE || cipherImpl->attr.mode != HCF_ALG_MODE_CCM) { + return HCF_SUCCESS; + } + /* ccm decrypt need set tag */ + if (EVP_CIPHER_CTX_ctrl(data->ctx, EVP_CTRL_AEAD_SET_TAG, GetCcmTagLen(params), GetCcmTag(params)) != + HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + LOGE("set AuthTag failed!"); + goto clearup; + } + return HCF_SUCCESS; +clearup: + FreeCipherData(&(cipherImpl->cipherData)); + return ret; +} + +static HcfResult CommonUpdate(CipherData *data, HcfBlob *input, HcfBlob *output) +{ + int32_t ret = EVP_CipherUpdate(data->ctx, output->data, (int *)&output->len, + input->data, input->len); + if (ret != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + LOGE("cipher update failed!"); + return HCF_ERR_CRYPTO_OPERATION; + } + return HCF_SUCCESS; +} + +static HcfResult AeadUpdate(CipherData *data, HCF_ALG_PARA_VALUE mode, HcfBlob *input, HcfBlob *output) +{ + if (mode == HCF_ALG_MODE_CCM) { + if (EVP_CipherUpdate(data->ctx, NULL, (int *)&output->len, NULL, input->len) != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + LOGE("ccm cipher update failed!"); + return HCF_ERR_CRYPTO_OPERATION; + } + } + + int32_t ret = EVP_CipherUpdate(data->ctx, NULL, (int *)&output->len, data->aad, data->aadLen); + if (ret != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + LOGE("aad cipher update failed!"); + return HCF_ERR_CRYPTO_OPERATION; + } + ret = EVP_CipherUpdate(data->ctx, output->data, (int *)&output->len, input->data, input->len); + if (ret != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + LOGE("gcm cipher update failed!"); + return HCF_ERR_CRYPTO_OPERATION; + } + return HCF_SUCCESS; +} + +static HcfResult AllocateOutput(HcfBlob *input, HcfBlob *output, bool *isUpdateInput) +{ + uint32_t outLen = 0; + if (IsBlobValid(input)) { + outLen += input->len; + *isUpdateInput = true; + } + outLen += AES_BLOCK_SIZE; + if (outLen == 0) { + LOGE("output size is invaild!"); + return HCF_INVALID_PARAMS; + } + output->data = (uint8_t *)HcfMalloc(outLen, 0); + if (output->data == NULL) { + LOGE("malloc output failed!"); + return HCF_ERR_MALLOC; + } + output->len = outLen; + return HCF_SUCCESS; +} + +static HcfResult EngineUpdate(OH_HCF_CipherGeneratorSpi *self, HcfBlob *input, HcfBlob *output) +{ + if ((self == NULL) || (input == NULL) || (output == NULL)) { + LOGE("Invalid input parameter!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((const HcfObjectBase *)self, GetAesGeneratorClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + + HcfCipherAesGeneratorSpiOpensslImpl *cipherImpl = (HcfCipherAesGeneratorSpiOpensslImpl *)self; + CipherData *data = cipherImpl->cipherData; + if (data == NULL) { + LOGE("cipherData is null!"); + return HCF_INVALID_PARAMS; + } + bool isUpdateInput = false; + HcfResult ret = AllocateOutput(input, output, &isUpdateInput); + if (ret != HCF_SUCCESS) { + LOGE("AllocateOutput failed!"); + return ret; + } + + if (!data->aead) { + ret = CommonUpdate(data, input, output); + } else { + ret = AeadUpdate(data, cipherImpl->attr.mode, input, output); + } + if (ret != HCF_SUCCESS) { + HcfBlobDataFree(output); + FreeCipherData(&(cipherImpl->cipherData)); + } + data->aead = false; + return ret; +} + +static HcfResult CommonDoFinal(CipherData *data, HcfBlob *input, HcfBlob *output) +{ + int32_t ret; + uint32_t len = 0; + bool isUpdateInput = false; + HcfResult res = AllocateOutput(input, output, &isUpdateInput); + if (res != HCF_SUCCESS) { + LOGE("AllocateOutput failed!"); + return res; + } + if (isUpdateInput) { + ret = EVP_CipherUpdate(data->ctx, output->data, (int32_t *)&len, input->data, input->len); + if (ret != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + LOGE("EVP_CipherUpdate failed!"); + return HCF_ERR_CRYPTO_OPERATION; + } + } + ret = EVP_CipherFinal_ex(data->ctx, output->data + len, (int *)&output->len); + if (ret != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + LOGE("EVP_CipherFinal_ex failed!"); + return HCF_ERR_CRYPTO_OPERATION; + } + output->len += len; + return HCF_SUCCESS; +} + +static HcfResult AllocateCcmOutput(CipherData *data, HcfBlob *input, HcfBlob *output, bool *isUpdateInput) +{ + uint32_t outLen = 0; + if (IsBlobValid(input)) { + outLen += input->len; + *isUpdateInput = true; + } + int32_t authTagLen = data->enc == ENCRYPT_MODE ? CCM_TAG_SIZE : 0; + outLen += authTagLen + AES_BLOCK_SIZE; + if (outLen == 0) { + LOGE("output size is invaild!"); + return HCF_INVALID_PARAMS; + } + output->data = (uint8_t *)HcfMalloc(outLen, 0); + if (output->data == NULL) { + LOGE("malloc output failed!"); + return HCF_ERR_MALLOC; + } + output->len = outLen; + return HCF_SUCCESS; +} + +static HcfResult CcmDecryptDoFinal(HcfBlob *output, bool isUpdateInput) +{ + if (isUpdateInput) { /* DecryptFinal this does not occur in CCM mode */ + return HCF_SUCCESS; + } + if (output->data != NULL) { + HcfBlobDataFree(output); + } + return HCF_SUCCESS; +} + +static HcfResult CcmEncryptDoFinal(CipherData *data, HcfBlob *output, uint32_t len) +{ + int32_t ret = EVP_CIPHER_CTX_ctrl(data->ctx, EVP_CTRL_AEAD_GET_TAG, data->tagLen, output->data + len); + if (ret != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + LOGE("get AuthTag failed!"); + return HCF_ERR_CRYPTO_OPERATION; + } + output->len = data->tagLen + len; + return HCF_SUCCESS; +} + +static HcfResult CcmDoFinal(CipherData *data, HcfBlob *input, HcfBlob *output) +{ + bool isUpdateInput = false; + uint32_t len = 0; + HcfResult res = AllocateCcmOutput(data, input, output, &isUpdateInput); + if (res != HCF_SUCCESS) { + LOGE("AllocateCcmOutput failed!"); + return res; + } + if (isUpdateInput) { + HcfResult result = AeadUpdate(data, HCF_ALG_MODE_CCM, input, output); + if (result != HCF_SUCCESS) { + LOGE("AeadUpdate failed!"); + return result; + } + len = output->len; + } + if (data->enc == ENCRYPT_MODE) { + return CcmEncryptDoFinal(data, output, len); + } else if (data->enc == DECRYPT_MODE) { + return CcmDecryptDoFinal(output, isUpdateInput); + } else { + return HCF_INVALID_PARAMS; + } +} + +static HcfResult GcmDecryptDoFinal(CipherData *data, HcfBlob *input, HcfBlob *output, uint32_t len) +{ + if (data->tag == NULL) { + LOGE("gcm decrypt has not AuthTag!"); + return HCF_INVALID_PARAMS; + } + int32_t ret = EVP_CIPHER_CTX_ctrl(data->ctx, EVP_CTRL_AEAD_SET_TAG, data->tagLen, (void *)data->tag); + if (ret != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + LOGE("gcm decrypt set AuthTag failed!"); + return HCF_ERR_CRYPTO_OPERATION; + } + ret = EVP_CipherFinal_ex(data->ctx, output->data + len, (int *)&output->len); + if (ret != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + LOGE("EVP_CipherFinal_ex failed!"); + return HCF_ERR_CRYPTO_OPERATION; + } + output->len = output->len + len; + return HCF_SUCCESS; +} + +static HcfResult GcmEncryptDoFinal(CipherData *data, HcfBlob *input, HcfBlob *output, uint32_t len) +{ + int32_t ret = EVP_CipherFinal_ex(data->ctx, output->data + len, (int *)&output->len); + if (ret != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + LOGE("EVP_CipherFinal_ex failed!"); + return HCF_ERR_CRYPTO_OPERATION; + } + output->len += len; + ret = EVP_CIPHER_CTX_ctrl(data->ctx, EVP_CTRL_AEAD_GET_TAG, data->tagLen, + output->data + output->len); + if (ret != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + LOGE("get AuthTag failed!"); + return HCF_ERR_CRYPTO_OPERATION; + } + output->len += data->tagLen; + return HCF_SUCCESS; +} + +static HcfResult AllocateGcmOutput(CipherData *data, HcfBlob *input, HcfBlob *output, bool *isUpdateInput) +{ + uint32_t outLen = 0; + if (IsBlobValid(input)) { + outLen += input->len; + *isUpdateInput = true; + } + int32_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!"); + return HCF_INVALID_PARAMS; + } + output->data = (uint8_t *)HcfMalloc(outLen, 0); + if (output->data == NULL) { + LOGE("malloc output failed!"); + return HCF_ERR_MALLOC; + } + output->len = outLen; + return HCF_SUCCESS; +} + +static HcfResult GcmDoFinal(CipherData *data, HcfBlob *input, HcfBlob *output) +{ + uint32_t len = 0; + bool isUpdateInput = false; + HcfResult res = AllocateGcmOutput(data, input, output, &isUpdateInput); + if (res != HCF_SUCCESS) { + LOGE("AllocateGcmOutput failed!"); + return res; + } + + if (isUpdateInput) { + HcfResult result = AeadUpdate(data, HCF_ALG_MODE_GCM, input, output); + if (result != HCF_SUCCESS) { + LOGE("AeadUpdate failed!"); + return result; + } + len = output->len; + } + if (data->enc == ENCRYPT_MODE) { + return GcmEncryptDoFinal(data, input, output, len); + } else if (data->enc == DECRYPT_MODE) { + return GcmDecryptDoFinal(data, input, output, len); + } else { + return HCF_INVALID_PARAMS; + } +} + +static HcfResult EngineDoFinal(OH_HCF_CipherGeneratorSpi *self, HcfBlob *input, HcfBlob *output) +{ + if ((self == NULL) || (output == NULL)) { /* input maybe is null */ + LOGE("Invalid input parameter!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((const HcfObjectBase *)self, GetAesGeneratorClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + HcfResult ret = HCF_ERR_CRYPTO_OPERATION; + HcfCipherAesGeneratorSpiOpensslImpl *cipherImpl = (HcfCipherAesGeneratorSpiOpensslImpl *)self; + CipherData *data = cipherImpl->cipherData; + HCF_ALG_PARA_VALUE mode = cipherImpl->attr.mode; + if (data == NULL) { + LOGE("cipherData is null!"); + return HCF_INVALID_PARAMS; + } + + if (mode == HCF_ALG_MODE_CCM) { + ret = CcmDoFinal(data, input, output); + } else if (mode == HCF_ALG_MODE_GCM) { + ret = GcmDoFinal(data, input, output); + } else { /* only ECB CBC CTR CFB OFB support */ + ret = CommonDoFinal(data, input, output); + } + + FreeCipherData(&(cipherImpl->cipherData)); + if (ret != HCF_SUCCESS) { + HcfBlobDataFree(output); + } + return ret; +} + +static void EngineAesGeneratorDestroy(HcfObjectBase *self) +{ + if (self == NULL) { + return; + } + if (!IsClassMatch(self, GetAesGeneratorClass())) { + LOGE("Class is not match."); + return; + } + + HcfCipherAesGeneratorSpiOpensslImpl *impl = (HcfCipherAesGeneratorSpiOpensslImpl *)self; + FreeCipherData(&(impl->cipherData)); + HcfFree(impl); +} + +HcfResult HcfCipherAesGeneratorSpiCreate(CipherAttr *attr, OH_HCF_CipherGeneratorSpi **generator) +{ + if ((attr == NULL) || (generator == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + HcfCipherAesGeneratorSpiOpensslImpl *returnImpl = (HcfCipherAesGeneratorSpiOpensslImpl *)HcfMalloc( + sizeof(HcfCipherAesGeneratorSpiOpensslImpl), 0); + if (returnImpl == NULL) { + LOGE("Failed to allocate returnImpl memroy!"); + return HCF_ERR_MALLOC; + } + (void)memcpy_s(&returnImpl->attr, sizeof(CipherAttr), attr, sizeof(CipherAttr)); + returnImpl->base.init = EngineCipherInit; + returnImpl->base.update = EngineUpdate; + returnImpl->base.doFinal = EngineDoFinal; + returnImpl->base.base.destroy = EngineAesGeneratorDestroy; + returnImpl->base.base.getClass = GetAesGeneratorClass; + + *generator = (OH_HCF_CipherGeneratorSpi *)returnImpl; + return HCF_SUCCESS; +} diff --git a/plugin/openssl_plugin/crypto_operation/hmac/inc/mac_openssl.h b/plugin/openssl_plugin/crypto_operation/hmac/inc/mac_openssl.h new file mode 100644 index 0000000..98f15eb --- /dev/null +++ b/plugin/openssl_plugin/crypto_operation/hmac/inc/mac_openssl.h @@ -0,0 +1,26 @@ +/* + * Copyright (C) 2022 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_spi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +HcfResult OpensslMacSpiCreate(const char *opensslAlgoName, HcfMacSpi **spiObj); + +#ifdef __cplusplus +} +#endif diff --git a/plugin/openssl_plugin/crypto_operation/hmac/src/mac_openssl.c b/plugin/openssl_plugin/crypto_operation/hmac/src/mac_openssl.c new file mode 100644 index 0000000..00abbbf --- /dev/null +++ b/plugin/openssl_plugin/crypto_operation/hmac/src/mac_openssl.c @@ -0,0 +1,193 @@ +/* + * Copyright (C) 2022 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_openssl.h" + +#include "sym_common_defines.h" +#include "openssl_common.h" +#include "securec.h" +#include "log.h" +#include "memory.h" +#include "config.h" +#include "utils.h" + +#include + +typedef struct { + HcfMacSpi base; + + HMAC_CTX *ctx; + + char opensslAlgoName[HCF_MAX_ALGO_NAME_LEN]; +} HcfMacSpiImpl; + +static const char *OpensslGetMacClass(void) +{ + return "OpensslMac"; +} + +static HMAC_CTX *OpensslGetMacCtx(HcfMacSpi *self) +{ + if (!IsClassMatch((HcfObjectBase *)self, OpensslGetMacClass())) { + LOGE("Class is not match."); + return NULL; + } + return ((HcfMacSpiImpl *)self)->ctx; +} + +static const EVP_MD *OpensslGetMacAlgoFromString(const char *mdName) +{ + if (strcmp(mdName, "SHA1") == 0) { + return EVP_sha1(); + } else if (strcmp(mdName, "SHA224") == 0) { + return EVP_sha224(); + } else if (strcmp(mdName, "SHA256") == 0) { + return EVP_sha256(); + } else if (strcmp(mdName, "SHA384") == 0) { + return EVP_sha384(); + } else if (strcmp(mdName, "SHA512") == 0) { + return EVP_sha512(); + } + return NULL; +} + +static HcfResult OpensslEngineInitMac(HcfMacSpi *self, const HcfSymKey *key) +{ + if (OpensslGetMacCtx(self) == NULL) { + LOGE("The CTX is NULL!"); + return HCF_ERR_CRYPTO_OPERATION; + } + if (!IsClassMatch((const HcfObjectBase *)key, OPENSSL_SYM_KEY_CLASS)) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, OpensslGetMacClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + HcfBlob keyBlob = ((SymKeyImpl *)key)->keyMaterial; + if (!IsBlobValid(&keyBlob)) { + LOGE("Invalid keyMaterial"); + return HCF_INVALID_PARAMS; + } + const EVP_MD *mdfunc = OpensslGetMacAlgoFromString(((HcfMacSpiImpl *)self)->opensslAlgoName); + int32_t ret = HMAC_Init_ex(OpensslGetMacCtx(self), keyBlob.data, keyBlob.len, mdfunc, NULL); + if (ret != HCF_OPENSSL_SUCCESS) { + LOGE("HMAC_Init_ex return error!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + return HCF_SUCCESS; +} + +static HcfResult OpensslEngineUpdateMac(HcfMacSpi *self, HcfBlob *input) +{ + if (OpensslGetMacCtx(self) == NULL) { + LOGE("The CTX is NULL!"); + return HCF_ERR_CRYPTO_OPERATION; + } + if (HMAC_Update(OpensslGetMacCtx(self), input->data, input->len) != HCF_OPENSSL_SUCCESS) { + LOGE("HMAC_Update return error!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + return HCF_SUCCESS; +} + +static HcfResult OpensslEngineDoFinalMac(HcfMacSpi *self, HcfBlob *output) +{ + if (OpensslGetMacCtx(self) == NULL) { + LOGE("The CTX is NULL!"); + return HCF_ERR_CRYPTO_OPERATION; + } + unsigned char outputBuf[EVP_MAX_MD_SIZE]; + uint32_t outputLen; + int32_t ret = HMAC_Final(OpensslGetMacCtx(self), outputBuf, &outputLen); + if (ret != HCF_OPENSSL_SUCCESS) { + LOGE("HMAC_Final return error!"); + HcfPrintOpensslError(); + 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; + } + if (memcpy_s(output->data, outputLen, outputBuf, outputLen) != EOK) { + LOGE("memcpy error!"); + HcfFree(output->data); + output->data = NULL; + return HCF_ERR_COPY; + } + output->len = outputLen; + return HCF_SUCCESS; +} + +static uint32_t OpensslEngineGetMacLength(HcfMacSpi *self) +{ + if (OpensslGetMacCtx(self) == NULL) { + LOGE("The CTX is NULL!"); + return HCF_ERR_CRYPTO_OPERATION; + } + return HMAC_size(OpensslGetMacCtx(self)); +} + +static void OpensslDestroyMac(HcfObjectBase *self) +{ + if (self == NULL) { + LOGE("Self ptr is NULL"); + return; + } + if (!IsClassMatch(self, OpensslGetMacClass())) { + LOGE("Class is not match."); + return; + } + if (OpensslGetMacCtx((HcfMacSpi *)self) != NULL) { + HMAC_CTX_free(OpensslGetMacCtx((HcfMacSpi *)self)); + } + HcfFree(self); +} + +HcfResult OpensslMacSpiCreate(const char *opensslAlgoName, HcfMacSpi **spiObj) +{ + if (spiObj == NULL) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + HcfMacSpiImpl *returnSpiImpl = (HcfMacSpiImpl *)HcfMalloc(sizeof(HcfMacSpiImpl), 0); + if (returnSpiImpl == NULL) { + LOGE("Failed to allocate returnImpl memory!"); + return HCF_ERR_MALLOC; + } + if (strcpy_s(returnSpiImpl->opensslAlgoName, HCF_MAX_ALGO_NAME_LEN, opensslAlgoName) != EOK) { + LOGE("Failed to copy algoName!"); + HcfFree(returnSpiImpl); + return HCF_ERR_COPY; + } + returnSpiImpl->ctx = HMAC_CTX_new(); + if (returnSpiImpl->ctx == NULL) { + LOGE("Failed to create ctx!"); + HcfFree(returnSpiImpl); + return HCF_ERR_CRYPTO_OPERATION; + } + returnSpiImpl->base.base.getClass = OpensslGetMacClass; + returnSpiImpl->base.base.destroy = OpensslDestroyMac; + returnSpiImpl->base.engineInitMac = OpensslEngineInitMac; + returnSpiImpl->base.engineUpdateMac = OpensslEngineUpdateMac; + returnSpiImpl->base.engineDoFinalMac = OpensslEngineDoFinalMac; + returnSpiImpl->base.engineGetMacLength = OpensslEngineGetMacLength; + *spiObj = (HcfMacSpi *)returnSpiImpl; + return HCF_SUCCESS; +} \ No newline at end of file diff --git a/plugin/openssl_plugin/crypto_operation/key_agreement/inc/ecdh_openssl.h b/plugin/openssl_plugin/crypto_operation/key_agreement/inc/ecdh_openssl.h new file mode 100644 index 0000000..8729e12 --- /dev/null +++ b/plugin/openssl_plugin/crypto_operation/key_agreement/inc/ecdh_openssl.h @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2022 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_ECDH_OPENSSL_H +#define HCF_ECDH_OPENSSL_H + +#include "key_agreement_spi.h" +#include "params_parser.h" +#include "result.h" + +#ifdef __cplusplus +extern "C" { +#endif + +HcfResult HcfKeyAgreementSpiEcdhCreate(HcfKeyAgreementParams *params, HcfKeyAgreementSpi **returnObj); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/plugin/openssl_plugin/crypto_operation/key_agreement/src/ecdh_openssl.c b/plugin/openssl_plugin/crypto_operation/key_agreement/src/ecdh_openssl.c new file mode 100644 index 0000000..de061ed --- /dev/null +++ b/plugin/openssl_plugin/crypto_operation/key_agreement/src/ecdh_openssl.c @@ -0,0 +1,209 @@ +/* + * Copyright (C) 2022 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 "ecdh_openssl.h" + +#include +#include + +#include "algorithm_parameter.h" +#include "openssl_class.h" +#include "openssl_common.h" +#include "log.h" +#include "memory.h" +#include "utils.h" + +typedef struct { + HcfKeyAgreementSpi base; + + int32_t curveId; +} HcfKeyAgreementSpiEcdhOpensslImpl; + +static EVP_PKEY *NewPKeyByEccPubKey(int32_t curveId, HcfOpensslEccPubKey *publicKey) +{ + EC_KEY *ecKey = EC_KEY_new_by_curve_name(curveId); + if (ecKey == NULL) { + HcfPrintOpensslError(); + return NULL; + } + if (EC_KEY_set_public_key(ecKey, (publicKey->pk)) != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + EC_KEY_free(ecKey); + return NULL; + } + EVP_PKEY *pKey = EVP_PKEY_new(); + if (pKey == NULL) { + HcfPrintOpensslError(); + EC_KEY_free(ecKey); + return NULL; + } + if (EVP_PKEY_assign_EC_KEY(pKey, ecKey) != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + EVP_PKEY_free(pKey); + EC_KEY_free(ecKey); + return NULL; + } + return pKey; +} + +static EVP_PKEY *NewPKeyByEccPriKey(int32_t curveId, HcfOpensslEccPriKey *privateKey) +{ + EC_KEY *ecKey = EC_KEY_new_by_curve_name(curveId); + if (ecKey == NULL) { + HcfPrintOpensslError(); + return NULL; + } + if (EC_KEY_set_private_key(ecKey, (privateKey->sk)) != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + EC_KEY_free(ecKey); + return NULL; + } + EVP_PKEY *pKey = EVP_PKEY_new(); + if (pKey == NULL) { + HcfPrintOpensslError(); + EC_KEY_free(ecKey); + return NULL; + } + if (EVP_PKEY_assign_EC_KEY(pKey, ecKey) != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + EVP_PKEY_free(pKey); + EC_KEY_free(ecKey); + return NULL; + } + return pKey; +} + +static HcfResult EcdhDerive(EVP_PKEY *priPKey, EVP_PKEY *pubPKey, HcfBlob *returnSecret) +{ + EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new(priPKey, NULL); + if (ctx == NULL) { + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + if (EVP_PKEY_derive_init(ctx) != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + EVP_PKEY_CTX_free(ctx); + return HCF_ERR_CRYPTO_OPERATION; + } + if (EVP_PKEY_derive_set_peer(ctx, pubPKey) != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + EVP_PKEY_CTX_free(ctx); + return HCF_ERR_CRYPTO_OPERATION; + } + size_t maxLen; + if (EVP_PKEY_derive(ctx, NULL, &maxLen) != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + EVP_PKEY_CTX_free(ctx); + return HCF_ERR_CRYPTO_OPERATION; + } + uint8_t *secretData = (uint8_t *)HcfMalloc(maxLen, 0); + if (secretData == NULL) { + LOGE("Failed to allocate secretData memory!"); + EVP_PKEY_CTX_free(ctx); + return HCF_ERR_MALLOC; + } + size_t actualLen = maxLen; + if (EVP_PKEY_derive(ctx, secretData, &actualLen) != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + EVP_PKEY_CTX_free(ctx); + HcfFree(secretData); + return HCF_ERR_CRYPTO_OPERATION; + } + EVP_PKEY_CTX_free(ctx); + if (actualLen > maxLen) { + LOGE("signature data too long."); + HcfFree(secretData); + return HCF_ERR_CRYPTO_OPERATION; + } + + returnSecret->data = secretData; + returnSecret->len = (uint32_t)actualLen; + return HCF_SUCCESS; +} + +// export interfaces +static const char *GetEcdhClass(void) +{ + return "HcfKeyAgreement.HcfKeyAgreementSpiEcdhOpensslImpl"; +} + +static void DestroyEcdh(HcfObjectBase *self) +{ + if (self == NULL) { + return; + } + if (!IsClassMatch(self, GetEcdhClass())) { + return; + } + HcfFree(self); +} + +static HcfResult EngineGenerateSecret(HcfKeyAgreementSpi *self, HcfPriKey *priKey, + HcfPubKey *pubKey, HcfBlob *returnSecret) +{ + LOGI("start ..."); + if ((self == NULL) || (priKey == NULL) || (pubKey == NULL) || (returnSecret == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if ((!IsClassMatch((HcfObjectBase *)self, GetEcdhClass())) || + (!IsClassMatch((HcfObjectBase *)priKey, HCF_OPENSSL_ECC_PRI_KEY_CLASS)) || + (!IsClassMatch((HcfObjectBase *)pubKey, HCF_OPENSSL_ECC_PUB_KEY_CLASS))) { + return HCF_INVALID_PARAMS; + } + + HcfKeyAgreementSpiEcdhOpensslImpl *impl = (HcfKeyAgreementSpiEcdhOpensslImpl *)self; + EVP_PKEY *priPKey = NewPKeyByEccPriKey(impl->curveId, (HcfOpensslEccPriKey *)priKey); + if (priPKey == NULL) { + return HCF_ERR_CRYPTO_OPERATION; + } + EVP_PKEY *pubPKey = NewPKeyByEccPubKey(impl->curveId, (HcfOpensslEccPubKey *)pubKey); + if (pubPKey == NULL) { + EVP_PKEY_free(priPKey); + return HCF_ERR_CRYPTO_OPERATION; + } + + int32_t res = EcdhDerive(priPKey, pubPKey, returnSecret); + EVP_PKEY_free(priPKey); + EVP_PKEY_free(pubPKey); + LOGI("end ..."); + return res; +} + +HcfResult HcfKeyAgreementSpiEcdhCreate(HcfKeyAgreementParams *params, HcfKeyAgreementSpi **returnObj) +{ + if ((params == NULL) || (returnObj == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + int32_t curveId; + if (GetOpensslCurveId(params->keyLen, &curveId) != HCF_SUCCESS) { + return HCF_INVALID_PARAMS; + } + + HcfKeyAgreementSpiEcdhOpensslImpl *returnImpl = (HcfKeyAgreementSpiEcdhOpensslImpl *)HcfMalloc( + sizeof(HcfKeyAgreementSpiEcdhOpensslImpl), 0); + if (returnImpl == NULL) { + LOGE("Failed to allocate returnImpl memroy!"); + return HCF_ERR_MALLOC; + } + returnImpl->base.base.getClass = GetEcdhClass; + returnImpl->base.base.destroy = DestroyEcdh; + returnImpl->base.engineGenerateSecret = EngineGenerateSecret; + returnImpl->curveId = curveId; + + *returnObj = (HcfKeyAgreementSpi *)returnImpl; + return HCF_SUCCESS; +} diff --git a/plugin/openssl_plugin/crypto_operation/md/inc/md_openssl.h b/plugin/openssl_plugin/crypto_operation/md/inc/md_openssl.h new file mode 100644 index 0000000..705e9a7 --- /dev/null +++ b/plugin/openssl_plugin/crypto_operation/md/inc/md_openssl.h @@ -0,0 +1,26 @@ +/* + * Copyright (C) 2022 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_spi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +HcfResult OpensslMdSpiCreate(const char *opensslAlgoName, HcfMdSpi **spiObj); + +#ifdef __cplusplus +} +#endif diff --git a/plugin/openssl_plugin/crypto_operation/md/src/md_openssl.c b/plugin/openssl_plugin/crypto_operation/md/src/md_openssl.c new file mode 100644 index 0000000..c34c5ae --- /dev/null +++ b/plugin/openssl_plugin/crypto_operation/md/src/md_openssl.c @@ -0,0 +1,169 @@ +/* + * Copyright (C) 2022 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_openssl.h" + +#include "openssl_common.h" +#include "securec.h" +#include "log.h" +#include "memory.h" +#include "config.h" +#include "utils.h" + +#include + +typedef struct { + HcfMdSpi base; + + EVP_MD_CTX *ctx; + + char opensslAlgoName[HCF_MAX_ALGO_NAME_LEN]; +} OpensslMdSpiImpl; + +static const char *OpensslGetMdClass(void) +{ + return "OpensslMd"; +} + +static EVP_MD_CTX *OpensslGetMdCtx(HcfMdSpi *self) +{ + if (!IsClassMatch((HcfObjectBase *)self, OpensslGetMdClass())) { + LOGE("Class is not match."); + return NULL; + } + return ((OpensslMdSpiImpl *)self)->ctx; +} + +static const EVP_MD *OpensslGetMdAlgoFromString(const char *mdName) +{ + if (strcmp(mdName, "SHA1") == 0) { + return EVP_sha1(); + } else if (strcmp(mdName, "SHA224") == 0) { + return EVP_sha224(); + } else if (strcmp(mdName, "SHA256") == 0) { + return EVP_sha256(); + } else if (strcmp(mdName, "SHA384") == 0) { + return EVP_sha384(); + } else if (strcmp(mdName, "SHA512") == 0) { + return EVP_sha512(); + } else if (strcmp(mdName, "MD5") == 0) { + return EVP_md5(); + } + return NULL; +} + +static HcfResult OpensslEngineUpdateMd(HcfMdSpi *self, HcfBlob *input) +{ + if (OpensslGetMdCtx(self) == NULL) { + LOGE("The CTX is NULL!"); + return HCF_ERR_CRYPTO_OPERATION; + } + if (EVP_DigestUpdate(OpensslGetMdCtx(self), input->data, input->len) != HCF_OPENSSL_SUCCESS) { + LOGE("EVP_DigestUpdate return error!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + return HCF_SUCCESS; +} + +static HcfResult OpensslEngineDoFinalMd(HcfMdSpi *self, HcfBlob *output) +{ + EVP_MD_CTX *localCtx = OpensslGetMdCtx(self); + if (localCtx == NULL) { + LOGE("The CTX is NULL!"); + return HCF_ERR_CRYPTO_OPERATION; + } + unsigned char outputBuf[EVP_MAX_MD_SIZE]; + uint32_t outputLen; + int32_t ret = EVP_DigestFinal_ex(localCtx, outputBuf, &outputLen); + if (ret != HCF_OPENSSL_SUCCESS) { + LOGE("EVP_DigestFinal_ex return error!"); + HcfPrintOpensslError(); + 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; + } + if (memcpy_s(output->data, outputLen, outputBuf, outputLen) != EOK) { + LOGE("memcpy error!"); + HcfFree(output->data); + output->data = NULL; + return HCF_ERR_COPY; + } + output->len = outputLen; + return HCF_SUCCESS; +} + +static uint32_t OpensslEngineGetMdLength(HcfMdSpi *self) +{ + if (OpensslGetMdCtx(self) == NULL) { + LOGE("The CTX is NULL!"); + return 0; + } + uint32_t size = EVP_MD_CTX_size(OpensslGetMdCtx(self)); + return size; +} + +static void OpensslDestroyMd(HcfObjectBase *self) +{ + if (self == NULL) { + LOGE("Self ptr is NULL!"); + return; + } + if (!IsClassMatch(self, OpensslGetMdClass())) { + LOGE("Class is not match."); + return; + } + if (OpensslGetMdCtx((HcfMdSpi *)self) != NULL) { + EVP_MD_CTX_free(OpensslGetMdCtx((HcfMdSpi *)self)); + } + HcfFree(self); +} + +HcfResult OpensslMdSpiCreate(const char *opensslAlgoName, HcfMdSpi **spiObj) +{ + if (spiObj == 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!"); + return HCF_ERR_MALLOC; + } + returnSpiImpl->ctx = EVP_MD_CTX_new(); + if (returnSpiImpl->ctx == NULL) { + LOGE("Failed to create ctx!"); + HcfFree(returnSpiImpl); + return HCF_ERR_MALLOC; + } + const EVP_MD *mdfunc = OpensslGetMdAlgoFromString(opensslAlgoName); + int32_t ret = EVP_DigestInit_ex(returnSpiImpl->ctx, mdfunc, NULL); + if (ret != HCF_OPENSSL_SUCCESS) { + LOGE("Failed to init MD!"); + HcfFree(returnSpiImpl); + EVP_MD_CTX_free(returnSpiImpl->ctx); + return HCF_ERR_CRYPTO_OPERATION; + } + returnSpiImpl->base.base.getClass = OpensslGetMdClass; + returnSpiImpl->base.base.destroy = OpensslDestroyMd; + returnSpiImpl->base.engineUpdateMd = OpensslEngineUpdateMd; + returnSpiImpl->base.engineDoFinalMd = OpensslEngineDoFinalMd; + returnSpiImpl->base.engineGetMdLength = OpensslEngineGetMdLength; + *spiObj = (HcfMdSpi *)returnSpiImpl; + return HCF_SUCCESS; +} \ No newline at end of file diff --git a/plugin/openssl_plugin/crypto_operation/rsa/inc/cipher_rsa_openssl.h b/plugin/openssl_plugin/crypto_operation/rsa/inc/cipher_rsa_openssl.h new file mode 100644 index 0000000..731a5e5 --- /dev/null +++ b/plugin/openssl_plugin/crypto_operation/rsa/inc/cipher_rsa_openssl.h @@ -0,0 +1,27 @@ +/* + * Copyright (C) 2022 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_factory_spi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +HcfResult HcfCipherRsaCipherSpiCreate(CipherAttr *params, OH_HCF_CipherGeneratorSpi **generator); + + +#ifdef __cplusplus +} +#endif \ No newline at end of file diff --git a/plugin/openssl_plugin/crypto_operation/rsa/src/cipher_rsa_openssl.c b/plugin/openssl_plugin/crypto_operation/rsa/src/cipher_rsa_openssl.c new file mode 100644 index 0000000..69ab3e1 --- /dev/null +++ b/plugin/openssl_plugin/crypto_operation/rsa/src/cipher_rsa_openssl.c @@ -0,0 +1,355 @@ +/* + * Copyright (C) 2022 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_rsa_openssl.h" +#include "securec.h" +#include "openssl/rsa.h" +#include "rsa_openssl_common.h" +#include "log.h" +#include "memory.h" +#include "openssl_class.h" +#include "openssl_common.h" +#include "stdbool.h" +#include "string.h" +#include "utils.h" + +static const char *EngineGetClass(); + +typedef struct { + OH_HCF_CipherGeneratorSpi super; + + CipherAttr attr; + + InitFlag initFlag; + + EVP_PKEY_CTX *ctx; +} HcfCipherRsaGeneratorSpiImpl; + +static HcfResult CheckCipherInitParams(enum HcfCryptoMode opMode, HcfKey *key) +{ + switch (opMode) { + case ENCRYPT_MODE: + if (!IsClassMatch((HcfObjectBase *)key, OPENSSL_RSA_PUBKEY_CLASS)) { + LOGE("Class not match"); + return HCF_INVALID_PARAMS; + } + break; + case DECRYPT_MODE: + if (!IsClassMatch((HcfObjectBase *)key, OPENSSL_RSA_PRIKEY_CLASS)) { + LOGE("Class not match"); + return HCF_INVALID_PARAMS; + } + break; + default: + LOGE("Invalid opMode %u", opMode); + return HCF_INVALID_PARAMS; + } + + return HCF_SUCCESS; +} + + +static HcfResult DuplicateRsaFromKey(HcfKey *key, enum HcfCryptoMode opMode, RSA **dupRsa) +{ + HcfResult ret = HCF_SUCCESS; + if (opMode == ENCRYPT_MODE) { + ret = DuplicateRsa(((HcfOpensslRsaPubKey *)key)->pk, false, dupRsa); + if (ret != HCF_SUCCESS) { + LOGE("dup pub rsa fail."); + return ret; + } + } else if (opMode == DECRYPT_MODE) { + ret = DuplicateRsa(((HcfOpensslRsaPriKey *)key)->sk, true, dupRsa); + if (ret != HCF_SUCCESS) { + LOGE("dup pri rsa fail."); + return ret; + } + } else { + LOGE("OpMode not match."); + return HCF_INVALID_PARAMS; + } + return ret; +} + +static HcfResult InitEvpPkeyCtx(HcfCipherRsaGeneratorSpiImpl *impl, HcfKey *key, enum HcfCryptoMode opMode) +{ + RSA *rsa = NULL; + HcfResult ret = HCF_SUCCESS; + ret = DuplicateRsaFromKey(key, opMode, &rsa); + if (ret != HCF_SUCCESS) { + LOGE("DuplicateRsaFromKey fail."); + return ret; + } + EVP_PKEY *pkey = EVP_PKEY_new(); + if (key == NULL) { + LOGE("New EVP_PKEY fail."); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + + if (EVP_PKEY_assign_RSA(pkey, rsa) != HCF_OPENSSL_SUCCESS) { + LOGE("EVP_PKEY_assign_RSA fail"); + HcfPrintOpensslError(); + EVP_PKEY_free(pkey); + return HCF_ERR_CRYPTO_OPERATION; + } + impl->ctx = EVP_PKEY_CTX_new(pkey, NULL); + if (impl->ctx == NULL) { + LOGE("EVP_PKEY_CTX_new fail"); + HcfPrintOpensslError(); + EVP_PKEY_free(pkey); + return HCF_ERR_CRYPTO_OPERATION; + } + int32_t sslRet = HCF_OPENSSL_SUCCESS; + if (opMode == ENCRYPT_MODE) { + sslRet = EVP_PKEY_encrypt_init(impl->ctx); + } else { + sslRet = EVP_PKEY_decrypt_init(impl->ctx); + } + if (sslRet != HCF_OPENSSL_SUCCESS) { + LOGE("Init EVP_PKEY fail"); + HcfPrintOpensslError(); + EVP_PKEY_free(pkey); + EVP_PKEY_CTX_free(impl->ctx); + return HCF_ERR_CRYPTO_OPERATION; + } + EVP_PKEY_free(pkey); + return HCF_SUCCESS; +} + +static HcfResult SetDetailParams(HcfCipherRsaGeneratorSpiImpl *impl) +{ + CipherAttr attr = impl->attr; + const EVP_MD *md = GetOpensslDigestAlg(attr.md); + if (md == NULL && attr.paddingMode == HCF_OPENSSL_RSA_PKCS1_OAEP_PADDING) { + LOGE("md is NULL."); + return HCF_INVALID_PARAMS; + } + const EVP_MD *mgf1md = GetOpensslDigestAlg(attr.mgf1md); + if (mgf1md == NULL && attr.paddingMode == HCF_OPENSSL_RSA_PKCS1_OAEP_PADDING) { + LOGE("mgf1md is NULL."); + return HCF_INVALID_PARAMS; + } + int32_t opensslPadding = 0; + if (GetOpensslPadding(attr.paddingMode, &opensslPadding) != HCF_SUCCESS) { + LOGE("Padding is dismatch."); + return HCF_INVALID_PARAMS; + } + if (EVP_PKEY_CTX_set_rsa_padding(impl->ctx, opensslPadding) != HCF_OPENSSL_SUCCESS) { + LOGE("Cipher set padding fail."); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + if (attr.paddingMode == HCF_OPENSSL_RSA_PKCS1_OAEP_PADDING) { + // set md and mgf1md + if (EVP_PKEY_CTX_set_rsa_oaep_md(impl->ctx, md) != HCF_OPENSSL_SUCCESS + || EVP_PKEY_CTX_set_rsa_mgf1_md(impl->ctx, mgf1md) != HCF_OPENSSL_SUCCESS) { + LOGE("Set md or mgf1md fail"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + } + return HCF_SUCCESS; +} + +static HcfResult EngineInit(OH_HCF_CipherGeneratorSpi *self, enum HcfCryptoMode opMode, + HcfKey *key, HcfParamsSpec *params) +{ + LOGI("EngineInit start"); + if (self == NULL || key == NULL) { + LOGE("Param is invalid."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, EngineGetClass())) { + LOGE("Class not match"); + return HCF_INVALID_PARAMS; + } + + HcfCipherRsaGeneratorSpiImpl *impl = (HcfCipherRsaGeneratorSpiImpl *)self; + if (impl->initFlag != UNINITIALIZED) { + LOGE("The cipher has been initialize, don't init again."); + return HCF_INVALID_PARAMS; + } + + // check opMode is matched with Key + if (CheckCipherInitParams(opMode, key) != HCF_SUCCESS) { + LOGE("OpMode dismatch with keyType."); + return HCF_INVALID_PARAMS; + } + impl->attr.mode = (int32_t)opMode; + if (InitEvpPkeyCtx(impl, key, opMode) != HCF_SUCCESS) { + LOGE("InitEvpPkeyCtx fail"); + return HCF_ERR_CRYPTO_OPERATION; + } + + if (SetDetailParams(impl) != HCF_SUCCESS) { + EVP_PKEY_CTX_free(impl->ctx); + LOGE("SetDetailParams fail."); + return HCF_ERR_CRYPTO_OPERATION; + } + impl->initFlag = INITIALIZED; + LOGI("EngineInit end"); + return HCF_SUCCESS; +} + +static HcfResult EngineUpdata(OH_HCF_CipherGeneratorSpi *self, HcfBlob *input, HcfBlob *output) +{ + LOGE("Openssl don't support update"); + (void)self; + (void)input; + (void)output; + return HCF_NOT_SUPPORT; +} + +static HcfResult DoRsaCrypt(EVP_PKEY_CTX *ctx, HcfBlob *input, HcfBlob *output, int32_t mode) +{ + int32_t ret = HCF_OPENSSL_SUCCESS; + if (mode == ENCRYPT_MODE) { + ret = EVP_PKEY_encrypt(ctx, output->data, &output->len, input->data, input->len); + } else if (mode == DECRYPT_MODE) { + ret = EVP_PKEY_decrypt(ctx, output->data, &output->len, input->data, input->len); + } else { + LOGE("OpMode is invalid."); + return HCF_INVALID_PARAMS; + } + if (ret != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + return HCF_SUCCESS; +} + +static HcfResult EngineDoFinal(OH_HCF_CipherGeneratorSpi *self, HcfBlob *input, HcfBlob *output) +{ + LOGI("EngineDoFinal start"); + if (self == NULL || input == NULL || input->data == NULL) { + LOGE("Param is invalid."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, EngineGetClass())) { + LOGE("Class not match"); + return HCF_INVALID_PARAMS; + } + HcfCipherRsaGeneratorSpiImpl *impl = (HcfCipherRsaGeneratorSpiImpl *)self; + if (impl->initFlag != INITIALIZED) { + LOGE("RSACipher has not been init"); + return HCF_INVALID_PARAMS; + } + CipherAttr attr = impl->attr; + output->len = 0; + output->data = NULL; + HcfResult ret = DoRsaCrypt(impl->ctx, input, output, attr.mode); + if (ret != HCF_SUCCESS) { + LOGE("GetOutLen fail."); + return HCF_ERR_CRYPTO_OPERATION; + } + LOGI("ouput data len is %zu.", output->len); + + output->data = (uint8_t *)HcfMalloc(sizeof(uint8_t) * output->len, 0); + ret = DoRsaCrypt(impl->ctx, input, output, attr.mode); + if (ret != HCF_SUCCESS) { + HcfFree(output->data); + output->data = NULL; + output->len = 0; + return HCF_ERR_CRYPTO_OPERATION; + } + LOGI("EngineDoFinal end"); + return HCF_SUCCESS; +} + +static void EngineDestroySpiImpl(HcfObjectBase *generator) +{ + if (generator == NULL) { + return; + } + if (!IsClassMatch((HcfObjectBase *)generator, EngineGetClass())) { + LOGE("Class not match"); + return; + } + HcfCipherRsaGeneratorSpiImpl *impl = (HcfCipherRsaGeneratorSpiImpl *)generator; + EVP_PKEY_CTX_free(impl->ctx); + impl->ctx = NULL; + HcfFree(impl); + generator = NULL; +} + +static const char *EngineGetClass() +{ + return OPENSSL_RSA_CIPHER_CLASS; +} + +static HcfResult CheckRsaCipherParams(CipherAttr *params) +{ + int32_t opensslPadding = 0; + if (params->algo != HCF_ALG_RSA) { + LOGE("Cipher algo %u is invalid.", params->algo); + return HCF_INVALID_PARAMS; + } + if (GetOpensslPadding(params->paddingMode, &opensslPadding) != HCF_SUCCESS) { + LOGE("Cipher create without padding"); + return HCF_INVALID_PARAMS; + } + if (params->paddingMode == HCF_ALG_NOPADDING && (GetOpensslDigestAlg(params->md) != NULL || + GetOpensslDigestAlg(params->mgf1md) != NULL)) { + LOGE("Nopadding don't need md or mgf1md"); + return HCF_INVALID_PARAMS; + } + + if (params->paddingMode == HCF_OPENSSL_RSA_PKCS1_OAEP_PADDING && GetOpensslDigestAlg(params->md) == NULL) { + LOGE("md is NULL"); + return HCF_INVALID_PARAMS; + } + if (params->paddingMode == HCF_OPENSSL_RSA_PKCS1_OAEP_PADDING && GetOpensslDigestAlg(params->mgf1md) == NULL) { + LOGE("Use pkcs1_oaep padding, but mgf1md is NULL"); + return HCF_INVALID_PARAMS; + } + return HCF_SUCCESS; +} + +HcfResult HcfCipherRsaCipherSpiCreate(CipherAttr *params, OH_HCF_CipherGeneratorSpi **generator) +{ + LOGI("Start create rsa cipher spiObj."); + if (generator == NULL || params == NULL) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + HcfCipherRsaGeneratorSpiImpl *returnImpl = (HcfCipherRsaGeneratorSpiImpl *)HcfMalloc( + sizeof(HcfCipherRsaGeneratorSpiImpl), 0); + if (returnImpl == NULL) { + LOGE("Malloc rsa cipher fail."); + return HCF_ERR_MALLOC; + } + if (memcpy_s(&returnImpl->attr, sizeof(CipherAttr), params, sizeof(CipherAttr)) != HCF_SUCCESS) { + LOGE("memcpuy_s CipherAttr fail."); + HcfFree(returnImpl); + return HCF_ERR_COPY; + } + + if (CheckRsaCipherParams(&returnImpl->attr) != HCF_SUCCESS) { + HcfFree(returnImpl); + returnImpl = NULL; + return HCF_INVALID_PARAMS; + } + + returnImpl->super.init = EngineInit; + returnImpl->super.update = EngineUpdata; + returnImpl->super.doFinal = EngineDoFinal; + returnImpl->super.base.destroy = EngineDestroySpiImpl; + returnImpl->super.base.getClass = EngineGetClass; + returnImpl->initFlag = UNINITIALIZED; + *generator = (OH_HCF_CipherGeneratorSpi *)returnImpl; + LOGI("Rsa Cipher create success."); + return HCF_SUCCESS; +} diff --git a/plugin/openssl_plugin/crypto_operation/signature/inc/ecdsa_openssl.h b/plugin/openssl_plugin/crypto_operation/signature/inc/ecdsa_openssl.h new file mode 100644 index 0000000..8a882fa --- /dev/null +++ b/plugin/openssl_plugin/crypto_operation/signature/inc/ecdsa_openssl.h @@ -0,0 +1,33 @@ +/* + * Copyright (C) 2022 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_ECDSA_OPENSSL_H +#define HCF_ECDSA_OPENSSL_H + +#include "signature_spi.h" +#include "params_parser.h" +#include "result.h" + +#ifdef __cplusplus +extern "C" { +#endif + +HcfResult HcfSignSpiEcdsaCreate(HcfSignatureParams *params, HcfSignSpi **returnObj); +HcfResult HcfVerifySpiEcdsaCreate(HcfSignatureParams *params, HcfVerifySpi **returnObj); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/plugin/openssl_plugin/crypto_operation/signature/inc/signature_rsa_openssl.h b/plugin/openssl_plugin/crypto_operation/signature/inc/signature_rsa_openssl.h new file mode 100644 index 0000000..dda9d5b --- /dev/null +++ b/plugin/openssl_plugin/crypto_operation/signature/inc/signature_rsa_openssl.h @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2022 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 "signature_spi.h" +#include "params_parser.h" +#include "result.h" + +typedef struct { + HcfParamsSpec base; + int32_t padding; + int32_t md; +} HcfAsySignatureSpiRsaParams; + +#ifdef __cplusplus +extern "C" { +#endif + +HcfResult HcfSignSpiRsaCreate(HcfSignatureParams *params, HcfSignSpi **returnObj); +HcfResult HcfVerifySpiRsaCreate(HcfSignatureParams *params, HcfVerifySpi **returnObj); + +#ifdef __cplusplus +} +#endif + diff --git a/plugin/openssl_plugin/crypto_operation/signature/src/ecdsa_openssl.c b/plugin/openssl_plugin/crypto_operation/signature/src/ecdsa_openssl.c new file mode 100644 index 0000000..89c0e46 --- /dev/null +++ b/plugin/openssl_plugin/crypto_operation/signature/src/ecdsa_openssl.c @@ -0,0 +1,428 @@ +/* + * Copyright (C) 2022 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 "ecdsa_openssl.h" + +#include +#include + +#include "algorithm_parameter.h" +#include "openssl_class.h" +#include "openssl_common.h" +#include "log.h" +#include "memory.h" +#include "utils.h" + +#define OPENSSL_ECC_SIGN_CLASS "OPENSSL.ECC.SIGN" +#define OPENSSL_ECC_VERIFY_CLASS "OPENSSL.ECC.VERIFY" + +typedef enum { + UNINITIALIZED = 0, + INITIALIZED = 1, + READY = 2, +} EcdsaStatus; + +typedef struct { + HcfSignSpi base; + + const EVP_MD *digestAlg; + + EVP_MD_CTX *ctx; + + int32_t curveId; + + EcdsaStatus status; +} HcfSignSpiEcdsaOpensslImpl; + +typedef struct { + HcfVerifySpi base; + + const EVP_MD *digestAlg; + + EVP_MD_CTX *ctx; + + int32_t curveId; + + EcdsaStatus status; +} HcfVerifySpiEcdsaOpensslImpl; + +static bool IsDigestAlgValid(uint32_t alg) +{ + if ((alg == HCF_OPENSSL_DIGEST_SHA1) || (alg == HCF_OPENSSL_DIGEST_SHA224) || (alg == HCF_OPENSSL_DIGEST_SHA256) || + (alg == HCF_OPENSSL_DIGEST_SHA384) || (alg == HCF_OPENSSL_DIGEST_SHA512)) { + return true; + } else { + LOGE("Invalid digest num is %u.", alg); + return false; + } +} + +// export interfaces +static const char *GetEcdsaSignClass(void) +{ + return OPENSSL_ECC_SIGN_CLASS; +} + +static const char *GetEcdsaVerifyClass(void) +{ + return OPENSSL_ECC_VERIFY_CLASS; +} + +static void DestroyEcdsaSign(HcfObjectBase *self) +{ + if (self == NULL) { + return; + } + if (!IsClassMatch(self, GetEcdsaSignClass())) { + return; + } + HcfSignSpiEcdsaOpensslImpl *impl = (HcfSignSpiEcdsaOpensslImpl *)self; + EVP_MD_CTX_destroy(impl->ctx); + impl->ctx = NULL; + HcfFree(impl); +} + +static void DestroyEcdsaVerify(HcfObjectBase *self) +{ + if (self == NULL) { + return; + } + if (!IsClassMatch(self, GetEcdsaVerifyClass())) { + return; + } + HcfSignSpiEcdsaOpensslImpl *impl = (HcfSignSpiEcdsaOpensslImpl *)self; + EVP_MD_CTX_destroy(impl->ctx); + impl->ctx = NULL; + HcfFree(impl); +} + +static HcfResult EngineSignInit(HcfSignSpi *self, HcfParamsSpec *params, HcfPriKey *privateKey) +{ + LOGI("start ..."); + (void)params; + if ((self == NULL) || (privateKey == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if ((!IsClassMatch((HcfObjectBase *)self, GetEcdsaSignClass())) || + (!IsClassMatch((HcfObjectBase *)privateKey, HCF_OPENSSL_ECC_PRI_KEY_CLASS))) { + return HCF_INVALID_PARAMS; + } + + HcfSignSpiEcdsaOpensslImpl *impl = (HcfSignSpiEcdsaOpensslImpl *)self; + if (impl->status != UNINITIALIZED) { + LOGE("Repeated initialization is not allowed."); + return HCF_INVALID_PARAMS; + } + EC_KEY *ecKey = EC_KEY_new_by_curve_name(impl->curveId); + if (ecKey == NULL) { + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + if (EC_KEY_set_private_key(ecKey, ((HcfOpensslEccPriKey *)privateKey)->sk) != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + EC_KEY_free(ecKey); + return HCF_ERR_CRYPTO_OPERATION; + } + EVP_PKEY *pKey = EVP_PKEY_new(); + if (pKey == NULL) { + HcfPrintOpensslError(); + EC_KEY_free(ecKey); + return HCF_ERR_CRYPTO_OPERATION; + } + if (EVP_PKEY_assign_EC_KEY(pKey, ecKey) != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + EVP_PKEY_free(pKey); + EC_KEY_free(ecKey); + return HCF_ERR_CRYPTO_OPERATION; + } + if (EVP_DigestSignInit(impl->ctx, NULL, impl->digestAlg, NULL, pKey) != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + EVP_PKEY_free(pKey); + return HCF_ERR_CRYPTO_OPERATION; + } + EVP_PKEY_free(pKey); + impl->status = INITIALIZED; + LOGI("end ..."); + return HCF_SUCCESS; +} + +static HcfResult EngineSignUpdate(HcfSignSpi *self, HcfBlob *data) +{ + LOGI("start ..."); + if ((self == NULL) || (!IsBlobValid(data))) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetEcdsaSignClass())) { + return HCF_INVALID_PARAMS; + } + HcfSignSpiEcdsaOpensslImpl *impl = (HcfSignSpiEcdsaOpensslImpl *)self; + if (impl->status == UNINITIALIZED) { + LOGE("Sign object has not been initialized."); + return HCF_INVALID_PARAMS; + } + if (EVP_DigestSignUpdate(impl->ctx, data->data, data->len) != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + impl->status = READY; + LOGI("end ..."); + return HCF_SUCCESS; +} + +static HcfResult EngineSignDoFinal(HcfSignSpi *self, HcfBlob *data, HcfBlob *returnSignatureData) +{ + LOGI("start ..."); + if ((self == NULL) || (returnSignatureData == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetEcdsaSignClass())) { + return HCF_INVALID_PARAMS; + } + + HcfSignSpiEcdsaOpensslImpl *impl = (HcfSignSpiEcdsaOpensslImpl *)self; + if (IsBlobValid(data)) { + if (EVP_DigestSignUpdate(impl->ctx, data->data, data->len) != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + impl->status = READY; + } + if (impl->status != READY) { + LOGE("The message has not been transferred."); + return HCF_INVALID_PARAMS; + } + size_t maxLen; + if (EVP_DigestSignFinal(impl->ctx, NULL, &maxLen) != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + uint8_t *outData = (uint8_t *)HcfMalloc(maxLen, 0); + if (outData == NULL) { + LOGE("Failed to allocate outData memory!"); + return HCF_ERR_MALLOC; + } + size_t actualLen = maxLen; + if (EVP_DigestSignFinal(impl->ctx, outData, &actualLen) != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + HcfFree(outData); + return HCF_ERR_CRYPTO_OPERATION; + } + if (actualLen > maxLen) { + LOGE("signature data too long."); + HcfFree(outData); + return HCF_ERR_CRYPTO_OPERATION; + } + + returnSignatureData->data = outData; + returnSignatureData->len = (uint32_t)actualLen; + LOGI("end ..."); + return HCF_SUCCESS; +} + +static HcfResult EngineVerifyInit(HcfVerifySpi *self, HcfParamsSpec *params, HcfPubKey *publicKey) +{ + LOGI("start ..."); + (void)params; + if ((self == NULL) || (publicKey == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if ((!IsClassMatch((HcfObjectBase *)self, GetEcdsaVerifyClass())) || + (!IsClassMatch((HcfObjectBase *)publicKey, HCF_OPENSSL_ECC_PUB_KEY_CLASS))) { + return HCF_INVALID_PARAMS; + } + + HcfVerifySpiEcdsaOpensslImpl *impl = (HcfVerifySpiEcdsaOpensslImpl *)self; + if (impl->status != UNINITIALIZED) { + LOGE("Repeated initialization is not allowed."); + return HCF_INVALID_PARAMS; + } + EC_KEY *ecKey = EC_KEY_new_by_curve_name(impl->curveId); + if (ecKey == NULL) { + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + if (EC_KEY_set_public_key(ecKey, ((HcfOpensslEccPubKey *)publicKey)->pk) != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + EC_KEY_free(ecKey); + return HCF_ERR_CRYPTO_OPERATION; + } + EVP_PKEY *pKey = EVP_PKEY_new(); + if (pKey == NULL) { + HcfPrintOpensslError(); + EC_KEY_free(ecKey); + return HCF_ERR_CRYPTO_OPERATION; + } + if (EVP_PKEY_assign_EC_KEY(pKey, ecKey) != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + EVP_PKEY_free(pKey); + EC_KEY_free(ecKey); + return HCF_ERR_CRYPTO_OPERATION; + } + if (EVP_DigestVerifyInit(impl->ctx, NULL, impl->digestAlg, NULL, pKey) != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + EVP_PKEY_free(pKey); + return HCF_ERR_CRYPTO_OPERATION; + } + EVP_PKEY_free(pKey); + impl->status = INITIALIZED; + LOGI("end ..."); + return HCF_SUCCESS; +} + +static HcfResult EngineVerifyUpdate(HcfVerifySpi *self, HcfBlob *data) +{ + LOGI("start ..."); + if ((self == NULL) || (!IsBlobValid(data))) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetEcdsaVerifyClass())) { + return HCF_INVALID_PARAMS; + } + + HcfVerifySpiEcdsaOpensslImpl *impl = (HcfVerifySpiEcdsaOpensslImpl *)self; + if (impl->status == UNINITIALIZED) { + LOGE("Verify object has not been initialized."); + return HCF_INVALID_PARAMS; + } + if (EVP_DigestVerifyUpdate(impl->ctx, data->data, data->len) != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + impl->status = READY; + LOGI("end ..."); + return HCF_SUCCESS; +} + +static bool EngineVerifyDoFinal(HcfVerifySpi *self, HcfBlob *data, HcfBlob *signatureData) +{ + LOGI("start ..."); + if ((self == NULL) || (!IsBlobValid(signatureData))) { + LOGE("Invalid input parameter."); + return false; + } + if (!IsClassMatch((HcfObjectBase *)self, GetEcdsaVerifyClass())) { + return false; + } + + HcfVerifySpiEcdsaOpensslImpl *impl = (HcfVerifySpiEcdsaOpensslImpl *)self; + if (IsBlobValid(data)) { + if (EVP_DigestVerifyUpdate(impl->ctx, data->data, data->len) != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + return false; + } + impl->status = READY; + } + if (impl->status != READY) { + LOGE("The message has not been transferred."); + return false; + } + if (EVP_DigestVerifyFinal(impl->ctx, signatureData->data, signatureData->len) != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + return false; + } + LOGI("end ..."); + return true; +} + +HcfResult HcfSignSpiEcdsaCreate(HcfSignatureParams *params, HcfSignSpi **returnObj) +{ + if ((params == NULL) || (returnObj == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + int32_t curveId; + if (GetOpensslCurveId(params->keyLen, &curveId) != HCF_SUCCESS) { + return HCF_INVALID_PARAMS; + } + if (!IsDigestAlgValid(params->md)) { + return HCF_INVALID_PARAMS; + } + const EVP_MD *opensslAlg = GetOpensslDigestAlg(params->md); + if (opensslAlg == NULL) { + return HCF_INVALID_PARAMS; + } + + HcfSignSpiEcdsaOpensslImpl *returnImpl = (HcfSignSpiEcdsaOpensslImpl *)HcfMalloc( + sizeof(HcfSignSpiEcdsaOpensslImpl), 0); + if (returnImpl == NULL) { + LOGE("Failed to allocate returnImpl memroy!"); + return HCF_ERR_MALLOC; + } + returnImpl->base.base.getClass = GetEcdsaSignClass; + returnImpl->base.base.destroy = DestroyEcdsaSign; + returnImpl->base.engineInit = EngineSignInit; + returnImpl->base.engineUpdate = EngineSignUpdate; + returnImpl->base.engineSign = EngineSignDoFinal; + returnImpl->curveId = curveId; + returnImpl->digestAlg = opensslAlg; + returnImpl->status = UNINITIALIZED; + returnImpl->ctx = EVP_MD_CTX_create(); + if (returnImpl->ctx == NULL) { + LOGE("Failed to allocate ctx memory!"); + HcfFree(returnImpl); + return HCF_ERR_MALLOC; + } + + *returnObj = (HcfSignSpi *)returnImpl; + return HCF_SUCCESS; +} + +HcfResult HcfVerifySpiEcdsaCreate(HcfSignatureParams *params, HcfVerifySpi **returnObj) +{ + if ((params == NULL) || (returnObj == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + int32_t curveId; + if (GetOpensslCurveId(params->keyLen, &curveId) != HCF_SUCCESS) { + return HCF_INVALID_PARAMS; + } + if (!IsDigestAlgValid(params->md)) { + return HCF_INVALID_PARAMS; + } + const EVP_MD *opensslAlg = GetOpensslDigestAlg(params->md); + if (opensslAlg == NULL) { + return HCF_INVALID_PARAMS; + } + + HcfVerifySpiEcdsaOpensslImpl *returnImpl = (HcfVerifySpiEcdsaOpensslImpl *)HcfMalloc( + sizeof(HcfVerifySpiEcdsaOpensslImpl), 0); + if (returnImpl == NULL) { + LOGE("Failed to allocate returnImpl memroy!"); + return HCF_ERR_MALLOC; + } + returnImpl->base.base.getClass = GetEcdsaVerifyClass; + returnImpl->base.base.destroy = DestroyEcdsaVerify; + returnImpl->base.engineInit = EngineVerifyInit; + returnImpl->base.engineUpdate = EngineVerifyUpdate; + returnImpl->base.engineVerify = EngineVerifyDoFinal; + returnImpl->curveId = curveId; + returnImpl->digestAlg = opensslAlg; + returnImpl->status = UNINITIALIZED; + returnImpl->ctx = EVP_MD_CTX_create(); + if (returnImpl->ctx == NULL) { + LOGE("Failed to allocate ctx memory!"); + HcfFree(returnImpl); + return HCF_ERR_MALLOC; + } + + *returnObj = (HcfVerifySpi *)returnImpl; + 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 new file mode 100644 index 0000000..d8ff234 --- /dev/null +++ b/plugin/openssl_plugin/crypto_operation/signature/src/signature_rsa_openssl.c @@ -0,0 +1,479 @@ +/* + * Copyright (C) 2022 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 "signature_rsa_openssl.h" +#include "string.h" +#include + +#include "algorithm_parameter.h" +#include "log.h" +#include "memory.h" +#include "openssl_class.h" +#include "openssl_common.h" +#include "rsa_openssl_common.h" +#include "utils.h" + +typedef struct { + HcfSignSpi base; + + EVP_MD_CTX *mdctx; + + int32_t padding; + + int32_t md; + + int32_t mgf1md; + + InitFlag initFlag; +} HcfSignSpiRsaOpensslImpl; + +typedef struct { + HcfVerifySpi base; + + EVP_MD_CTX *mdctx; + + int32_t padding; + + int32_t md; + + int32_t mgf1md; + + InitFlag initFlag; +} HcfVerifySpiRsaOpensslImpl; + +static const char *GetRsaSignClass() +{ + return OPENSSL_RSA_SIGN_CLASS; +} + +static const char *GetRsaVerifyClass() +{ + return OPENSSL_RSA_VERIFY_CLASS; +} + +static void DestroyRsaSign(HcfObjectBase *self) +{ + if (self == NULL) { + LOGE("Class is null"); + return; + } + if (!IsClassMatch(self, OPENSSL_RSA_SIGN_CLASS)) { + LOGE("Class not match."); + return; + } + HcfSignSpiRsaOpensslImpl *impl = (HcfSignSpiRsaOpensslImpl *)self; + EVP_MD_CTX_destroy(impl->mdctx); + impl->mdctx = NULL; + HcfFree(impl); + impl = NULL; + LOGI("DestroyRsaSign success."); +} + +static void DestroyRsaVerify(HcfObjectBase *self) +{ + if (self == NULL) { + LOGE("Class is null"); + return; + } + if (!IsClassMatch(self, OPENSSL_RSA_VERIFY_CLASS)) { + LOGE("Class not match."); + return; + } + HcfVerifySpiRsaOpensslImpl *impl = (HcfVerifySpiRsaOpensslImpl *)self; + EVP_MD_CTX_destroy(impl->mdctx); + impl->mdctx = NULL; + HcfFree(impl); + impl = NULL; + LOGI("DestroyRsaVerify success."); +} + +static HcfResult CheckInitKeyType(HcfKey *key, bool signing) +{ + if (signing) { + if (!IsClassMatch((HcfObjectBase *)key, OPENSSL_RSA_PRIKEY_CLASS)) { + LOGE("Input keyType dismatch with sign option, please use priKey."); + return HCF_INVALID_PARAMS; + } + } else { + if (!IsClassMatch((HcfObjectBase *)key, OPENSSL_RSA_PUBKEY_CLASS)) { + LOGE("Input keyType dismatch with sign option, please use pubKey."); + return HCF_INVALID_PARAMS; + } + } + return HCF_SUCCESS; +} + +static EVP_PKEY *InitRsaEvpKey(const HcfKey *key, bool signing) +{ + RSA *rsa = NULL; + if (DuplicateRsa(signing ? ((HcfOpensslRsaPriKey *)key)->sk : ((HcfOpensslRsaPubKey *)key)->pk, signing, &rsa) + != HCF_SUCCESS) { + LOGE("dup pub rsa fail."); + return NULL; + } + if (rsa == NULL) { + LOGE("The Key is has lost."); + return NULL; + } + EVP_PKEY *pkey = EVP_PKEY_new(); + if (pkey == NULL) { + LOGE("New evp pkey failed"); + HcfPrintOpensslError(); + RSA_free(rsa); + return NULL; + } + if (EVP_PKEY_assign_RSA(pkey, rsa) != HCF_OPENSSL_SUCCESS) { + LOGE("EVP_PKEY_assign_RSA fail."); + HcfPrintOpensslError(); + RSA_free(rsa); + EVP_PKEY_free(pkey); + return NULL; + } + return pkey; +} + +static HcfResult SetPaddingAndDigest(EVP_PKEY_CTX *ctx, int32_t hcfPadding, int32_t md, int32_t mgf1md) +{ + int32_t opensslPadding = 0; + if (GetOpensslPadding(hcfPadding, &opensslPadding) != HCF_SUCCESS) { + LOGE("getpadding fail."); + return HCF_INVALID_PARAMS; + } + if (EVP_PKEY_CTX_set_rsa_padding(ctx, opensslPadding) != HCF_OPENSSL_SUCCESS) { + LOGE("EVP_PKEY_CTX_set_rsa_padding fail"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + if (hcfPadding == HCF_OPENSSL_RSA_PSS_PADDING) { + LOGI("padding is pss, set mgf1 md"); + if (EVP_PKEY_CTX_set_rsa_mgf1_md(ctx, GetOpensslDigestAlg(mgf1md)) != HCF_OPENSSL_SUCCESS) { + LOGE("EVP_PKEY_CTX_set_rsa_mgf1_md fail"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + } + return HCF_SUCCESS; +} + + +static HcfResult SetSignParams(HcfSignSpiRsaOpensslImpl *impl, HcfPriKey *privateKey) +{ + EVP_PKEY *dupKey = InitRsaEvpKey((HcfKey *)privateKey, true); + if (dupKey == NULL) { + LOGE("InitRsaEvpKey fail."); + return HCF_ERR_CRYPTO_OPERATION; + } + EVP_PKEY_CTX *ctx = NULL; + if (EVP_DigestSignInit(impl->mdctx, &ctx, GetOpensslDigestAlg(impl->md), NULL, dupKey) != HCF_OPENSSL_SUCCESS) { + LOGE("EVP_DigestSignInit fail."); + EVP_PKEY_free(dupKey); + return HCF_ERR_CRYPTO_OPERATION; + } + if (SetPaddingAndDigest(ctx, impl->padding, impl->md, impl->mgf1md) != HCF_SUCCESS) { + LOGE("set padding and digest fail"); + EVP_PKEY_free(dupKey); + return HCF_ERR_CRYPTO_OPERATION; + } + EVP_PKEY_free(dupKey); + return HCF_SUCCESS; +} + +static HcfResult EngineSignInit(HcfSignSpi *self, HcfParamsSpec *params, HcfPriKey *privateKey) +{ + LOGI("EngineSignInit start"); + if (self == NULL || privateKey == NULL) { + LOGE("Invalid input params"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, OPENSSL_RSA_SIGN_CLASS)) { + LOGE("Class not match."); + return HCF_INVALID_PARAMS; + } + HcfSignSpiRsaOpensslImpl *impl = (HcfSignSpiRsaOpensslImpl *)self; + if (impl->initFlag != UNINITIALIZED) { + LOGE("Sign has been init"); + return HCF_INVALID_PARAMS; + } + if (CheckInitKeyType((HcfKey *)privateKey, true) != HCF_SUCCESS) { + LOGE("KeyType dismatch."); + return HCF_INVALID_PARAMS; + } + if (SetSignParams(impl, privateKey) != HCF_SUCCESS) { + LOGE("Sign set padding or md fail"); + return HCF_ERR_CRYPTO_OPERATION; + } + impl->initFlag = INITIALIZED; + LOGI("EngineSignInit end"); + return HCF_SUCCESS; +} + +static HcfResult SetVerifyParams(HcfVerifySpiRsaOpensslImpl *impl, HcfPubKey *publicKey) +{ + EVP_PKEY_CTX *ctx = NULL; + EVP_PKEY *dupKey = InitRsaEvpKey((HcfKey *)publicKey, false); + if (dupKey == NULL) { + LOGE("InitRsaEvpKey fail."); + return HCF_ERR_CRYPTO_OPERATION; + } + if (EVP_DigestVerifyInit(impl->mdctx, &ctx, GetOpensslDigestAlg(impl->md), NULL, dupKey) != HCF_OPENSSL_SUCCESS) { + LOGE("EVP_DigestVerifyInit fail."); + HcfPrintOpensslError(); + EVP_PKEY_free(dupKey); + return HCF_ERR_CRYPTO_OPERATION; + } + if (SetPaddingAndDigest(ctx, impl->padding, impl->md, impl->mgf1md) != HCF_SUCCESS) { + LOGE("set padding and digest fail"); + EVP_PKEY_free(dupKey); + return HCF_ERR_CRYPTO_OPERATION; + } + EVP_PKEY_free(dupKey); + return HCF_SUCCESS; +} + +static HcfResult EngineVerifyInit(HcfVerifySpi *self, HcfParamsSpec *params, HcfPubKey *publicKey) +{ + LOGI("EngineVerifyInit start"); + if (self == NULL || publicKey == NULL) { + LOGE("Invalid input params."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, OPENSSL_RSA_VERIFY_CLASS)) { + LOGE("Class not match."); + return HCF_INVALID_PARAMS; + } + HcfVerifySpiRsaOpensslImpl *impl = (HcfVerifySpiRsaOpensslImpl *)self; + if (impl->initFlag != UNINITIALIZED) { + LOGE("Verigy has been init."); + return HCF_INVALID_PARAMS; + } + if (CheckInitKeyType((HcfKey *)publicKey, false) != HCF_SUCCESS) { + LOGE("KeyType dismatch."); + return HCF_INVALID_PARAMS; + } + if (SetVerifyParams(impl, publicKey) != HCF_SUCCESS) { + LOGE("Verify set padding or md fail"); + return HCF_ERR_CRYPTO_OPERATION; + } + impl->initFlag = INITIALIZED; + LOGI("EngineVerifyInit end"); + return HCF_SUCCESS; +} + +static HcfResult EngineSignUpdate(HcfSignSpi *self, HcfBlob *data) +{ + LOGI("start ..."); + if ((self == NULL) || (data == NULL) || (data->data == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, OPENSSL_RSA_SIGN_CLASS)) { + LOGE("Class not match."); + return HCF_INVALID_PARAMS; + } + HcfSignSpiRsaOpensslImpl *impl = (HcfSignSpiRsaOpensslImpl *)self; + if (impl->initFlag != INITIALIZED) { + LOGE("The Sign has not been init"); + return HCF_INVALID_PARAMS; + } + if (EVP_DigestSignUpdate(impl->mdctx, data->data, data->len) != HCF_OPENSSL_SUCCESS) { + LOGE("EVP_DigestSignUpdate fail"); + return HCF_ERR_CRYPTO_OPERATION; + } + LOGI("end ..."); + return HCF_SUCCESS; +} + +static HcfResult EngineVerifyUpdate(HcfVerifySpi *self, HcfBlob *data) +{ + LOGI("start ..."); + if ((self == NULL) || (data == NULL) || (data->data == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, OPENSSL_RSA_VERIFY_CLASS)) { + LOGE("Class not match."); + return HCF_INVALID_PARAMS; + } + HcfVerifySpiRsaOpensslImpl *impl = (HcfVerifySpiRsaOpensslImpl *)self; + if (impl->initFlag != INITIALIZED) { + LOGE("The Sign has not been init"); + return HCF_INVALID_PARAMS; + } + if (EVP_DigestVerifyUpdate(impl->mdctx, data->data, data->len) != HCF_OPENSSL_SUCCESS) { + LOGE("EVP_DigestSignUpdate fail"); + return HCF_ERR_CRYPTO_OPERATION; + } + LOGI("end ..."); + return HCF_SUCCESS; +} + +static HcfResult EngineSign(HcfSignSpi *self, HcfBlob *data, HcfBlob *returnSignatureData) +{ + LOGI("EngineSign start"); + if (self == NULL || data == NULL || data->data == NULL || returnSignatureData == NULL) { + LOGE("Invalid input params."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, OPENSSL_RSA_SIGN_CLASS)) { + LOGE("Class not match."); + return HCF_INVALID_PARAMS; + } + HcfSignSpiRsaOpensslImpl *impl = (HcfSignSpiRsaOpensslImpl *)self; + if (impl->initFlag != INITIALIZED) { + LOGE("The Sign has not been init"); + return HCF_INVALID_PARAMS; + } + if (data != NULL && data->data != NULL) { + if (EVP_DigestSignUpdate(impl->mdctx, data->data, data->len) != HCF_OPENSSL_SUCCESS) { + LOGE("Dofinal update data fail."); + return HCF_ERR_CRYPTO_OPERATION; + } + } + size_t maxLen; + if (EVP_DigestSignFinal(impl->mdctx, NULL, &maxLen) != HCF_OPENSSL_SUCCESS) { + LOGE("EVP_DigestSignFinal fail"); + return HCF_ERR_CRYPTO_OPERATION; + } + uint8_t *outData = (uint8_t *)HcfMalloc(maxLen, 0); + if (outData == NULL) { + LOGE("Failed to allocate outData memory!"); + return HCF_ERR_MALLOC; + } + size_t actualLen = maxLen; + if (EVP_DigestSignFinal(impl->mdctx, outData, &actualLen) != HCF_OPENSSL_SUCCESS) { + LOGE("EVP_DigestSignFinal fail"); + HcfFree(outData); + return HCF_ERR_CRYPTO_OPERATION; + } + if (actualLen > maxLen) { + LOGE("signature data too long."); + HcfFree(outData); + return HCF_ERR_CRYPTO_OPERATION; + } + + returnSignatureData->data = outData; + returnSignatureData->len = (uint32_t)actualLen; + + LOGI("EngineSign end"); + return HCF_SUCCESS; +} + +static bool EngineVerify(HcfVerifySpi *self, HcfBlob *data, HcfBlob *signatureData) +{ + LOGI("EngineVerify start"); + if (self == NULL || data == NULL || data->data == NULL || signatureData == NULL || signatureData->data == NULL) { + LOGE("Invalid input params"); + return false; + } + if (!IsClassMatch((HcfObjectBase *)self, OPENSSL_RSA_VERIFY_CLASS)) { + LOGE("Class not match."); + return false; + } + + HcfVerifySpiRsaOpensslImpl *impl = (HcfVerifySpiRsaOpensslImpl *)self; + if (impl->initFlag != INITIALIZED) { + LOGE("The Sign has not been init"); + return HCF_INVALID_PARAMS; + } + if (data != NULL && data->data != NULL) { + if (EVP_DigestVerifyUpdate(impl->mdctx, data->data, data->len) != HCF_OPENSSL_SUCCESS) { + LOGE("EVP_DigestVerifyUpdate fail"); + return false; + } + } + if (EVP_DigestVerifyFinal(impl->mdctx, signatureData->data, signatureData->len) != HCF_OPENSSL_SUCCESS) { + LOGE("EVP_DigestVerifyFinal fail"); + return false; + } + LOGI("EngineVerify end"); + return true; +} + +static HcfResult CheckSignatureParams(HcfSignatureParams *params) +{ + if (GetOpensslDigestAlg(params->md) == NULL) { + LOGE("Md is NULL"); + return HCF_INVALID_PARAMS; + } + if (params->padding == HCF_OPENSSL_RSA_PSS_PADDING && GetOpensslDigestAlg(params->mgf1md) == NULL) { + LOGE("Use pss padding, but mgf1md is NULL"); + return HCF_INVALID_PARAMS; + } + return HCF_SUCCESS; +} + +HcfResult HcfSignSpiRsaCreate(HcfSignatureParams *params, HcfSignSpi **returnObj) +{ + LOGI("HcfSignSpiRsaCreate start"); + if (params == NULL || returnObj == NULL) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (CheckSignatureParams(params) != HCF_SUCCESS) { + return HCF_INVALID_PARAMS; + } + HcfSignSpiRsaOpensslImpl *returnImpl = (HcfSignSpiRsaOpensslImpl *)HcfMalloc( + sizeof(HcfSignSpiRsaOpensslImpl), 0); + if (returnImpl == NULL) { + LOGE("Failed to allocate returnImpl memroy!"); + return HCF_ERR_MALLOC; + } + returnImpl->base.base.getClass = GetRsaSignClass; + returnImpl->base.base.destroy = DestroyRsaSign; + returnImpl->base.engineInit = EngineSignInit; + returnImpl->base.engineUpdate = EngineSignUpdate; + returnImpl->base.engineSign = EngineSign; + + returnImpl->md = params->md; + returnImpl->padding = params->padding; + returnImpl->mgf1md = params->mgf1md; + returnImpl->mdctx = EVP_MD_CTX_create(); + returnImpl->initFlag = UNINITIALIZED; + *returnObj = (HcfSignSpi *)returnImpl; + LOGI("HcfSignSpiRsaCreate end"); + return HCF_SUCCESS; +} + +HcfResult HcfVerifySpiRsaCreate(HcfSignatureParams *params, HcfVerifySpi **returnObj) +{ + LOGI("HcfSignSpiRsaCreate start"); + if (params == NULL || returnObj == NULL) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (CheckSignatureParams(params) != HCF_SUCCESS) { + return HCF_INVALID_PARAMS; + } + HcfVerifySpiRsaOpensslImpl *returnImpl = (HcfVerifySpiRsaOpensslImpl *)HcfMalloc( + sizeof(HcfVerifySpiRsaOpensslImpl), 0); + if (returnImpl == NULL) { + LOGE("Failed to allocate returnImpl memroy!"); + return HCF_ERR_MALLOC; + } + returnImpl->base.base.getClass = GetRsaVerifyClass; + returnImpl->base.base.destroy = DestroyRsaVerify; + returnImpl->base.engineInit = EngineVerifyInit; + returnImpl->base.engineUpdate = EngineVerifyUpdate; + returnImpl->base.engineVerify = EngineVerify; + + returnImpl->md = params->md; + returnImpl->padding = params->padding; + returnImpl->mgf1md = params->mgf1md; + returnImpl->mdctx = EVP_MD_CTX_create(); + returnImpl->initFlag = UNINITIALIZED; + *returnObj = (HcfVerifySpi *)returnImpl; + LOGI("HcfSignSpiRsaCreate end"); + return HCF_SUCCESS; +} diff --git a/plugin/openssl_plugin/key/asy_key_generator/inc/ecc_asy_key_generator_openssl.h b/plugin/openssl_plugin/key/asy_key_generator/inc/ecc_asy_key_generator_openssl.h new file mode 100644 index 0000000..4f757bd --- /dev/null +++ b/plugin/openssl_plugin/key/asy_key_generator/inc/ecc_asy_key_generator_openssl.h @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2022 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_ECC_ASY_KEY_GENERATOR_OPENSSL_H +#define HCF_ECC_ASY_KEY_GENERATOR_OPENSSL_H + +#include "asy_key_generator_spi.h" +#include "params_parser.h" +#include "result.h" + +#ifdef __cplusplus +extern "C" { +#endif + +HcfResult HcfAsyKeyGeneratorSpiEccCreate(HcfAsyKeyGenParams *params, HcfAsyKeyGeneratorSpi **returnObj); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/plugin/openssl_plugin/key/asy_key_generator/inc/rsa_asy_key_generator_openssl.h b/plugin/openssl_plugin/key/asy_key_generator/inc/rsa_asy_key_generator_openssl.h new file mode 100644 index 0000000..d3e029e --- /dev/null +++ b/plugin/openssl_plugin/key/asy_key_generator/inc/rsa_asy_key_generator_openssl.h @@ -0,0 +1,28 @@ +/* + * Copyright (C) 2022 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_spi.h" +#include "params_parser.h" +#include "result.h" + +#ifdef __cplusplus +extern "C" { +#endif + +HcfResult HcfAsyKeyGeneratorSpiRsaCreate(HcfAsyKeyGenParams *params, HcfAsyKeyGeneratorSpi **generator); + +#ifdef __cplusplus +} +#endif 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 new file mode 100644 index 0000000..61092d2 --- /dev/null +++ b/plugin/openssl_plugin/key/asy_key_generator/src/ecc_asy_key_generator_openssl.c @@ -0,0 +1,523 @@ +/* + * Copyright (C) 2022 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_asy_key_generator_openssl.h" + +#include +#include + +#include "algorithm_parameter.h" +#include "log.h" +#include "memory.h" +#include "openssl_class.h" +#include "openssl_common.h" +#include "utils.h" + +#define OPENSSL_ECC_KEY_GENERATOR_CLASS "OPENSSL.ECC.KEY_GENERATOR_CLASS" +#define OPENSSL_ECC_ALGORITHM "EC" +#define OPENSSL_ECC_PUB_KEY_FORMAT "X.509" +#define OPENSSL_ECC_PRI_KEY_FORMAT "PKCS#8" + +typedef struct { + HcfAsyKeyGeneratorSpi base; + + int32_t curveId; +} HcfAsyKeyGeneratorSpiOpensslEccImpl; + +static HcfResult NewEcKeyPairByOpenssl(int32_t curveId, EC_POINT **returnPubKey, BIGNUM **returnPriKey) +{ + EC_KEY *ecKey = EC_KEY_new_by_curve_name(curveId); + if (ecKey == NULL) { + LOGE("new ec key failed."); + return HCF_ERR_CRYPTO_OPERATION; + } + if (EC_KEY_generate_key(ecKey) <= 0) { + LOGE("generate ec key failed."); + EC_KEY_free(ecKey); + return HCF_ERR_CRYPTO_OPERATION; + } + if (EC_KEY_check_key(ecKey) <= 0) { + LOGE("check key fail."); + EC_KEY_free(ecKey); + return HCF_ERR_CRYPTO_OPERATION; + } + const EC_POINT *pubKey = EC_KEY_get0_public_key(ecKey); + const BIGNUM *priKey = EC_KEY_get0_private_key(ecKey); + const EC_GROUP *group = EC_KEY_get0_group(ecKey); + if ((pubKey == NULL) || (priKey == NULL) || (group == NULL)) { + LOGE("ec key is invalid."); + EC_KEY_free(ecKey); + return HCF_ERR_CRYPTO_OPERATION; + } + EC_POINT *newPubKey = EC_POINT_dup(pubKey, group); + if (newPubKey == NULL) { + LOGE("copy pubKey fail."); + EC_KEY_free(ecKey); + return HCF_ERR_CRYPTO_OPERATION; + } + BIGNUM *newPriKey = BN_dup(priKey); + if (newPriKey == NULL) { + LOGE("copy pubKey fail."); + EC_KEY_free(ecKey); + EC_POINT_free(newPubKey); + return HCF_ERR_CRYPTO_OPERATION; + } + + *returnPubKey = newPubKey; + *returnPriKey = newPriKey; + EC_KEY_free(ecKey); + return HCF_SUCCESS; +} + +// export interfaces +static const char *GetEccKeyPairGeneratorClass(void) +{ + return OPENSSL_ECC_KEY_GENERATOR_CLASS; +} + +static const char *GetEccKeyPairClass(void) +{ + return HCF_OPENSSL_ECC_KEY_PAIR_CLASS; +} + +static const char *GetEccPubKeyClass(void) +{ + return HCF_OPENSSL_ECC_PUB_KEY_CLASS; +} + +static const char *GetEccPriKeyClass(void) +{ + return HCF_OPENSSL_ECC_PRI_KEY_CLASS; +} + +static void DestroyEccKeyPairGenerator(HcfObjectBase *self) +{ + if (self == NULL) { + return; + } + if (!IsClassMatch(self, GetEccKeyPairGeneratorClass())) { + return; + } + HcfFree(self); +} + +static void DestroyEccKeyPair(HcfObjectBase *self) +{ + if (self == NULL) { + return; + } + if (!IsClassMatch(self, GetEccKeyPairClass())) { + return; + } + HcfOpensslEccKeyPair *impl = (HcfOpensslEccKeyPair *)self; + if (impl->base.pubKey != NULL) { + OH_HCF_ObjDestroy(impl->base.pubKey); + impl->base.pubKey = NULL; + } + if (impl->base.priKey != NULL) { + OH_HCF_ObjDestroy(impl->base.priKey); + impl->base.priKey = NULL; + } + HcfFree(impl); +} + +static void DestroyEccPubKey(HcfObjectBase *self) +{ + if (self == NULL) { + return; + } + if (!IsClassMatch(self, GetEccPubKeyClass())) { + return; + } + HcfOpensslEccPubKey *impl = (HcfOpensslEccPubKey *)self; + EC_POINT_free(impl->pk); + impl->pk = NULL; + HcfFree(impl); +} + +static void DestroyEccPriKey(HcfObjectBase *self) +{ + if (self == NULL) { + return; + } + if (!IsClassMatch(self, GetEccPriKeyClass())) { + return; + } + HcfOpensslEccPriKey *impl = (HcfOpensslEccPriKey *)self; + BN_clear_free(impl->sk); + impl->sk = NULL; + HcfFree(impl); +} + +static const char *GetEccPubKeyAlgorithm(HcfKey *self) +{ + if (self == NULL) { + LOGE("Invalid input parameter."); + return NULL; + } + if (!IsClassMatch((HcfObjectBase *)self, HCF_OPENSSL_ECC_PUB_KEY_CLASS)) { + return NULL; + } + return OPENSSL_ECC_ALGORITHM; +} + +static const char *GetEccPriKeyAlgorithm(HcfKey *self) +{ + if (self == NULL) { + LOGE("Invalid input parameter."); + return NULL; + } + if (!IsClassMatch((HcfObjectBase *)self, HCF_OPENSSL_ECC_PRI_KEY_CLASS)) { + return NULL; + } + return OPENSSL_ECC_ALGORITHM; +} + +static const char *GetEccPubKeyFormat(HcfKey *self) +{ + if (self == NULL) { + LOGE("Invalid input parameter."); + return NULL; + } + if (!IsClassMatch((HcfObjectBase *)self, HCF_OPENSSL_ECC_PUB_KEY_CLASS)) { + return NULL; + } + return OPENSSL_ECC_PUB_KEY_FORMAT; +} + +static const char *GetEccPriKeyFormat(HcfKey *self) +{ + if (self == NULL) { + LOGE("Invalid input parameter."); + return NULL; + } + if (!IsClassMatch((HcfObjectBase *)self, HCF_OPENSSL_ECC_PRI_KEY_CLASS)) { + return NULL; + } + return OPENSSL_ECC_PRI_KEY_FORMAT; +} + +static HcfResult GetEccPubKeyEncoded(HcfKey *self, HcfBlob *returnBlob) +{ + LOGI("start ..."); + if ((self == NULL) || (returnBlob == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, HCF_OPENSSL_ECC_PUB_KEY_CLASS)) { + return HCF_INVALID_PARAMS; + } + + HcfOpensslEccPubKey *impl = (HcfOpensslEccPubKey *)self; + if (impl->pk == NULL) { + LOGE("Empty public key!"); + return HCF_INVALID_PARAMS; + } + EC_GROUP *group = EC_GROUP_new_by_curve_name(impl->curveId); + if (group == NULL) { + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + uint32_t maxLen = EC_POINT_point2oct(group, impl->pk, POINT_CONVERSION_UNCOMPRESSED, NULL, 0, NULL); + uint8_t *outData = (uint8_t *)HcfMalloc(maxLen, 0); + if (outData == NULL) { + LOGE("Failed to allocate outData memory!"); + EC_GROUP_free(group); + return HCF_ERR_MALLOC; + } + uint32_t actualLen = EC_POINT_point2oct(group, impl->pk, POINT_CONVERSION_UNCOMPRESSED, outData, maxLen, NULL); + EC_GROUP_free(group); + if (actualLen <= 0) { + HcfPrintOpensslError(); + HcfFree(outData); + return HCF_ERR_CRYPTO_OPERATION; + } + + returnBlob->data = outData; + returnBlob->len = actualLen; + LOGI("end ..."); + return HCF_SUCCESS; +} + +static HcfResult GetEccPriKeyEncoded(HcfKey *self, HcfBlob *returnBlob) +{ + LOGI("start ..."); + if ((self == NULL) || (returnBlob == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, HCF_OPENSSL_ECC_PRI_KEY_CLASS)) { + return HCF_INVALID_PARAMS; + } + + HcfOpensslEccPriKey *impl = (HcfOpensslEccPriKey *)self; + if (impl->sk == NULL) { + LOGE("Empty private key!"); + return HCF_INVALID_PARAMS; + } + uint32_t maxLen = BN_num_bytes(impl->sk); + uint8_t *outData = (uint8_t *)HcfMalloc(maxLen, 0); + if (outData == NULL) { + LOGE("Failed to allocate outData memory!"); + return HCF_ERR_MALLOC; + } + uint32_t actualLen = BN_bn2binpad(impl->sk, outData, maxLen); + if (actualLen <= 0) { + HcfPrintOpensslError(); + HcfFree(outData); + return HCF_ERR_CRYPTO_OPERATION; + } + + returnBlob->data = outData; + returnBlob->len = actualLen; + LOGI("end ..."); + return HCF_SUCCESS; +} + +static void EccPriKeyClearMem(HcfPriKey *self) +{ + if (self == NULL) { + return; + } + if (!IsClassMatch((HcfObjectBase *)self, GetEccPriKeyClass())) { + return; + } + HcfOpensslEccPriKey *impl = (HcfOpensslEccPriKey *)self; + BN_clear(impl->sk); +} + +static HcfResult CreateEccPubKey(int32_t curveId, EC_POINT *pubKey, HcfOpensslEccPubKey **returnObj) +{ + HcfOpensslEccPubKey *returnPubKey = (HcfOpensslEccPubKey *)HcfMalloc(sizeof(HcfOpensslEccPubKey), 0); + if (returnPubKey == NULL) { + LOGE("Failed to allocate returnPubKey memory!"); + return HCF_ERR_MALLOC; + } + returnPubKey->base.base.base.destroy = DestroyEccPubKey; + returnPubKey->base.base.base.getClass = GetEccPubKeyClass; + returnPubKey->base.base.getAlgorithm = GetEccPubKeyAlgorithm; + returnPubKey->base.base.getEncoded = GetEccPubKeyEncoded; + returnPubKey->base.base.getFormat = GetEccPubKeyFormat; + returnPubKey->curveId = curveId; + returnPubKey->pk = pubKey; + + *returnObj = returnPubKey; + return HCF_SUCCESS; +} + +static HcfResult CreateEccPriKey(int32_t curveId, BIGNUM *priKey, HcfOpensslEccPriKey **returnObj) +{ + HcfOpensslEccPriKey *returnPriKey = (HcfOpensslEccPriKey *)HcfMalloc(sizeof(HcfOpensslEccPriKey), 0); + if (returnPriKey == NULL) { + LOGE("Failed to allocate returnPriKey memory!"); + return HCF_ERR_MALLOC; + } + returnPriKey->base.base.base.destroy = DestroyEccPriKey; + returnPriKey->base.base.base.getClass = GetEccPriKeyClass; + returnPriKey->base.base.getAlgorithm = GetEccPriKeyAlgorithm; + returnPriKey->base.base.getEncoded = GetEccPriKeyEncoded; + returnPriKey->base.base.getFormat = GetEccPriKeyFormat; + returnPriKey->base.clearMem = EccPriKeyClearMem; + returnPriKey->curveId = curveId; + returnPriKey->sk = priKey; + + *returnObj = returnPriKey; + return HCF_SUCCESS; +} + +static HcfResult CreateEccKeyPair(HcfOpensslEccPubKey *pubKey, HcfOpensslEccPriKey *priKey, + HcfOpensslEccKeyPair **returnObj) +{ + HcfOpensslEccKeyPair *returnKeyPair = (HcfOpensslEccKeyPair *)HcfMalloc(sizeof(HcfOpensslEccKeyPair), 0); + if (returnKeyPair == NULL) { + LOGE("Failed to allocate returnKeyPair memory!"); + return HCF_ERR_MALLOC; + } + returnKeyPair->base.base.getClass = GetEccKeyPairClass; + returnKeyPair->base.base.destroy = DestroyEccKeyPair; + returnKeyPair->base.pubKey = (HcfPubKey *)pubKey; + returnKeyPair->base.priKey = (HcfPriKey *)priKey; + + *returnObj = returnKeyPair; + return HCF_SUCCESS; +} + +static HcfResult ConvertEcPubKeyByOpenssl(int32_t curveId, HcfBlob *pubKeyBlob, HcfOpensslEccPubKey **returnPubKey) +{ + EC_GROUP *group = EC_GROUP_new_by_curve_name(curveId); + if (group == NULL) { + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + EC_POINT *point = EC_POINT_new(group); + if (point == NULL) { + HcfPrintOpensslError(); + EC_GROUP_free(group); + return HCF_ERR_CRYPTO_OPERATION; + } + if (EC_POINT_oct2point(group, point, pubKeyBlob->data, pubKeyBlob->len, NULL) != HCF_OPENSSL_SUCCESS) { + HcfPrintOpensslError(); + EC_POINT_free(point); + EC_GROUP_free(group); + return HCF_ERR_CRYPTO_OPERATION; + } + EC_GROUP_free(group); + int32_t res = CreateEccPubKey(curveId, point, returnPubKey); + if (res != HCF_SUCCESS) { + EC_POINT_free(point); + return res; + } + return HCF_SUCCESS; +} + +static HcfResult ConvertEcPriKeyByOpenssl(int32_t curveId, HcfBlob *priKeyBlob, HcfOpensslEccPriKey **returnPriKey) +{ + BIGNUM *bn = BN_bin2bn(priKeyBlob->data, priKeyBlob->len, NULL); + if (bn == NULL) { + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + int32_t res = CreateEccPriKey(curveId, bn, returnPriKey); + if (res != HCF_SUCCESS) { + BN_clear_free(bn); + return res; + } + return HCF_SUCCESS; +} + +static HcfResult EngineConvertEccKey(HcfAsyKeyGeneratorSpi *self, HcfParamsSpec *params, HcfBlob *pubKeyBlob, + HcfBlob *priKeyBlob, HcfKeyPair **returnKeyPair) +{ + LOGI("start ..."); + (void)params; + if ((self == NULL) || (returnKeyPair == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetEccKeyPairGeneratorClass())) { + return HCF_INVALID_PARAMS; + } + bool pubKeyValid = IsBlobValid(pubKeyBlob); + bool priKeyValid = IsBlobValid(priKeyBlob); + if ((!pubKeyValid) && (!priKeyValid)) { + LOGE("The private key and public key cannot both be NULL."); + return HCF_INVALID_PARAMS; + } + + HcfAsyKeyGeneratorSpiOpensslEccImpl *impl = (HcfAsyKeyGeneratorSpiOpensslEccImpl *)self; + int32_t res = HCF_SUCCESS; + HcfOpensslEccPubKey *pubKey = NULL; + HcfOpensslEccPriKey *priKey = NULL; + HcfOpensslEccKeyPair *keyPair = NULL; + do { + if (pubKeyValid) { + res = ConvertEcPubKeyByOpenssl(impl->curveId, pubKeyBlob, &pubKey); + if (res != HCF_SUCCESS) { + break; + } + } + if (priKeyValid) { + res = ConvertEcPriKeyByOpenssl(impl->curveId, priKeyBlob, &priKey); + if (res != HCF_SUCCESS) { + break; + } + } + res = CreateEccKeyPair(pubKey, priKey, &keyPair); + } while (0); + if (res != HCF_SUCCESS) { + OH_HCF_ObjDestroy(pubKey); + OH_HCF_ObjDestroy(priKey); + return res; + } + + *returnKeyPair = (HcfKeyPair *)keyPair; + LOGI("end ..."); + return HCF_SUCCESS; +} + +static HcfResult EngineGenerateKeyPair(HcfAsyKeyGeneratorSpi *self, HcfKeyPair **returnObj) +{ + LOGI("start ..."); + if ((self == NULL) || (returnObj == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, GetEccKeyPairGeneratorClass())) { + return HCF_INVALID_PARAMS; + } + + HcfAsyKeyGeneratorSpiOpensslEccImpl *impl = (HcfAsyKeyGeneratorSpiOpensslEccImpl *)self; + EC_POINT *ecPubKey = NULL; + BIGNUM *ecPriKey = NULL; + int32_t res = NewEcKeyPairByOpenssl(impl->curveId, &ecPubKey, &ecPriKey); + if (res != HCF_SUCCESS) { + return res; + } + HcfOpensslEccPubKey *pubKey = NULL; + res = CreateEccPubKey(impl->curveId, ecPubKey, &pubKey); + if (res != HCF_SUCCESS) { + EC_POINT_free(ecPubKey); + BN_clear_free(ecPriKey); + return res; + } + HcfOpensslEccPriKey *priKey = NULL; + res = CreateEccPriKey(impl->curveId, ecPriKey, &priKey); + if (res != HCF_SUCCESS) { + OH_HCF_ObjDestroy(pubKey); + BN_clear_free(ecPriKey); + return res; + } + HcfOpensslEccKeyPair *returnKeyPair = (HcfOpensslEccKeyPair *)HcfMalloc(sizeof(HcfOpensslEccKeyPair), 0); + if (returnKeyPair == NULL) { + LOGE("Failed to allocate returnKeyPair memory!"); + OH_HCF_ObjDestroy(pubKey); + OH_HCF_ObjDestroy(priKey); + return HCF_ERR_MALLOC; + } + returnKeyPair->base.base.getClass = GetEccKeyPairClass; + returnKeyPair->base.base.destroy = DestroyEccKeyPair; + returnKeyPair->base.pubKey = (HcfPubKey *)pubKey; + returnKeyPair->base.priKey = (HcfPriKey *)priKey; + + *returnObj = (HcfKeyPair *)returnKeyPair; + LOGI("end ..."); + return HCF_SUCCESS; +} + +HcfResult HcfAsyKeyGeneratorSpiEccCreate(HcfAsyKeyGenParams *params, HcfAsyKeyGeneratorSpi **returnObj) +{ + if (params == NULL || returnObj == NULL) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + int32_t curveId; + if (GetOpensslCurveId(params->bits, &curveId) != HCF_SUCCESS) { + return HCF_INVALID_PARAMS; + } + HcfAsyKeyGeneratorSpiOpensslEccImpl *returnImpl = (HcfAsyKeyGeneratorSpiOpensslEccImpl *)HcfMalloc( + sizeof(HcfAsyKeyGeneratorSpiOpensslEccImpl), 0); + if (returnImpl == NULL) { + LOGE("Failed to allocate returnImpl memroy!"); + return HCF_ERR_MALLOC; + } + returnImpl->base.base.getClass = GetEccKeyPairGeneratorClass; + returnImpl->base.base.destroy = DestroyEccKeyPairGenerator; + returnImpl->base.engineConvertKey = EngineConvertEccKey; + returnImpl->base.engineGenerateKeyPair = EngineGenerateKeyPair; + returnImpl->curveId = curveId; + + *returnObj = (HcfAsyKeyGeneratorSpi *)returnImpl; + return HCF_SUCCESS; +} 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 new file mode 100644 index 0000000..3330b63 --- /dev/null +++ b/plugin/openssl_plugin/key/asy_key_generator/src/rsa_asy_key_generator_openssl.c @@ -0,0 +1,778 @@ +/* + * Copyright (C) 2022 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 "rsa_asy_key_generator_openssl.h" +#include "algorithm_parameter.h" +#include "asy_key_generator_spi.h" +#include "log.h" + +#include "memory.h" +#include "openssl_class.h" +#include "openssl_common.h" +#include "rsa_openssl_common.h" +#include "securec.h" +#include "string.h" +#include "utils.h" + +#define OPENSSL_BITS_PER_BYTE 8 +#define OPENSSL_RSA_KEYPAIR_CNT 3 +#define OPENSSL_RSA_KEYGEN_DEFAULT_PRIMES 2 +#define MAX_KEY_SIZE 8192 +#define MIN_KEY_SIZE 512 + +enum OpensslRsaKeySize { + OPENSSL_RSA_KEY_SIZE_512 = 512, + OPENSSL_RSA_KEY_SIZE_768 = 768, + OPENSSL_RSA_KEY_SIZE_1024 = 1024, + OPENSSL_RSA_KEY_SIZE_2048 = 2048, + OPENSSL_RSA_KEY_SIZE_3072 = 3072, + OPENSSL_RSA_KEY_SIZE_4096 = 4096, + OPENSSL_RSA_KEY_SIZE_8192 = 8192, +}; + +enum OpensslRsaPrimesSize { + OPENSSL_RSA_PRIMES_SIZE_2 = 2, + OPENSSL_RSA_PRIMES_SIZE_3 = 3, + OPENSSL_RSA_PRIMES_SIZE_4 = 4, + OPENSSL_RSA_PRIMES_SIZE_5 = 5, +}; + +typedef struct { + uint32_t keySize; + + uint32_t nSize; + + uint32_t eSize; + + uint32_t dSize; +} KeyMaterialRsa; + +typedef struct { + int32_t bits; + int32_t primes; + BIGNUM *pubExp; +} HcfAsyKeyGenSpiRsaParams; + +typedef struct { + HcfAsyKeyGeneratorSpi base; + + HcfAsyKeyGenSpiRsaParams *params; +} HcfAsyKeyGeneratorSpiRsaOpensslImpl; + +static HcfResult CheckRsaKeyGenParams(HcfAsyKeyGenSpiRsaParams *params) +{ + if (params->pubExp == NULL) { + LOGE("pubExp is NULL."); + return HCF_INVALID_PARAMS; + } + switch (params->bits) { + case OPENSSL_RSA_KEY_SIZE_512: + case OPENSSL_RSA_KEY_SIZE_768: + if (params->primes != OPENSSL_RSA_PRIMES_SIZE_2) { + LOGE("Set invalid primes %d to Keygen bits %d.", params->primes, params->bits); + return HCF_INVALID_PARAMS; + } + break; + case OPENSSL_RSA_KEY_SIZE_1024: + case OPENSSL_RSA_KEY_SIZE_2048: + case OPENSSL_RSA_KEY_SIZE_3072: + if (params->primes > OPENSSL_RSA_PRIMES_SIZE_3 || params->primes < OPENSSL_RSA_PRIMES_SIZE_2) { + LOGE("Set invalid primes %d to Keygen bits %d.", params->primes, params->bits); + return HCF_INVALID_PARAMS; + } + break; + case OPENSSL_RSA_KEY_SIZE_4096: + if (params->primes > OPENSSL_RSA_PRIMES_SIZE_4 || params->primes < OPENSSL_RSA_PRIMES_SIZE_2) { + LOGE("Set invalid primes %d to Keygen bits %d.", params->primes, params->bits); + return HCF_INVALID_PARAMS; + } + break; + case OPENSSL_RSA_KEY_SIZE_8192: + if (params->primes > OPENSSL_RSA_PRIMES_SIZE_5 || params->primes < OPENSSL_RSA_PRIMES_SIZE_2) { + LOGE("Set invalid primes %d to Keygen bits %d.", params->primes, params->bits); + return HCF_INVALID_PARAMS; + } + break; + default: + LOGE("The current bits %d is invalid.", params->bits); + return HCF_INVALID_PARAMS; + } + return HCF_SUCCESS; +} + +static HcfResult DuplicatePkAndSkFromRSA(const RSA *rsa, RSA **pubKey, RSA **priKey) +{ + if (rsa == NULL) { + LOGE("Rsa is NULL."); + return HCF_INVALID_PARAMS; + } + if (DuplicateRsa(rsa, false, pubKey) != HCF_SUCCESS) { + LOGE("Duplicate pubkey rsa fail"); + return HCF_ERR_CRYPTO_OPERATION; + } + if (DuplicateRsa(rsa, true, priKey) != HCF_SUCCESS) { + LOGE("Duplicate prikey rsa fail"); + RSA_free(*pubKey); + *pubKey = NULL; + return HCF_ERR_CRYPTO_OPERATION; + } + return HCF_SUCCESS; +} + +static const char *GetOpensslPubkeyClass() +{ + return OPENSSL_RSA_PUBKEY_CLASS; +} + +static const char *GetOpensslPrikeyClass() +{ + return OPENSSL_RSA_PRIKEY_CLASS; +} + +static const char *GetOpensslKeyPairClass() +{ + return OPENSSL_RSA_KEYPAIR_CLASS; +} + +static void DestroyPubKey(HcfObjectBase *self) +{ + if (self == NULL) { + LOGE("PubKey is NULL."); + return; + } + if (!IsClassMatch(self, OPENSSL_RSA_PUBKEY_CLASS)) { + LOGE("Class not match"); + return; + } + HcfOpensslRsaPubKey *impl = (HcfOpensslRsaPubKey *)self; + RSA_free(impl->pk); + impl->pk = NULL; + HcfFree(self); + self = NULL; +} + +static void DestroyPriKey(HcfObjectBase *self) +{ + if (self == NULL) { + LOGE("PubKey is NULL."); + return; + } + if (!IsClassMatch(self, OPENSSL_RSA_PRIKEY_CLASS)) { + LOGE("Class not match"); + return; + } + HcfOpensslRsaPriKey *impl = (HcfOpensslRsaPriKey*)self; + if (impl->sk != NULL) { + RSA_free(impl->sk); + impl->sk = NULL; + } + HcfFree(impl); + self = NULL; +} + +static void DestroyKeyPair(HcfObjectBase *self) +{ + if (self == NULL) { + LOGE("PubKey is NULL."); + return; + } + if (!IsClassMatch(self, OPENSSL_RSA_KEYPAIR_CLASS)) { + LOGE("Class not match"); + return; + } + HcfOpensslRsaKeyPair *impl = (HcfOpensslRsaKeyPair*)self; + OH_HCF_ObjDestroy((HcfObjectBase *)impl->base.priKey); + impl->base.priKey = NULL; + OH_HCF_ObjDestroy((HcfObjectBase *)impl->base.pubKey); + impl->base.pubKey = NULL; + HcfFree(self); + self = NULL; +} + +static HcfResult RsaSaveKeyMaterial(const RSA *rsa, const uint32_t keySize, HcfBlob *key, bool needPrivate) +{ + const uint32_t keyByteLen = keySize / OPENSSL_BITS_PER_BYTE; + const uint32_t rawMaterialLen = sizeof(KeyMaterialRsa) + keyByteLen * OPENSSL_RSA_KEYPAIR_CNT; + uint8_t *rawMaterial = (uint8_t *)HcfMalloc(rawMaterialLen, 0); + if (rawMaterial == NULL) { + LOGE("Malloc rawMaterial fail."); + return HCF_ERR_MALLOC; + } + KeyMaterialRsa *keyMaterial = (KeyMaterialRsa *)rawMaterial; + keyMaterial->keySize = keySize; + uint8_t *tmp_buff = (uint8_t *)HcfMalloc(sizeof(uint8_t) * keyByteLen, 0); + if (tmp_buff == NULL) { + HcfFree(rawMaterial); + return HCF_ERR_MALLOC; + } + HcfResult ret = HCF_SUCCESS; + uint32_t offset = sizeof(*keyMaterial); + keyMaterial->nSize = (uint32_t)BN_bn2bin(RSA_get0_n(rsa), tmp_buff); + if (memcpy_s(rawMaterial + offset, keyByteLen, tmp_buff, keyMaterial->nSize) != HCF_SUCCESS) { + LOGE("copy n fail"); + ret = HCF_ERR_CRYPTO_OPERATION; + goto ERR; + } + offset += keyMaterial->nSize; + keyMaterial->eSize = (uint32_t)BN_bn2bin(RSA_get0_e(rsa), tmp_buff); + if (memcpy_s(rawMaterial + offset, keyByteLen, tmp_buff, keyMaterial->eSize) != HCF_SUCCESS) { + LOGE("copy e fail"); + ret = HCF_ERR_CRYPTO_OPERATION; + goto ERR; + } + offset += keyMaterial->eSize; + if (needPrivate) { + keyMaterial->dSize = (uint32_t)BN_bn2bin(RSA_get0_d(rsa), tmp_buff); + if (memcpy_s(rawMaterial + offset, keyByteLen, tmp_buff, keyMaterial->dSize) != HCF_SUCCESS) { + LOGE("copy d fail"); + ret = HCF_ERR_CRYPTO_OPERATION; + goto ERR; + } + } + key->data = rawMaterial; + key->len = sizeof(KeyMaterialRsa) + keyMaterial->nSize + keyMaterial->eSize + keyMaterial->dSize; + HcfFree(tmp_buff); + return HCF_SUCCESS; +ERR: + HcfFree(keyMaterial); + HcfFree(tmp_buff); + return ret; +} + +static HcfResult GetPubKeyEncoded(HcfKey *self, HcfBlob *returnBlob) +{ + if (self == NULL || returnBlob == NULL) { + LOGE("Input params is invalid."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, OPENSSL_RSA_PUBKEY_CLASS)) { + LOGE("Class not match."); + return HCF_INVALID_PARAMS; + } + HcfOpensslRsaPubKey *impl = (HcfOpensslRsaPubKey *)self; + + return RsaSaveKeyMaterial(impl->pk, impl->bits, returnBlob, false); +} + +static HcfResult GetPriKeyEncoded(HcfKey *self, HcfBlob *returnBlob) +{ + if (self == NULL || returnBlob == NULL) { + LOGE("Key is null."); + return HCF_INVALID_PARAMS; + } + + if (!IsClassMatch((HcfObjectBase *)self, OPENSSL_RSA_PRIKEY_CLASS)) { + LOGE("Class not match."); + return HCF_INVALID_PARAMS; + } + HcfOpensslRsaPriKey *impl = (HcfOpensslRsaPriKey *)self; + + return RsaSaveKeyMaterial(impl->sk, impl->bits, returnBlob, true); +} + +static const char *GetKeyFormat() +{ + return OPENSSL_RSA_KEY_FORMAT; +} + +static const char *GetAlgorithm() +{ + return OPENSSL_RSA_ALGORITHM; +} + +static void ClearPriKeyMem(HcfPriKey *self) +{ + if (self == NULL) { + LOGE("PriKey is NULL."); + return; + } + if (!IsClassMatch((HcfObjectBase *)self, OPENSSL_RSA_PRIKEY_CLASS)) { + LOGE("Class not match"); + return; + } + RSA_free(((HcfOpensslRsaPriKey *)self)->sk); + ((HcfOpensslRsaPriKey *)self)->sk = NULL; +} + +static HcfResult PackPubKey(RSA *rsaPubKey, uint32_t bits, HcfOpensslRsaPubKey **retPubKey) +{ + if (retPubKey == NULL || rsaPubKey == NULL) { + LOGE("Invalid params"); + return HCF_INVALID_PARAMS; + } + *retPubKey = (HcfOpensslRsaPubKey *)HcfMalloc(sizeof(HcfOpensslRsaPubKey), 0); + if (*retPubKey == NULL) { + LOGE("Malloc retPubKey fail"); + return HCF_ERR_MALLOC; + } + (*retPubKey)->pk = rsaPubKey; + (*retPubKey)->bits = bits; + (*retPubKey)->base.base.getAlgorithm = GetAlgorithm; + (*retPubKey)->base.base.getEncoded = GetPubKeyEncoded; + (*retPubKey)->base.base.getFormat = GetKeyFormat; + (*retPubKey)->base.base.base.getClass = GetOpensslPubkeyClass; + (*retPubKey)->base.base.base.destroy = DestroyPubKey; + return HCF_SUCCESS; +} + +static HcfResult PackPriKey(RSA *rsaPriKey, uint32_t bits, HcfOpensslRsaPriKey **retPriKey) +{ + if (retPriKey == NULL || rsaPriKey == NULL) { + LOGE("Invalid params"); + return HCF_INVALID_PARAMS; + } + *retPriKey = (HcfOpensslRsaPriKey *)HcfMalloc(sizeof(HcfOpensslRsaPriKey), 0); + if (*retPriKey == NULL) { + LOGE("Malloc retPriKey fail"); + return HCF_ERR_MALLOC; + } + (*retPriKey)->sk = rsaPriKey; + (*retPriKey)->bits = bits; + (*retPriKey)->base.clearMem = ClearPriKeyMem; + (*retPriKey)->base.base.getAlgorithm = GetAlgorithm; + (*retPriKey)->base.base.getEncoded = GetPriKeyEncoded; + (*retPriKey)->base.base.getFormat = GetKeyFormat; + (*retPriKey)->base.base.base.getClass = GetOpensslPrikeyClass; + (*retPriKey)->base.base.base.destroy = DestroyPriKey; + return HCF_SUCCESS; +} + +static HcfResult PackKeyPair(RSA *rsa, uint32_t realBits, HcfOpensslRsaKeyPair **retKeyPair) +{ + if (retKeyPair == NULL || rsa == NULL) { + LOGE("Invalid params"); + return HCF_INVALID_PARAMS; + } + RSA *pubKey = NULL, *priKey = NULL; + if (DuplicatePkAndSkFromRSA(rsa, &pubKey, &priKey) != HCF_SUCCESS) { + LOGE("DuplicatePkAndSkFromRSA fail"); + return HCF_ERR_CRYPTO_OPERATION; + } + HcfResult ret = HCF_SUCCESS; + *retKeyPair = (HcfOpensslRsaKeyPair *)HcfMalloc(sizeof(HcfOpensslRsaKeyPair), 0); + if (*retKeyPair == NULL) { + LOGE("Malloc keypair fail"); + RSA_free(pubKey); + RSA_free(priKey); + return HCF_ERR_MALLOC; + } + HcfOpensslRsaPriKey *priKeyImpl = NULL; + HcfOpensslRsaPubKey *pubKeyImpl = NULL; + ret = PackPubKey(pubKey, realBits, &pubKeyImpl); + if (ret != HCF_SUCCESS) { + LOGE("Pack pubKey fail."); + goto ERR2; + } + ret = PackPriKey(priKey, realBits, &priKeyImpl); + if (ret != HCF_SUCCESS) { + LOGE("Pack priKey fail."); + goto ERR1; + } + (*retKeyPair)->base.priKey = (HcfPriKey *)priKeyImpl; + (*retKeyPair)->base.pubKey = (HcfPubKey *)pubKeyImpl; + (*retKeyPair)->base.base.getClass = GetOpensslKeyPairClass; + (*retKeyPair)->base.base.destroy = DestroyKeyPair; + return HCF_SUCCESS; +ERR1: + HcfFree(pubKeyImpl); +ERR2: + RSA_free(pubKey); + RSA_free(priKey); + HcfFree(*retKeyPair); + *retKeyPair = NULL; + return ret; +} + +static HcfResult GenerateKeyPairByOpenssl(HcfAsyKeyGenSpiRsaParams *params, HcfKeyPair **keyPair) +{ + // check input params is valid + HcfResult res = CheckRsaKeyGenParams(params); + if (res != HCF_SUCCESS) { + LOGE("Rsa CheckRsaKeyGenParams fail."); + return HCF_INVALID_PARAMS; + } + // Generate keyPair RSA + RSA *rsa = RSA_new(); + if (rsa == NULL) { + LOGE("new RSA fail."); + return HCF_ERR_MALLOC; + } + LOGI("keygen bits is %d, primes is %d", params->bits, GetRealPrimes(params->primes)); + if (GetRealPrimes(params->primes) != OPENSSL_RSA_KEYGEN_DEFAULT_PRIMES) { + if (RSA_generate_multi_prime_key(rsa, params->bits, GetRealPrimes(params->primes), params->pubExp, NULL) + != HCF_OPENSSL_SUCCESS) { + LOGE("Generate multi-primes rsa key fail"); + HcfPrintOpensslError(); + RSA_free(rsa); + return HCF_ERR_CRYPTO_OPERATION; + } + } else { + if (RSA_generate_key_ex(rsa, params->bits, params->pubExp, NULL) != HCF_OPENSSL_SUCCESS) { + LOGE("Generate rsa key fail"); + HcfPrintOpensslError(); + RSA_free(rsa); + return HCF_ERR_CRYPTO_OPERATION; + } + } + + // devided to pk and sk; + HcfOpensslRsaKeyPair *keyPairImpl = NULL; + res = PackKeyPair(rsa, params->bits, &keyPairImpl); + if (res != HCF_SUCCESS) { + LOGE("Generate keyPair fail."); + RSA_free(rsa); + return res; + } + *keyPair = (HcfKeyPair *)keyPairImpl; + RSA_free(rsa); + LOGI("Generate keypair success."); + return res; +} + +static HcfResult EngineGenerateKeyPair(HcfAsyKeyGeneratorSpi *self, HcfKeyPair **keyPair) +{ + LOGI("EngineGenerateKeyPair start"); + if (self == NULL || keyPair == NULL) { + LOGE("Invalid params."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, OPENSSL_RSA_GENERATOR_CLASS)) { + LOGE("Class not match."); + return HCF_INVALID_PARAMS; + } + HcfAsyKeyGeneratorSpiRsaOpensslImpl *impl = (HcfAsyKeyGeneratorSpiRsaOpensslImpl *)self; + return GenerateKeyPairByOpenssl(impl->params, keyPair); +} + +static const char *GetKeyGeneratorClass() +{ + return OPENSSL_RSA_GENERATOR_CLASS; +} + +static void DestroyKeyGeneratorSpiImpl(HcfObjectBase *self) +{ + LOGI("DestroyKeyGeneratorSpiImpl start."); + if (self == NULL) { + LOGE("DestroyKeyGeneratorSpiImpl is null"); + return; + } + if (!IsClassMatch(self, OPENSSL_RSA_GENERATOR_CLASS)) { + LOGE("Class not match."); + return; + } + // destroy pubExp first. + HcfAsyKeyGeneratorSpiRsaOpensslImpl *impl = (HcfAsyKeyGeneratorSpiRsaOpensslImpl *)self; + if (impl->params != NULL && impl->params->pubExp != NULL) { + BN_free(impl->params->pubExp); + } + HcfFree(impl->params); + impl->params = NULL; + HcfFree(self); + self = NULL; + LOGI("DestroyKeyGeneratorSpiImpl end."); +} + +static HcfResult InitRsaKeyBuf(const KeyMaterialRsa *keyMaterial, HcfBlob *bufBlob) +{ + uint32_t maxSize; + if (keyMaterial->nSize >= keyMaterial->eSize) { + maxSize = keyMaterial->nSize; + } else { + maxSize = keyMaterial->eSize; + } + + if (maxSize < keyMaterial->dSize) { + maxSize = keyMaterial->dSize; + } + + bufBlob->data = (uint8_t *)HcfMalloc(maxSize, 0); + if (bufBlob->data == NULL) { + LOGE("HcfMalloc failed!"); + return HCF_ERR_MALLOC; + } + bufBlob->len = maxSize; + return HCF_SUCCESS; +} + +static HcfResult ParseRsaBnFromBin(const HcfBlob *key, BIGNUM **n, BIGNUM **e, BIGNUM **d, const bool needPrivate) +{ + const KeyMaterialRsa *keyMaterial = (KeyMaterialRsa *)(key->data); + HcfBlob bufBlob = { .len = 0, .data = NULL }; + HcfResult ret = InitRsaKeyBuf(keyMaterial, &bufBlob); + if (ret != HCF_SUCCESS) { + return ret; + } + ret = HCF_SUCCESS; + do { + uint32_t offset = sizeof(*keyMaterial); + if (memcpy_s(bufBlob.data, bufBlob.len, key->data + offset, keyMaterial->nSize) != HCF_SUCCESS) { + LOGE("memcpy_s n bin data fail"); + ret = HCF_ERR_COPY; + break; + } + *n = BN_bin2bn(bufBlob.data, keyMaterial->nSize, NULL); + offset += keyMaterial->nSize; + if (memcpy_s(bufBlob.data, bufBlob.len, key->data + offset, keyMaterial->eSize) != HCF_SUCCESS) { + LOGE("memcpy_s e bin data fail"); + ret = HCF_ERR_COPY; + break; + } + *e = BN_bin2bn(bufBlob.data, keyMaterial->eSize, NULL); + offset += keyMaterial->eSize; + *d = NULL; + if (needPrivate) { + if (memcpy_s(bufBlob.data, bufBlob.len, key->data + offset, keyMaterial->dSize) != HCF_SUCCESS) { + LOGE("memcpy_s d bin data fail"); + ret = HCF_ERR_COPY; + break; + } + *d = BN_bin2bn(bufBlob.data, keyMaterial->dSize, NULL); + } + } while (0); + (void)memset_s(bufBlob.data, bufBlob.len, 0, + (((keyMaterial->keySize) + OPENSSL_BITS_PER_BYTE - 1) / OPENSSL_BITS_PER_BYTE)); + HcfFree(bufBlob.data); + return ret; +} + +static RSA *InitRsaStructByBin(const HcfBlob *key, const bool needPrivateExponent) +{ + BIGNUM *n = NULL; + BIGNUM *e = NULL; + BIGNUM *d = NULL; + + RSA *rsa = NULL; + do { + if (ParseRsaBnFromBin(key, &n, &e, &d, needPrivateExponent) != HCF_SUCCESS) { + LOGE("ParseRsaBnFromBin fail"); + break; + } + rsa = RSA_new(); + if (rsa != NULL) { + if (RSA_set0_key(rsa, n, e, d) != HCF_OPENSSL_SUCCESS) { + LOGE("set rsa Bn fail"); + HcfPrintOpensslError(); + RSA_free(rsa); + rsa = NULL; + break; + } + } + } while (0); + + if (rsa == NULL) { + BN_clear_free(n); + BN_clear_free(e); + BN_clear_free(d); + } + + return rsa; +} + +static HcfResult RsaCheckKeyMaterial(const HcfBlob *key) +{ + const KeyMaterialRsa *keyMaterial = (KeyMaterialRsa *)(key->data); + if ((keyMaterial->keySize < MIN_KEY_SIZE) || (keyMaterial->keySize > MAX_KEY_SIZE)) { + LOGE("Input keySize is invalid"); + return HCF_INVALID_PARAMS; + } + if (key->len != sizeof(KeyMaterialRsa) + keyMaterial->nSize + keyMaterial->eSize + keyMaterial->dSize) { + LOGE("Input len dismatch with data"); + return HCF_INVALID_PARAMS; + } + return HCF_SUCCESS; +} + +static HcfResult ConvertPubKey(HcfBlob *pubKeyBlob, HcfOpensslRsaPubKey **pubkeyRet) +{ + if ((pubKeyBlob == NULL) || (pubKeyBlob->data == NULL)) { + LOGE("PubKeyBlob is NULL."); + return HCF_INVALID_PARAMS; + } + if (RsaCheckKeyMaterial(pubKeyBlob) != HCF_SUCCESS) { + LOGE("check input key material fail"); + return HCF_INVALID_PARAMS; + } + + RSA *rsaPk = InitRsaStructByBin(pubKeyBlob, false); + if (rsaPk == NULL) { + LOGE("Init rsaPk fail."); + return HCF_ERR_MALLOC; + } + KeyMaterialRsa *keyMaterial = (KeyMaterialRsa *)(pubKeyBlob->data); + HcfOpensslRsaPubKey *pubKey = NULL; + HcfResult ret = PackPubKey(rsaPk, keyMaterial->keySize, &pubKey); + if (ret != HCF_SUCCESS) { + LOGE("PackPubKey fail"); + goto ERR; + } + *pubkeyRet = pubKey; + return ret; +ERR: + RSA_free(rsaPk); + return ret; +} + +static HcfResult ConvertPriKey(HcfBlob *priKeyBlob, HcfOpensslRsaPriKey **priKeyRet) +{ + if (priKeyBlob == NULL || priKeyBlob->data == NULL) { + LOGE("PriKeyBlob is NULL."); + return HCF_INVALID_PARAMS; + } + if (RsaCheckKeyMaterial(priKeyBlob) != HCF_SUCCESS) { + LOGE("check input key material fail"); + return HCF_INVALID_PARAMS; + } + RSA *rsaSk = InitRsaStructByBin(priKeyBlob, true); + if (rsaSk == NULL) { + LOGE("Init rsaSk fail."); + return HCF_ERR_MALLOC; + } + KeyMaterialRsa *keyMaterial = (KeyMaterialRsa *)(priKeyBlob->data); + HcfOpensslRsaPriKey *priKey = NULL; + HcfResult ret = PackPriKey(rsaSk, keyMaterial->keySize, &priKey); + if (ret != HCF_SUCCESS) { + LOGE("PackPriKey fail"); + goto ERR; + } + *priKeyRet = priKey; + return ret; +ERR: + RSA_free(rsaSk); + return ret; +} + +static HcfResult EngineConvertKey(HcfAsyKeyGeneratorSpi *self, HcfParamsSpec *params, HcfBlob *pubKeyBlob, + HcfBlob *priKeyBlob, HcfKeyPair **returnKeyPair) +{ + LOGI("EngineConvertKey start"); + (void)params; + if ((self == NULL) || (returnKeyPair == NULL) || ((pubKeyBlob == NULL) && (priKeyBlob == NULL))) { + LOGE("ConvertKeyParams is invalid."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((HcfObjectBase *)self, OPENSSL_RSA_GENERATOR_CLASS)) { + LOGE("Class not match."); + return HCF_INVALID_PARAMS; + } + + HcfOpensslRsaPubKey *pubKey = NULL; + if ((pubKeyBlob != NULL) && (pubKeyBlob->data != NULL)) { + if (ConvertPubKey(pubKeyBlob, &pubKey) != HCF_SUCCESS) { + LOGE("convert pubkey fail."); + return HCF_INVALID_PARAMS; + } + } + + HcfOpensslRsaPriKey *priKey = NULL; + if (priKeyBlob != NULL && priKeyBlob->data != NULL) { + if (ConvertPriKey(priKeyBlob, &priKey) != HCF_SUCCESS) { + LOGE("convert prikey fail."); + OH_HCF_ObjDestroy((HcfObjectBase *)pubKey); + return HCF_INVALID_PARAMS; + } + } + + HcfOpensslRsaKeyPair *keyPair = (HcfOpensslRsaKeyPair *)HcfMalloc(sizeof(HcfOpensslRsaKeyPair), 0); + if (keyPair == NULL) { + LOGE("Malloc keyPair fail."); + OH_HCF_ObjDestroy((HcfObjectBase *)pubKey); + OH_HCF_ObjDestroy((HcfObjectBase *)priKey); + return HCF_ERR_MALLOC; + } + + keyPair->base.priKey = (HcfPriKey *)priKey; + keyPair->base.pubKey = (HcfPubKey *)pubKey; + keyPair->base.base.getClass = GetOpensslKeyPairClass; + keyPair->base.base.destroy = DestroyKeyPair; + *returnKeyPair = (HcfKeyPair *)keyPair; + LOGI("EngineConvertKey end"); + return HCF_SUCCESS; +} + +static HcfResult SetDefaultValue(HcfAsyKeyGenSpiRsaParams *params) +{ + if (params->primes == 0) { + LOGI("set default primes 2"); + params->primes = OPENSSL_RSA_PRIMES_SIZE_2; + } + if (params->pubExp == NULL) { + BIGNUM *e = BN_new(); + if (e == NULL) { + LOGE("Rsa new BN fail."); + return HCF_ERR_CRYPTO_OPERATION; + } + if (BN_set_word(e, RSA_F4) != HCF_OPENSSL_SUCCESS) { + LOGE("Rsa keygen Bn_set_word fail."); + BN_free(e); + return HCF_ERR_CRYPTO_OPERATION; + } + params->pubExp = e; + } + return HCF_SUCCESS; +} + +static HcfResult DecodeParams(HcfAsyKeyGenParams *from, HcfAsyKeyGenSpiRsaParams **to) +{ + *to = (HcfAsyKeyGenSpiRsaParams *)HcfMalloc(sizeof(HcfAsyKeyGenSpiRsaParams), 0); + if (*to == NULL) { + LOGE("Malloc HcfAsyKeyGenSpiRsaParams fail"); + return HCF_ERR_MALLOC; + } + + (*to)->bits = from->bits; + (*to)->primes = from->primes; + + // set 2 as default primes, RSA_F4 as default pubExp + if (SetDefaultValue(*to) != HCF_SUCCESS) { + LOGE("Set default value fail."); + HcfFree(*to); + *to = NULL; + return HCF_INVALID_PARAMS; + } + if (CheckRsaKeyGenParams(*to) != HCF_SUCCESS) { + LOGE("Invalid keyGen params"); + HcfFree(*to); + *to = NULL; + return HCF_INVALID_PARAMS; + } + return HCF_SUCCESS; +} + +HcfResult HcfAsyKeyGeneratorSpiRsaCreate(HcfAsyKeyGenParams *params, HcfAsyKeyGeneratorSpi **generator) +{ + LOGI("HcfAsyKeyGeneratorSpiRsaCreate start."); + if (params == NULL || generator == NULL) { + LOGE("Invalid input, params is invalid or generator is null."); + return HCF_INVALID_PARAMS; + } + HcfAsyKeyGeneratorSpiRsaOpensslImpl *impl = (HcfAsyKeyGeneratorSpiRsaOpensslImpl *) + HcfMalloc(sizeof(HcfAsyKeyGeneratorSpiRsaOpensslImpl), 0); + if (impl == NULL) { + LOGE("Failed to allocate returnImpl memroy!"); + return HCF_ERR_MALLOC; + } + if (DecodeParams(params, &impl->params) != HCF_SUCCESS) { + LOGE("Keygen params is invalid."); + HcfFree(impl); + return HCF_INVALID_PARAMS; + } + impl->base.base.getClass = GetKeyGeneratorClass; + impl->base.base.destroy = DestroyKeyGeneratorSpiImpl; + impl->base.engineGenerateKeyPair = EngineGenerateKeyPair; + impl->base.engineConvertKey = EngineConvertKey; + *generator = (HcfAsyKeyGeneratorSpi *)impl; + LOGI("HcfAsyKeyGeneratorSpiRsaCreate end."); + return HCF_SUCCESS; +} diff --git a/plugin/openssl_plugin/key/sym_key_generator/inc/sym_common_defines.h b/plugin/openssl_plugin/key/sym_key_generator/inc/sym_common_defines.h new file mode 100644 index 0000000..7c1b8d9 --- /dev/null +++ b/plugin/openssl_plugin/key/sym_key_generator/inc/sym_common_defines.h @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2022 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_factory_spi.h" +#include "sym_key.h" +#include "params_parser.h" + +typedef struct { + HCF_ALG_VALUE algo; + int keySize; +} SymKeyAttr; + +typedef struct { + HcfSymKey key; + char *algoName; + HcfBlob keyMaterial; +} SymKeyImpl; + +#ifdef __cplusplus +extern "C" { +#endif + +HcfResult HcfSymKeyGeneratorSpiCreate(SymKeyAttr *attr, OH_HCF_SymKeyGeneratorSpi **genertor); + +#ifdef __cplusplus +} +#endif + diff --git a/plugin/openssl_plugin/key/sym_key_generator/src/sym_key_openssl.c b/plugin/openssl_plugin/key/sym_key_generator/src/sym_key_openssl.c new file mode 100644 index 0000000..04c743c --- /dev/null +++ b/plugin/openssl_plugin/key/sym_key_generator/src/sym_key_openssl.c @@ -0,0 +1,320 @@ +/* + * Copyright (C) 2022 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 "log.h" +#include "memory.h" +#include "result.h" +#include "securec.h" +#include "utils.h" +#include "sym_common_defines.h" +#include "openssl_common.h" + +#define MAX_KEY_STR_SIZE 12 +#define MAX_KEY_LEN 4096 +#define KEY_BIT 8 +#define AES_ALG_NAME "AES" +#define DES_ALG_NAME "3DES" + +typedef struct { + OH_HCF_SymKeyGeneratorSpi base; + SymKeyAttr attr; +} HcfSymKeyGeneratorSpiOpensslImpl; + +static HcfResult GetEncoded(HcfKey *self, HcfBlob *key) +{ + if ((self == NULL) || (key == NULL)) { + LOGE("Invalid input parameter!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((const HcfObjectBase *)self, OPENSSL_SYM_KEY_CLASS)) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + SymKeyImpl *impl = (SymKeyImpl *)self; + if ((impl->keyMaterial.data == NULL) || (impl->keyMaterial.len == 0)) { + LOGE("Invalid SymKeyImpl parameter!"); + return HCF_INVALID_PARAMS; + } + key->data = (uint8_t *)HcfMalloc(impl->keyMaterial.len, 0); + if (key->data == NULL) { + LOGE("malloc keyMaterial failed!"); + return HCF_ERR_MALLOC; + } + (void)memcpy_s(key->data, impl->keyMaterial.len, impl->keyMaterial.data, impl->keyMaterial.len); + key->len = impl->keyMaterial.len; + return HCF_SUCCESS; +} + +static const char *GetFormat(HcfKey *self) +{ + if (self == NULL) { + LOGE("Invalid input parameter!"); + return NULL; + } + if (!IsClassMatch((const HcfObjectBase *)self, OPENSSL_SYM_KEY_CLASS)) { + LOGE("Class is not match."); + return NULL; + } + + return "PKCS#8"; +} + +static const char *GetSymKeyGeneratorClass(void) +{ + return OPENSSL_SYM_GENERATOR_CLASS; +} + +static const char *GetSymKeyClass(void) +{ + return OPENSSL_SYM_KEY_CLASS; +} + +static const char *GetAlgorithm(HcfKey *self) +{ + if (self == NULL) { + LOGE("Invalid input parameter!"); + return NULL; + } + if (!IsClassMatch((const HcfObjectBase *)self, OPENSSL_SYM_KEY_CLASS)) { + LOGE("Class is not match."); + return NULL; + } + SymKeyImpl *impl = (SymKeyImpl *)self; + return (const char *)impl->algoName; +} + +static HcfResult RandomSymmKey(int32_t keyLen, HcfBlob *symmKey) +{ + uint8_t *keyMaterial = (uint8_t *)HcfMalloc(keyLen, 0); + if (keyMaterial == NULL) { + LOGE("keyMaterial malloc failed!"); + return HCF_ERR_MALLOC; + } + int ret = RAND_bytes(keyMaterial, keyLen); + if (ret != HCF_OPENSSL_SUCCESS) { + LOGE("RAND_bytes failed!"); + HcfPrintOpensslError(); + HcfFree(keyMaterial); + return HCF_ERR_CRYPTO_OPERATION; + } + symmKey->data = keyMaterial; + symmKey->len = keyLen; + return HCF_SUCCESS; +} + +static HcfResult HcfSymmKeySpiCreate(int32_t keyLen, SymKeyImpl *symKey) +{ + if ((keyLen == 0) || (symKey == NULL)) { + LOGE("Invalid input parameter!"); + return HCF_INVALID_PARAMS; + } + int32_t res = RandomSymmKey(keyLen, &symKey->keyMaterial); + if (res != HCF_SUCCESS) { + LOGE("RandomSymmKey failed!"); + return res; + } + return res; +} + +static void DestroySymKeyGeneratorSpi(HcfObjectBase *base) +{ + if (base == NULL) { + LOGE("Invalid input parameter!"); + return; + } + if (!IsClassMatch(base, GetSymKeyGeneratorClass())) { + LOGE("Class is not match!"); + return; + } + HcfFree(base); + base = NULL; +} + +static void DestroySymKeySpi(HcfObjectBase *base) +{ + if (base == NULL) { + LOGE("Invalid input parameter!"); + return; + } + if (!IsClassMatch(base, OPENSSL_SYM_KEY_CLASS)) { + LOGE("Class is not match."); + return; + } + SymKeyImpl *impl = (SymKeyImpl *)base; + if (impl->algoName != NULL) { + HcfFree(impl->algoName); + impl->algoName = NULL; + } + if (impl->keyMaterial.data != NULL) { + (void)memset_s(impl->keyMaterial.data, impl->keyMaterial.len, 0, impl->keyMaterial.len); + HcfFree(impl->keyMaterial.data); + impl->keyMaterial.data = NULL; + impl->keyMaterial.len = 0; + } + HcfFree(impl); + impl = NULL; +} + +static char *GetAlgoName(HcfSymKeyGeneratorSpiOpensslImpl *impl) +{ + char keySizeChar[MAX_KEY_STR_SIZE] = { 0 }; + if (sprintf_s(keySizeChar, MAX_KEY_STR_SIZE, "%d", impl->attr.keySize) < 0) { + LOGE("Invalid input parameter!"); + return NULL; + } + + char *algoName = (char *)HcfMalloc(MAX_KEY_STR_SIZE, 0); + if (algoName == NULL) { + LOGE("algoName malloc failed!"); + return NULL; + } + int32_t aesSize = strlen(AES_ALG_NAME); + int32_t desSize = strlen(DES_ALG_NAME); + HCF_ALG_VALUE type = impl->attr.algo; + if (type == HCF_ALG_AES) { + if (strcpy_s(algoName, MAX_KEY_STR_SIZE, AES_ALG_NAME) != EOK) { + LOGE("aes algoName strcpy_s failed!"); + goto clearup; + } + if (strcpy_s(algoName + aesSize, MAX_KEY_STR_SIZE - aesSize, keySizeChar) != EOK) { + LOGE("aes algoName size strcpy_s failed!"); + goto clearup; + } + } else if (type == HCF_ALG_DES) { + if (strcpy_s(algoName, MAX_KEY_STR_SIZE, DES_ALG_NAME) != EOK) { + LOGE("des algoName strcpy_s failed!"); + goto clearup; + } + if (strcpy_s(algoName + desSize, MAX_KEY_STR_SIZE - desSize, keySizeChar) != EOK) { + LOGE("des algoName size strcpy_s failed!"); + goto clearup; + } + } else { + LOGE("unsupport algo!"); + goto clearup; + } + return algoName; +clearup: + HcfFree(algoName); + return NULL; +} + +static HcfResult CopySymmKey(const HcfBlob *srcKey, HcfBlob *dstKey) +{ + if ((srcKey->data == NULL) || (srcKey->len == 0)) { + LOGE("Invalid input parameter!"); + return HCF_INVALID_PARAMS; + } + uint8_t *keyMaterial = (uint8_t *)HcfMalloc(srcKey->len, 0); + if (keyMaterial == NULL) { + LOGE("keyMaterial malloc failed!"); + return HCF_ERR_MALLOC; + } + (void)memcpy_s(keyMaterial, srcKey->len, srcKey->data, srcKey->len); + dstKey->data = keyMaterial; + dstKey->len = srcKey->len; + return HCF_SUCCESS; +} + +static HcfResult GenerateSymmKey(OH_HCF_SymKeyGeneratorSpi *self, HcfSymKey **symmKey) +{ + if ((self == NULL) || (symmKey == NULL)) { + LOGE("Invalid input parameter!"); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((const HcfObjectBase *)self, GetSymKeyGeneratorClass())) { + LOGE("Class is not match!"); + return HCF_INVALID_PARAMS; + } + SymKeyImpl *returnSymmKey = (SymKeyImpl *)HcfMalloc(sizeof(SymKeyImpl), 0); + if (returnSymmKey == NULL) { + LOGE("Failed to allocate returnKeyPair memory!"); + return HCF_ERR_MALLOC; + } + HcfSymKeyGeneratorSpiOpensslImpl *impl = (HcfSymKeyGeneratorSpiOpensslImpl *)self; + int32_t res = HcfSymmKeySpiCreate(impl->attr.keySize / KEY_BIT, returnSymmKey); + if (res != HCF_SUCCESS) { + HcfFree(returnSymmKey); + return res; + } + returnSymmKey->algoName = GetAlgoName(impl); + returnSymmKey->key.key.getEncoded = GetEncoded; + returnSymmKey->key.key.getFormat = GetFormat; + returnSymmKey->key.key.getAlgorithm = GetAlgorithm; + returnSymmKey->key.key.base.destroy = DestroySymKeySpi; + returnSymmKey->key.key.base.getClass = GetSymKeyClass; + *symmKey = (HcfSymKey *)returnSymmKey; + return HCF_SUCCESS; +} + +static HcfResult ConvertSymmKey(OH_HCF_SymKeyGeneratorSpi *self, const HcfBlob *key, HcfSymKey **symmKey) +{ + if ((self == NULL) || (symmKey == NULL) || !IsBlobValid(key)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + if (!IsClassMatch((const HcfObjectBase *)self, GetSymKeyGeneratorClass())) { + LOGE("Class is not match."); + return HCF_INVALID_PARAMS; + } + HcfSymKeyGeneratorSpiOpensslImpl *impl = (HcfSymKeyGeneratorSpiOpensslImpl *)self; + + if ((key->len == 0) || (key->len > MAX_KEY_LEN) || ((impl->attr.keySize / KEY_BIT) != (int32_t)key->len)) { + LOGE("Invalid param: input key length is invalid!"); + return HCF_INVALID_PARAMS; + } + + SymKeyImpl *returnSymmKey = (SymKeyImpl *)HcfMalloc(sizeof(SymKeyImpl), 0); + if (returnSymmKey == NULL) { + LOGE("Failed to allocate returnKeyPair memory!"); + return HCF_ERR_MALLOC; + } + int32_t res = CopySymmKey(key, &returnSymmKey->keyMaterial); + if (res != HCF_SUCCESS) { + HcfFree(returnSymmKey); + return res; + } + returnSymmKey->algoName = GetAlgoName(impl); + returnSymmKey->key.key.getEncoded = GetEncoded; + returnSymmKey->key.key.getFormat = GetFormat; + returnSymmKey->key.key.getAlgorithm = GetAlgorithm; + returnSymmKey->key.key.base.destroy = DestroySymKeySpi; + returnSymmKey->key.key.base.getClass = GetSymKeyClass; + *symmKey = (HcfSymKey *)returnSymmKey; + return HCF_SUCCESS; +} + +HcfResult HcfSymKeyGeneratorSpiCreate(SymKeyAttr *attr, OH_HCF_SymKeyGeneratorSpi **generator) +{ + if ((attr == NULL) || (generator == NULL)) { + LOGE("Invalid input parameter."); + return HCF_INVALID_PARAMS; + } + HcfSymKeyGeneratorSpiOpensslImpl *returnGenerator = (HcfSymKeyGeneratorSpiOpensslImpl *)HcfMalloc( + sizeof(HcfSymKeyGeneratorSpiOpensslImpl), 0); + if (returnGenerator == NULL) { + LOGE("Failed to allocate returnGenerator memory!"); + return HCF_ERR_MALLOC; + } + (void)memcpy_s(&returnGenerator->attr, sizeof(SymKeyAttr), attr, sizeof(SymKeyAttr)); + returnGenerator->base.engineGenerateSymmKey = GenerateSymmKey; + returnGenerator->base.engineConvertSymmKey = ConvertSymmKey; + returnGenerator->base.base.destroy = DestroySymKeyGeneratorSpi; + returnGenerator->base.base.getClass = GetSymKeyGeneratorClass; + *generator = (OH_HCF_SymKeyGeneratorSpi *)returnGenerator; + return HCF_SUCCESS; +} + diff --git a/plugin/openssl_plugin/rand/inc/rand_openssl.h b/plugin/openssl_plugin/rand/inc/rand_openssl.h new file mode 100644 index 0000000..83a1e22 --- /dev/null +++ b/plugin/openssl_plugin/rand/inc/rand_openssl.h @@ -0,0 +1,26 @@ +/* + * Copyright (C) 2022 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 "rand_spi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +HcfResult HcfRandSpiCreate(HcfRandSpi **spiObj); + +#ifdef __cplusplus +} +#endif diff --git a/plugin/openssl_plugin/rand/src/rand_openssl.c b/plugin/openssl_plugin/rand/src/rand_openssl.c new file mode 100644 index 0000000..da411b6 --- /dev/null +++ b/plugin/openssl_plugin/rand/src/rand_openssl.c @@ -0,0 +1,101 @@ +/* + * Copyright (C) 2022 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 "rand_openssl.h" + +#include "openssl_common.h" +#include "securec.h" +#include "log.h" +#include "memory.h" +#include "utils.h" + +#include + +typedef struct { + HcfRandSpi base; +} HcfRandSpiImpl; + +static const char *GetRandOpenSSLClass(void) +{ + return "RandOpenssl"; +} + +static HcfResult OpensslGenerateRandom(HcfRandSpi *self, int32_t numBytes, HcfBlob *random) +{ + unsigned char rand_buf[numBytes]; + int32_t ret = RAND_bytes(rand_buf, numBytes); + if (ret != HCF_OPENSSL_SUCCESS) { + LOGE("RAND_bytes return error!"); + HcfPrintOpensslError(); + return HCF_ERR_CRYPTO_OPERATION; + } + random->data = (uint8_t *)HcfMalloc(numBytes, 0); + if (random->data == NULL) { + LOGE("Failed to allocate random->data memory!"); + return HCF_ERR_MALLOC; + } + if (memcpy_s(random->data, numBytes, rand_buf, numBytes) != EOK) { + LOGE("memcpy error!"); + HcfFree(random->data); + random->data = NULL; + return HCF_ERR_COPY; + } + random->len = numBytes; + return HCF_SUCCESS; +} + +static HcfResult OpensslSetSeed(HcfRandSpi *self, HcfBlob *seed) +{ + int32_t seedLen = seed->len; + unsigned char seedBuf[seedLen]; + if (memcpy_s(seedBuf, seedLen, seed->data, seedLen) != EOK) { + LOGE("memcpy error!"); + return HCF_ERR_COPY; + } + RAND_seed(seedBuf, seedLen); + return HCF_SUCCESS; +} + +static void DestroyRandOpenssl(HcfObjectBase *self) +{ + if (self == NULL) { + LOGE("Self ptr is NULL!"); + return; + } + if (!IsClassMatch(self, GetRandOpenSSLClass())) { + LOGE("Class is not match."); + return; + } + HcfFree(self); +} + +HcfResult HcfRandSpiCreate(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 returnImpl memory!"); + return HCF_ERR_MALLOC; + } + returnSpiImpl->base.base.getClass = GetRandOpenSSLClass; + returnSpiImpl->base.base.destroy = DestroyRandOpenssl; + returnSpiImpl->base.engineGenerateRandom = OpensslGenerateRandom; + returnSpiImpl->base.engineSetSeed = OpensslSetSeed; + *spiObj = (HcfRandSpi *)returnSpiImpl; + return HCF_SUCCESS; +} \ No newline at end of file diff --git a/plugin/plugin.gni b/plugin/plugin.gni new file mode 100644 index 0000000..1db4d1e --- /dev/null +++ b/plugin/plugin.gni @@ -0,0 +1,86 @@ +# Copyright (C) 2022 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. + +base_path = "//base/security/crypto_framework" + +plugin_path = "//base/security/crypto_framework/plugin" + +plugin_inc_path = [ + "${base_path}/interfaces/innerkits/common", + "${plugin_path}/openssl_plugin/certificate/inc", + "${plugin_path}/openssl_plugin/common/inc", + "${plugin_path}/openssl_plugin/key/asy_key_generator/inc", + "${plugin_path}/openssl_plugin/key/sym_key_generator/inc", + "${plugin_path}/openssl_plugin/crypto_operation/aes/inc", + "${plugin_path}/openssl_plugin/crypto_operation/hmac/inc", + "${plugin_path}/openssl_plugin/crypto_operation/key_agreement/inc", + "${plugin_path}/openssl_plugin/crypto_operation/signature/inc", + "${plugin_path}/openssl_plugin/crypto_operation/md/inc", + "${plugin_path}/openssl_plugin/crypto_operation/rsa/inc", + "${plugin_path}/openssl_plugin/rand/inc", + "//base/security/crypto_framework/frameworks/spi", + "//base/security/crypto_framework/common/inc", +] + +plugin_signature_files = [ + "${plugin_path}/openssl_plugin/crypto_operation/signature/src/ecdsa_openssl.c", + "${plugin_path}/openssl_plugin/crypto_operation/signature/src/signature_rsa_openssl.c", +] + +plugin_common_files = [ + "${plugin_path}/openssl_plugin/common/src/openssl_common.c", + "${plugin_path}/openssl_plugin/common/src/rsa_openssl_common.c", +] + +plugin_asy_key_generator_files = [ + "${plugin_path}/openssl_plugin/key/asy_key_generator/src/ecc_asy_key_generator_openssl.c", + "${plugin_path}/openssl_plugin/key/asy_key_generator/src/rsa_asy_key_generator_openssl.c", +] + +plugin_key_agreement_files = [ + "${plugin_path}/openssl_plugin/crypto_operation/key_agreement/src/ecdh_openssl.c", +] + +plugin_certificate_files = [ + "${plugin_path}/openssl_plugin/certificate/src/x509_cert_chain_validator_openssl.c", + "${plugin_path}/openssl_plugin/certificate/src/x509_certificate_openssl.c", + "${plugin_path}/openssl_plugin/certificate/src/x509_crl_openssl.c", + "${plugin_path}/openssl_plugin/certificate/src/x509_crl_entry_openssl.c", +] + +plugin_sym_key_files = [ + "${plugin_path}/openssl_plugin/key/sym_key_generator/src/sym_key_openssl.c", +] + +plugin_cipher_files = [ + "${plugin_path}/openssl_plugin/crypto_operation/rsa/src/cipher_rsa_openssl.c", + "${plugin_path}/openssl_plugin/crypto_operation/aes/src/cipher_3des_openssl.c", + "${plugin_path}/openssl_plugin/crypto_operation/aes/src/cipher_aes_openssl.c", + "${plugin_path}/openssl_plugin/crypto_operation/aes/src/cipher_aes_common.c", +] + +plugin_hmac_files = [ + "${plugin_path}/openssl_plugin/crypto_operation/hmac/src/mac_openssl.c", +] + +plugin_rand_files = [ + "${plugin_path}/openssl_plugin/rand/src/rand_openssl.c", +] + +plugin_md_files = [ + "${plugin_path}/openssl_plugin/crypto_operation/md/src/md_openssl.c", +] + +plugin_files = plugin_certificate_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 diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn new file mode 100644 index 0000000..b6940d7 --- /dev/null +++ b/test/unittest/BUILD.gn @@ -0,0 +1,68 @@ +# Copyright (C) 2022 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("//build/test.gni") +import("//base/security/crypto_framework/frameworks/frameworks.gni") +import("//base/security/crypto_framework/plugin/plugin.gni") + +module_output_path = "crypto_framework/crypto_framework_test" + +ohos_unittest("crypto_framework_test") { + testonly = true + module_out_path = module_output_path + + include_dirs = [ "./include" ] + include_dirs += [ + "//utils/native/base/include", + "//third_party/openssl/include/", + ] + include_dirs += framework_inc_path + plugin_inc_path + + sources = [ + "src/crypto_ecc_asy_key_generator_test.cpp", + "src/crypto_ecc_key_agreement_test.cpp", + "src/crypto_ecc_sign_test.cpp", + "src/crypto_ecc_verify_test.cpp", + #"src/crypto_rsa_cipher_test.cpp", + # "src/crypto_rsa_asy_key_generator_test.cpp", + # "src/crypto_rsa_sign_test.cpp", + # "src/crypto_rsa_verify_test.cpp", + "src/crypto_x509_certificate_test.cpp", + "src/crypto_aes_cipher_test.cpp", + "src/crypto_3des_cipher_test.cpp", + "src/crypto_mac_test.cpp", + "src/crypto_md_test.cpp", + "src/crypto_rand_test.cpp", + "src/x509_cert_chain_validator_test.cpp", + "src/crypto_x509_crl_test.cpp", + ] + + cflags = [ "-DHILOG_ENABLE" ] + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + deps = [ + "//third_party/bounds_checking_function:libsec_shared", + "//utils/native/base:utils", + "//third_party/openssl:libcrypto_shared", + "//base/security/crypto_framework:crypto_framework_lib", + "//base/security/crypto_framework:crypto_openssl_plugin_lib", + ] + + defines = [ "HILOG_ENABLE" ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + ] +} diff --git a/test/unittest/src/crypto_3des_cipher_test.cpp b/test/unittest/src/crypto_3des_cipher_test.cpp new file mode 100644 index 0000000..eda7f79 --- /dev/null +++ b/test/unittest/src/crypto_3des_cipher_test.cpp @@ -0,0 +1,1407 @@ +/* + * Copyright (C) 2022 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 "sym_key_generator.h" +#include "cipher.h" +#include "log.h" +#include "memory.h" +#include "detailed_iv_params.h" +#include "detailed_gcm_params.h" +#include "detailed_ccm_params.h" + + +using namespace std; +using namespace testing::ext; + +class DesEncryptTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void DesEncryptTest::SetUpTestCase() {} +void DesEncryptTest::TearDownTestCase() {} + +void DesEncryptTest::SetUp() // add init here, this will be called before test. +{ +} + +void DesEncryptTest::TearDown() // add destroy here, this will be called when test case done. +{ +} + +static int32_t DesEncrypt(HcfCipher *cipher, HcfSymKey *key, HcfParamsSpec *params, + uint8_t *cipherText, int *cipherTextLen) +{ + uint8_t plainText[] = "this is test!"; + HcfBlob input = {.data = (uint8_t *)plainText, .len = 13}; + HcfBlob output = {}; + int32_t maxLen = *cipherTextLen; + int32_t ret = cipher->init(cipher, ENCRYPT_MODE, (HcfKey *)key, params); + if (ret != 0) { + LOGE("init failed! %d", ret); + return ret; + } + + ret = cipher->update(cipher, &input, &output); + if (ret != 0) { + LOGE("update failed!"); + return ret; + } + *cipherTextLen = output.len; + if (output.len > 0 && output.data != NULL) { + (void)memcpy_s(cipherText, maxLen, output.data, output.len); + } + if (output.data != NULL) { + HcfFree(output.data); + output.data = NULL; + } + ret = cipher->doFinal(cipher, NULL, &output); + if (ret != 0) { + LOGE("doFinal failed!"); + return ret; + } + if (output.len > 0 && output.data != NULL) { + (void)memcpy_s(cipherText + *cipherTextLen, maxLen - *cipherTextLen, output.data, output.len); + } + *cipherTextLen += output.len; + if (output.data != NULL) { + HcfFree(output.data); + output.data = NULL; + } + return 0; +} + +static int32_t DesDecrypt(HcfCipher *cipher, HcfSymKey *key, HcfParamsSpec *params, + uint8_t *cipherText, int cipherTextLen) +{ + uint8_t plainText[] = "this is test!"; + HcfBlob input = {.data = (uint8_t *)cipherText, .len = cipherTextLen}; + HcfBlob output = {}; + int32_t maxLen = cipherTextLen; + int32_t ret = cipher->init(cipher, DECRYPT_MODE, (HcfKey *)key, params); + if (ret != 0) { + LOGE("init failed! %d", ret); + return ret; + } + + ret = cipher->update(cipher, &input, &output); + if (ret != 0) { + LOGE("update failed!"); + return ret; + } + if (output.len > 0 && output.data != NULL) { + (void)memcpy_s(cipherText, maxLen, output.data, output.len); + } + cipherTextLen = output.len; + if (output.data != NULL) { + HcfFree(output.data); + output.data = NULL; + output.len = 0; + } + ret = cipher->doFinal(cipher, NULL, &output); + if (ret != 0) { + LOGE("doFinal failed!"); + return ret; + } + if (output.len > 0 && output.data != NULL) { + (void)memcpy_s(cipherText + cipherTextLen, maxLen - cipherTextLen, output.data, output.len); + } + cipherTextLen += output.len; + if (output.data != NULL) { + HcfFree(output.data); + output.data = NULL; + output.len = 0; + } + + ret = memcmp(cipherText, plainText, cipherTextLen); + ret = ret || (sizeof(plainText) - 1 == cipherTextLen) ? 0 : 1; + return ret; +} + +static int32_t DesNoUpdateEncrypt(HcfCipher *cipher, HcfSymKey *key, HcfParamsSpec *params, + uint8_t *cipherText, int *cipherTextLen) +{ + uint8_t plainText[] = "this is test!"; + HcfBlob input = {.data = (uint8_t *)plainText, .len = 13}; + HcfBlob output = {}; + int32_t maxLen = *cipherTextLen; + int32_t ret = cipher->init(cipher, ENCRYPT_MODE, (HcfKey *)key, params); + if (ret != 0) { + LOGE("init failed! %d", ret); + return ret; + } + + *cipherTextLen = 0; + ret = cipher->doFinal(cipher, &input, &output); + if (ret != 0) { + LOGE("doFinal failed!"); + return ret; + } + if (output.len > 0 && output.data != NULL) { + (void)memcpy_s(cipherText, maxLen, output.data, output.len); + } + *cipherTextLen += output.len; + if (output.data != NULL) { + HcfFree(output.data); + output.data = NULL; + } + return 0; +} + +static int32_t DesNoUpdateDecrypt(HcfCipher *cipher, HcfSymKey *key, HcfParamsSpec *params, + uint8_t *cipherText, int cipherTextLen) +{ + uint8_t plainText[] = "this is test!"; + HcfBlob input = {.data = (uint8_t *)cipherText, .len = cipherTextLen}; + HcfBlob output = {}; + int32_t maxLen = cipherTextLen; + int32_t ret = cipher->init(cipher, DECRYPT_MODE, (HcfKey *)key, params); + if (ret != 0) { + LOGE("init failed! %d", ret); + return ret; + } + + cipherTextLen = 0; + ret = cipher->doFinal(cipher, &input, &output); + if (ret != 0) { + LOGE("doFinal failed!"); + return ret; + } + if (output.len > 0 && output.data != NULL) { + (void)memcpy_s(cipherText, maxLen, output.data, output.len); + } + cipherTextLen += output.len; + if (output.data != NULL) { + HcfFree(output.data); + output.data = NULL; + output.len = 0; + } + + ret = memcmp(cipherText, plainText, cipherTextLen); + ret = ret || (sizeof(plainText) - 1 == cipherTextLen) ? 0 : 1; + return ret; +} + + +HWTEST_F(DesEncryptTest, DesEncryptTest001, TestSize.Level0) +{ + int ret = 0; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + + ret = HcfSymKeyGeneratorCreate("3DES192", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!"); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("3DES192|ECB|NoPadding", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = DesEncrypt(cipher, key, NULL, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("DesEncrypt failed! %d", ret); + goto clearup; + } + + ret = DesDecrypt(cipher, key, NULL, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("DesDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_NE(ret, 0); +} + +HWTEST_F(DesEncryptTest, DesEncryptTest002, TestSize.Level0) +{ + int ret = 0; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + + ret = HcfSymKeyGeneratorCreate("3DES192", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!"); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("3DES192|ECB|PKCS5", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = DesEncrypt(cipher, key, NULL, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("DesEncrypt failed! %d", ret); + goto clearup; + } + + ret = DesDecrypt(cipher, key, NULL, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("DesDecrypt failed! %d", ret); + goto clearup; + } + + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(DesEncryptTest, DesEncryptTest003, TestSize.Level0) +{ + int ret = 0; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + + ret = HcfSymKeyGeneratorCreate("3DES192", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!"); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("3DES192|ECB|PKCS7", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = DesEncrypt(cipher, key, NULL, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("DesEncrypt failed! %d", ret); + goto clearup; + } + + ret = DesDecrypt(cipher, key, NULL, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("DesDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + + +HWTEST_F(DesEncryptTest, DesEncryptTest004, TestSize.Level0) +{ + int ret = 0; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + uint8_t iv[8] = {0}; + HcfIvParamsSpec ivSpec = {}; + ivSpec.iv.data = iv; + ivSpec.iv.len = 8; + + ret = HcfSymKeyGeneratorCreate("3DES192", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!"); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("3DES192|CBC|NoPadding", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = DesEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("DesEncrypt failed! %d", ret); + goto clearup; + } + + ret = DesDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("DesDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_NE(ret, 0); +} + +HWTEST_F(DesEncryptTest, DesEncryptTest005, TestSize.Level0) +{ + int ret = 0; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + uint8_t iv[8] = {0}; + HcfIvParamsSpec ivSpec = {}; + ivSpec.iv.data = iv; + ivSpec.iv.len = 8; + + ret = HcfSymKeyGeneratorCreate("3DES192", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!"); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("3DES192|CBC|PKCS5", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = DesEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("DesEncrypt failed! %d", ret); + goto clearup; + } + ret = DesDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("DesDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(DesEncryptTest, DesEncryptTest006, TestSize.Level0) +{ + int ret = 0; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + uint8_t iv[8] = {0}; + HcfIvParamsSpec ivSpec = {}; + ivSpec.iv.data = iv; + ivSpec.iv.len = 8; + + ret = HcfSymKeyGeneratorCreate("3DES192", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!"); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("3DES192|CBC|PKCS7", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + ret = DesEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("DesEncrypt failed! %d", ret); + goto clearup; + } + + ret = DesDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("DesDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(DesEncryptTest, DesEncryptTest007, TestSize.Level0) +{ + int ret = 0; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + uint8_t iv[8] = {0}; + HcfIvParamsSpec ivSpec = {}; + ivSpec.iv.data = iv; + ivSpec.iv.len = 8; + + ret = HcfSymKeyGeneratorCreate("3DES192", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!"); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("3DES192|OFB|NoPadding", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = DesEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("DesEncrypt failed! %d", ret); + goto clearup; + } + + ret = DesDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("DesDecrypt failed! %d", ret); + goto clearup; + } + + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(DesEncryptTest, DesEncryptTest008, TestSize.Level0) +{ + int ret = 0; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + uint8_t iv[8] = {0}; + HcfIvParamsSpec ivSpec = {}; + ivSpec.iv.data = iv; + ivSpec.iv.len = 8; + + ret = HcfSymKeyGeneratorCreate("3DES192", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!"); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("3DES192|OFB|PKCS5", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + ret = DesEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("DesEncrypt failed! %d", ret); + goto clearup; + } + + ret = DesDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("DesDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(DesEncryptTest, DesEncryptTest009, TestSize.Level0) +{ + int ret = 0; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + uint8_t iv[8] = {0}; + HcfIvParamsSpec ivSpec = {}; + ivSpec.iv.data = iv; + ivSpec.iv.len = 8; + + ret = HcfSymKeyGeneratorCreate("3DES192", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!"); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("3DES192|OFB|PKCS7", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = DesEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("DesEncrypt failed! %d", ret); + goto clearup; + } + + ret = DesDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("DesDecrypt failed! %d", ret); + goto clearup; + } + + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(DesEncryptTest, DesEncryptTest010, TestSize.Level0) +{ + int ret = 0; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + uint8_t iv[8] = {0}; + HcfIvParamsSpec ivSpec = {}; + ivSpec.iv.data = iv; + ivSpec.iv.len = 8; + + ret = HcfSymKeyGeneratorCreate("3DES192", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!"); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("3DES192|CFB|NoPadding", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = DesEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("DesEncrypt failed! %d", ret); + goto clearup; + } + + ret = DesDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("DesDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(DesEncryptTest, DesEncryptTest011, TestSize.Level0) +{ + int ret = 0; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + uint8_t iv[8] = {0}; + HcfIvParamsSpec ivSpec = {}; + ivSpec.iv.data = iv; + ivSpec.iv.len = 8; + + ret = HcfSymKeyGeneratorCreate("3DES192", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!"); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("3DES192|CFB|PKCS5", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = DesEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("DesEncrypt failed! %d", ret); + goto clearup; + } + + ret = DesDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("DesDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(DesEncryptTest, DesEncryptTest012, TestSize.Level0) +{ + int ret = 0; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + uint8_t iv[8] = {0}; + HcfIvParamsSpec ivSpec = {}; + ivSpec.iv.data = iv; + ivSpec.iv.len = 8; + + ret = HcfSymKeyGeneratorCreate("3DES192", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!"); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("3DES192|CFB|PKCS7", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = DesEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("DesEncrypt failed! %d", ret); + goto clearup; + } + + ret = DesDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("DesDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(DesEncryptTest, DesEncryptTest013, TestSize.Level0) +{ + int ret = 0; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + + ret = HcfSymKeyGeneratorCreate("3DES192", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!"); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("3DES192|ECB|NoPadding", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = DesNoUpdateEncrypt(cipher, key, NULL, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("DesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = DesNoUpdateDecrypt(cipher, key, NULL, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("DesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_NE(ret, 0); +} + +HWTEST_F(DesEncryptTest, DesEncryptTest014, TestSize.Level0) +{ + int ret = 0; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + + ret = HcfSymKeyGeneratorCreate("3DES192", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!"); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("3DES192|ECB|PKCS5", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = DesNoUpdateEncrypt(cipher, key, NULL, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("DesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = DesNoUpdateDecrypt(cipher, key, NULL, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("DesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(DesEncryptTest, DesEncryptTest015, TestSize.Level0) +{ + int ret = 0; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + + ret = HcfSymKeyGeneratorCreate("3DES192", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!"); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("3DES192|ECB|PKCS7", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = DesNoUpdateEncrypt(cipher, key, NULL, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("DesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = DesNoUpdateDecrypt(cipher, key, NULL, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("DesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + + +HWTEST_F(DesEncryptTest, DesEncryptTest016, TestSize.Level0) +{ + int ret = 0; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + uint8_t iv[8] = {0}; + HcfIvParamsSpec ivSpec = {}; + ivSpec.iv.data = iv; + ivSpec.iv.len = 8; + + ret = HcfSymKeyGeneratorCreate("3DES192", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!"); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("3DES192|CBC|NoPadding", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = DesNoUpdateEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("DesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = DesNoUpdateDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("DesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_NE(ret, 0); +} + +HWTEST_F(DesEncryptTest, DesEncryptTest017, TestSize.Level0) +{ + int ret = 0; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + uint8_t iv[8] = {0}; + HcfIvParamsSpec ivSpec = {}; + ivSpec.iv.data = iv; + ivSpec.iv.len = 8; + + ret = HcfSymKeyGeneratorCreate("3DES192", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!"); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("3DES192|CBC|PKCS5", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = DesNoUpdateEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("DesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = DesNoUpdateDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("DesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(DesEncryptTest, DesEncryptTest018, TestSize.Level0) +{ + int ret = 0; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + uint8_t iv[8] = {0}; + HcfIvParamsSpec ivSpec = {}; + ivSpec.iv.data = iv; + ivSpec.iv.len = 8; + + ret = HcfSymKeyGeneratorCreate("3DES192", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!"); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("3DES192|CBC|PKCS7", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = DesNoUpdateEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("DesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = DesNoUpdateDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("DesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(DesEncryptTest, DesEncryptTest019, TestSize.Level0) +{ + int ret = 0; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + uint8_t iv[8] = {0}; + HcfIvParamsSpec ivSpec = {}; + ivSpec.iv.data = iv; + ivSpec.iv.len = 8; + + ret = HcfSymKeyGeneratorCreate("3DES192", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!"); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("3DES192|OFB|NoPadding", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = DesNoUpdateEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("DesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = DesNoUpdateDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("DesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(DesEncryptTest, DesEncryptTest020, TestSize.Level0) +{ + int ret = 0; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + uint8_t iv[8] = {0}; + HcfIvParamsSpec ivSpec = {}; + ivSpec.iv.data = iv; + ivSpec.iv.len = 8; + + ret = HcfSymKeyGeneratorCreate("3DES192", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!"); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("3DES192|OFB|PKCS5", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = DesNoUpdateEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("DesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = DesNoUpdateDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("DesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(DesEncryptTest, DesEncryptTest021, TestSize.Level0) +{ + int ret = 0; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + uint8_t iv[8] = {0}; + HcfIvParamsSpec ivSpec = {}; + ivSpec.iv.data = iv; + ivSpec.iv.len = 8; + + ret = HcfSymKeyGeneratorCreate("3DES192", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!"); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("3DES192|OFB|PKCS7", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = DesNoUpdateEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("DesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = DesNoUpdateDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("DesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(DesEncryptTest, DesEncryptTest022, TestSize.Level0) +{ + int ret = 0; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + uint8_t iv[8] = {0}; + HcfIvParamsSpec ivSpec = {}; + ivSpec.iv.data = iv; + ivSpec.iv.len = 8; + + ret = HcfSymKeyGeneratorCreate("3DES192", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!"); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("3DES192|CFB|NoPadding", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = DesNoUpdateEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("DesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = DesNoUpdateDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("DesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(DesEncryptTest, DesEncryptTest023, TestSize.Level0) +{ + int ret = 0; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + uint8_t iv[8] = {0}; + HcfIvParamsSpec ivSpec = {}; + ivSpec.iv.data = iv; + ivSpec.iv.len = 8; + + ret = HcfSymKeyGeneratorCreate("3DES192", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!"); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("3DES192|CFB|PKCS5", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = DesNoUpdateEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("DesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = DesNoUpdateDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("DesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(DesEncryptTest, DesEncryptTest024, TestSize.Level0) +{ + int ret = 0; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + uint8_t iv[8] = {0}; + HcfIvParamsSpec ivSpec = {}; + ivSpec.iv.data = iv; + ivSpec.iv.len = 8; + + ret = HcfSymKeyGeneratorCreate("3DES192", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!"); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("3DES192|CFB|PKCS7", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = DesNoUpdateEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("DesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = DesNoUpdateDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("DesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} \ No newline at end of file diff --git a/test/unittest/src/crypto_aes_cipher_test.cpp b/test/unittest/src/crypto_aes_cipher_test.cpp new file mode 100644 index 0000000..c50e70c --- /dev/null +++ b/test/unittest/src/crypto_aes_cipher_test.cpp @@ -0,0 +1,3822 @@ +/* + * Copyright (C) 2022 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 +#include + +#include "sym_key_generator.h" +#include "cipher.h" +#include "log.h" +#include "memory.h" +#include "detailed_iv_params.h" +#include "detailed_gcm_params.h" +#include "detailed_ccm_params.h" + + +using namespace std; +using namespace testing::ext; +const int32_t FILE_BLOCK_SIZE = 1024; +const int32_t RAND_MAX_NUM = 100; +const bool IS_DEBUG = false; + +class AesEncryptTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void AesEncryptTest::SetUpTestCase() {} + +void AesEncryptTest::TearDownTestCase() {} + +void AesEncryptTest::SetUp() // add init here, this will be called before test. +{ +} + +void AesEncryptTest::TearDown() // add destroy here, this will be called when test case done. +{ +} + +static void PrintfHex(const char *tag, uint8_t *in, int inLen) +{ + if (!IS_DEBUG) { + return; + } + printf("%s:\n", tag); + for (int i = 0; i < inLen; i++) { + printf("%02hhX", in[i]); + } + printf("\n"); +} + +static int32_t GenerateSymKey(const char *algoName, HcfSymKey **key) +{ + HcfSymKeyGenerator *generator = NULL; + + int32_t ret = HcfSymKeyGeneratorCreate(algoName, &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!"); + return ret; + } + + ret = generator->generateSymKey(generator, key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + } + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + return ret; +} + +static int32_t ConvertSymKey(const char *algoName, HcfSymKey **key) +{ + HcfSymKeyGenerator *generator = NULL; + uint8_t keyMaterial[] = { + 0xba, 0x3b, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56, + 0xad, 0x47, 0xfc, 0x5a, 0x46, 0x39, 0xee, 0x7c + }; + HcfBlob keyTmpBlob = {.data = (uint8_t *)keyMaterial, .len = 16}; + + int32_t ret = HcfSymKeyGeneratorCreate(algoName, &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + return ret; + } + + ret = generator->convertSymKey(generator, &keyTmpBlob, key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + } + PrintfHex("keybinary", keyTmpBlob.data, keyTmpBlob.len); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + return ret; +} + +/* just rand data fill file for test */ +static int32_t GeneratorFile(const char *fileName, int32_t genFileSize) +{ + if (genFileSize == 0) { + return 0; + } + uint8_t buffer[FILE_BLOCK_SIZE] = {0}; + std::ifstream file(fileName); + + if (file.good()) { + file.close(); + return 0; + } + ofstream outfile(fileName, ios::out|ios::binary|ios::app); + if (outfile.is_open()) { + while (genFileSize) { + for (uint32_t i = 0; i < FILE_BLOCK_SIZE; i++) { + buffer[i] = (rand() % RAND_MAX_NUM) + 1; + } + genFileSize -= FILE_BLOCK_SIZE; + outfile.write(reinterpret_cast(buffer), FILE_BLOCK_SIZE); + } + outfile.close(); + } + return 0; +} + +static int32_t CompareFileContent() +{ + int32_t ret = -1; + ifstream infile1, infile2; + infile1.open("/data/test_aes.txt", ios::in|ios::binary); + infile1.seekg (0, infile1.end); + uint32_t length1 = infile1.tellg(); + infile1.seekg (0, infile1.beg); + + infile2.open("/data/test_aes_new.txt", ios::in|ios::binary); + infile2.seekg (0, infile2.end); + uint32_t length2 = infile2.tellg(); + infile2.seekg (0, infile2.beg); + if (length1 != length2) { + return ret; + } + uint8_t buffer1[FILE_BLOCK_SIZE] = {0}; + uint8_t buffer2[FILE_BLOCK_SIZE] = {0}; + for (uint32_t i = 0; i < length1 / FILE_BLOCK_SIZE; i++) { + infile1.read(reinterpret_cast(buffer1), FILE_BLOCK_SIZE); + infile2.read(reinterpret_cast(buffer2), FILE_BLOCK_SIZE); + ret = memcmp(buffer1, buffer2, FILE_BLOCK_SIZE); + if (ret != 0) { + goto clearup; + } + } +clearup: + infile1.close(); + infile2.close(); + return ret; +} + +static int32_t AesMultiBlockEncrypt(HcfCipher *cipher, HcfSymKey *key, HcfParamsSpec *params) +{ + HcfBlob output = {}; + ifstream infile; + ofstream outfile; + infile.open("/data/test_aes.txt", ios::in|ios::binary); + infile.seekg (0, infile.end); + uint32_t length = infile.tellg(); + infile.seekg (0, infile.beg); + uint8_t buffer[1024] = {0}; + outfile.open("/data/test_aes_enc.txt", ios::out|ios::binary); + HcfBlob input = {.data = (uint8_t *)buffer, .len = FILE_BLOCK_SIZE}; + uint32_t count = length / FILE_BLOCK_SIZE; + + int32_t ret = cipher->init(cipher, ENCRYPT_MODE, (HcfKey *)key, params); + if (ret != 0) { + LOGE("init failed! %d", ret); + goto clearup; + } + for (uint32_t i = 0; i < count; i++) { + infile.read(reinterpret_cast(buffer), FILE_BLOCK_SIZE); + ret = cipher->update(cipher, &input, &output); + if (ret != 0) { + LOGE("update failed!"); + goto clearup; + } + if (output.data != nullptr && output.len > 0) { + outfile.write(reinterpret_cast(output.data), output.len); + } + if (output.data != NULL) { + HcfFree(output.data); + output.data = NULL; + } + } + ret = cipher->doFinal(cipher, NULL, &output); + if (ret != 0) { + LOGE("doFinal failed!"); + goto clearup; + } + if (output.data != nullptr && output.len > 0) { + outfile.write((const char *)output.data, output.len); + } + + if (output.data != NULL) { + HcfFree(output.data); + output.data = NULL; + } +clearup: + outfile.close(); + infile.close(); + + return ret; +} + +static int32_t AesMultiBlockDecrypt(HcfCipher *cipher, HcfSymKey *key, HcfParamsSpec *params) +{ + HcfBlob output = {}; + ifstream infile; + ofstream outfile; + infile.open("/data/test_aes_enc.txt", ios::in|ios::binary); + infile.seekg (0, infile.end); + uint32_t length = infile.tellg(); + infile.seekg (0, infile.beg); + uint8_t buffer[1024] = {0}; + outfile.open("/data/test_aes_new.txt", ios::out|ios::binary); + HcfBlob input = {.data = (uint8_t *)buffer, .len = FILE_BLOCK_SIZE}; + + uint32_t count = length / FILE_BLOCK_SIZE; + int32_t ret = cipher->init(cipher, DECRYPT_MODE, (HcfKey *)key, params); + if (ret != 0) { + LOGE("init failed! %d", ret); + goto clearup; + } + for (uint32_t i = 0; i < count; i++) { + infile.read(reinterpret_cast(buffer), FILE_BLOCK_SIZE); + ret = cipher->update(cipher, &input, &output); + if (ret != 0) { + LOGE("update failed!"); + goto clearup; + } + if (output.data != nullptr && output.len > 0) { + outfile.write(reinterpret_cast(output.data), output.len); + } + if (output.data != NULL) { + HcfFree(output.data); + output.data = NULL; + } + } + ret = cipher->doFinal(cipher, NULL, &output); + if (ret != 0) { + LOGE("doFinal failed!"); + goto clearup; + } + if (output.data != nullptr && output.len > 0) { + outfile.write((const char *)output.data, output.len); + } + + if (output.data != NULL) { + HcfFree(output.data); + output.data = NULL; + } +clearup: + outfile.close(); + infile.close(); + + return ret; +} + +static int32_t AesEncrypt(HcfCipher *cipher, HcfSymKey *key, HcfParamsSpec *params, + uint8_t *cipherText, int *cipherTextLen) +{ + uint8_t plainText[] = "this is test!"; + HcfBlob input = {.data = (uint8_t *)plainText, .len = 13}; + HcfBlob output = {}; + int32_t maxLen = *cipherTextLen; + int32_t ret = cipher->init(cipher, ENCRYPT_MODE, (HcfKey *)key, params); + if (ret != 0) { + LOGE("init failed! %d", ret); + return ret; + } + + ret = cipher->update(cipher, &input, &output); + if (ret != 0) { + LOGE("update failed!"); + return ret; + } + *cipherTextLen = output.len; + if (output.len > 0 && output.data != NULL) { + (void)memcpy_s(cipherText, maxLen, output.data, output.len); + } + if (output.data != NULL) { + HcfFree(output.data); + output.data = NULL; + } + ret = cipher->doFinal(cipher, NULL, &output); + if (ret != 0) { + LOGE("doFinal failed!"); + return ret; + } + if (output.len > 0 && output.data != NULL) { + (void)memcpy_s(cipherText + *cipherTextLen, maxLen - *cipherTextLen, output.data, output.len); + } + *cipherTextLen += output.len; + if (output.data != NULL) { + HcfFree(output.data); + output.data = NULL; + } + PrintfHex("ciphertext", cipherText, *cipherTextLen); + return 0; +} + +static int32_t AesDecrypt(HcfCipher *cipher, HcfSymKey *key, HcfParamsSpec *params, + uint8_t *cipherText, int cipherTextLen) +{ + uint8_t plainText[] = "this is test!"; + HcfBlob input = {.data = (uint8_t *)cipherText, .len = cipherTextLen}; + HcfBlob output = {}; + int32_t maxLen = cipherTextLen; + int32_t ret = cipher->init(cipher, DECRYPT_MODE, (HcfKey *)key, params); + if (ret != 0) { + LOGE("init failed! %d", ret); + return ret; + } + + ret = cipher->update(cipher, &input, &output); + if (ret != 0) { + LOGE("update failed!"); + return ret; + } + if (output.len > 0 && output.data != NULL) { + (void)memcpy_s(cipherText, maxLen, output.data, output.len); + } + cipherTextLen = output.len; + if (output.data != NULL) { + HcfFree(output.data); + output.data = NULL; + output.len = 0; + } + ret = cipher->doFinal(cipher, NULL, &output); + if (ret != 0) { + LOGE("doFinal failed!"); + return ret; + } + if (output.len > 0 && output.data != NULL) { + (void)memcpy_s(cipherText + cipherTextLen, maxLen - cipherTextLen, output.data, output.len); + } + cipherTextLen += output.len; + if (output.data != NULL) { + HcfFree(output.data); + output.data = NULL; + output.len = 0; + } + PrintfHex("planText", cipherText, cipherTextLen); + ret = memcmp(cipherText, plainText, cipherTextLen); + ret = ret || (cipherTextLen == sizeof(plainText) - 1) ? 0 : 1; + return ret; +} + +static int32_t AesNoUpdateEncrypt(HcfCipher *cipher, HcfSymKey *key, HcfParamsSpec *params, + uint8_t *cipherText, int *cipherTextLen) +{ + uint8_t plainText[] = "this is test!"; + HcfBlob input = {.data = (uint8_t *)plainText, .len = 13}; + HcfBlob output = {}; + int32_t maxLen = *cipherTextLen; + int32_t ret = cipher->init(cipher, ENCRYPT_MODE, (HcfKey *)key, params); + if (ret != 0) { + LOGE("init failed! %d", ret); + return ret; + } + + *cipherTextLen = 0; + ret = cipher->doFinal(cipher, &input, &output); + if (ret != 0) { + LOGE("doFinal failed!"); + return ret; + } + if (output.len > 0 && output.data != NULL) { + (void)memcpy_s(cipherText, maxLen, output.data, output.len); + } + *cipherTextLen += output.len; + if (output.data != NULL) { + HcfFree(output.data); + output.data = NULL; + } + PrintfHex("ciphertext", cipherText, *cipherTextLen); + return 0; +} + +static int32_t AesNoUpdateDecrypt(HcfCipher *cipher, HcfSymKey *key, HcfParamsSpec *params, + uint8_t *cipherText, int cipherTextLen) +{ + uint8_t plainText[] = "this is test!"; + HcfBlob input = {.data = (uint8_t *)cipherText, .len = cipherTextLen}; + HcfBlob output = {}; + int32_t maxLen = cipherTextLen; + int32_t ret = cipher->init(cipher, DECRYPT_MODE, (HcfKey *)key, params); + if (ret != 0) { + LOGE("init failed! %d", ret); + return ret; + } + + cipherTextLen = 0; + ret = cipher->doFinal(cipher, &input, &output); + if (ret != 0) { + LOGE("doFinal failed!"); + return ret; + } + if (output.len > 0 && output.data != NULL) { + (void)memcpy_s(cipherText, maxLen, output.data, output.len); + } + cipherTextLen += output.len; + if (output.data != NULL) { + HcfFree(output.data); + output.data = NULL; + output.len = 0; + } + PrintfHex("planText", cipherText, cipherTextLen); + ret = memcmp(cipherText, plainText, cipherTextLen); + ret = ret || (cipherTextLen == sizeof(plainText) - 1) ? 0 : 1; + return ret; +} + + +HWTEST_F(AesEncryptTest, AesEncryptTest001, TestSize.Level0) +{ + int ret = 0; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|ECB|NoPadding", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesEncrypt(cipher, key, NULL, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesDecrypt(cipher, key, NULL, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesDecrypt failed! %d", ret); + goto clearup; + } +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_NE(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest002, TestSize.Level0) +{ + int ret = 0; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|ECB|PKCS5", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesEncrypt(cipher, key, NULL, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesDecrypt(cipher, key, NULL, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesDecrypt failed! %d", ret); + goto clearup; + } +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest003, TestSize.Level0) +{ + int ret = 0; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|ECB|PKCS7", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesEncrypt(cipher, key, NULL, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesDecrypt(cipher, key, NULL, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest004, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|CBC|NoPadding", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_NE(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest005, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|CBC|PKCS5", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest006, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|CBC|PKCS7", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest007, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|CTR|NoPadding", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest008, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|CTR|PKCS5", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest009, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|CTR|PKCS7", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest010, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|OFB|NoPadding", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest011, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|OFB|PKCS5", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest012, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|OFB|PKCS7", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesDecrypt failed! %d", ret); + goto clearup; + } +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest013, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|CFB|NoPadding", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest014, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|CFB|PKCS5", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest015, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|CFB|PKCS7", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + + +HWTEST_F(AesEncryptTest, AesEncryptTest016, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|CFB1|NoPadding", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest017, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|CFB1|PKCS5", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest018, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + } + + ret = HcfCipherCreate("AES128|CFB1|PKCS7", &cipher);// CFB1/CFB8/CFB128 bit + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest019, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + } + + ret = HcfCipherCreate("AES128|CFB8|NoPadding", &cipher);// CFB1/CFB8/CFB128 bit + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest020, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + } + + ret = HcfCipherCreate("AES128|CFB8|PKCS5", &cipher);// CFB1/CFB8/CFB128 bit + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest021, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + } + + ret = HcfCipherCreate("AES128|CFB8|PKCS7", &cipher);// CFB1/CFB8/CFB128 bit + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest022, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + } + + ret = HcfCipherCreate("AES128|CFB128|NoPadding", &cipher);// CFB1/CFB8/CFB128 bit + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest023, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + } + + ret = HcfCipherCreate("AES128|CFB128|PKCS5", &cipher);// CFB1/CFB8/CFB128 bit + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest024, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + } + + ret = HcfCipherCreate("AES128|CFB128|PKCS7", &cipher);// CFB1/CFB8/CFB128 bit + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest025, TestSize.Level0) +{ + int ret = 0; + uint8_t aad[8] = {0}; + uint8_t tag[16] = {0}; + uint8_t iv[12] = {0}; // openssl only support nonce 12 bytes, tag 16bytes + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + + HcfGcmParamsSpec spec = {}; + spec.aad.data = aad; + spec.aad.len = sizeof(aad); + spec.tag.data = tag; + spec.tag.len = sizeof(tag); + spec.iv.data = iv; + spec.iv.len = sizeof(iv); + + ret = GenerateSymKey("AES128", &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|GCM|NoPadding", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesEncrypt(cipher, key, (HcfParamsSpec *)&spec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesEncrypt failed, ret:%d!", ret); + goto clearup; + } + + (void)memcpy_s(spec.tag.data, 16, cipherText + cipherTextLen - 16, 16); + PrintfHex("gcm tag", spec.tag.data, spec.tag.len); + cipherTextLen -= 16; + + ret = AesDecrypt(cipher, key, (HcfParamsSpec *)&spec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesDecrypt failed, ret:%d!", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest026, TestSize.Level0) +{ + int ret = 0; + uint8_t aad[8] = {0}; + uint8_t tag[16] = {0}; + uint8_t iv[12] = {0}; // openssl only support nonce 12 bytes, tag 16bytes + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + + HcfGcmParamsSpec spec = {}; + spec.aad.data = aad; + spec.aad.len = sizeof(aad); + spec.tag.data = tag; + spec.tag.len = sizeof(tag); + spec.iv.data = iv; + spec.iv.len = sizeof(iv); + + ret = GenerateSymKey("AES128", &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|GCM|PKCS5", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesEncrypt(cipher, key, (HcfParamsSpec *)&spec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesEncrypt failed, ret:%d!", ret); + goto clearup; + } + + (void)memcpy_s(spec.tag.data, 16, cipherText + cipherTextLen - 16, 16); + PrintfHex("gcm tag", spec.tag.data, spec.tag.len); + cipherTextLen -= 16; + + ret = AesDecrypt(cipher, key, (HcfParamsSpec *)&spec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesDecrypt failed, ret:%d!", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest027, TestSize.Level0) +{ + int ret = 0; + uint8_t aad[8] = {0}; + uint8_t tag[16] = {0}; + uint8_t iv[12] = {0}; // openssl only support nonce 12 bytes, tag 16bytes + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + + HcfGcmParamsSpec spec = {}; + spec.aad.data = aad; + spec.aad.len = sizeof(aad); + spec.tag.data = tag; + spec.tag.len = sizeof(tag); + spec.iv.data = iv; + spec.iv.len = sizeof(iv); + + ret = GenerateSymKey("AES128", &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|GCM|PKCS7", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesEncrypt(cipher, key, (HcfParamsSpec *)&spec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesEncrypt failed, ret:%d!", ret); + goto clearup; + } + + (void)memcpy_s(spec.tag.data, 16, cipherText + cipherTextLen - 16, 16); + PrintfHex("gcm tag", spec.tag.data, spec.tag.len); + cipherTextLen -= 16; + + ret = AesDecrypt(cipher, key, (HcfParamsSpec *)&spec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesDecrypt failed, ret:%d!", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest028, TestSize.Level0) +{ + int ret = 0; + uint8_t aad[8] = {0}; + uint8_t tag[12] = {0}; + uint8_t iv[7] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + HcfCcmParamsSpec spec = {}; + spec.aad.data = aad; + spec.aad.len = sizeof(aad); + spec.tag.data = tag; + spec.tag.len = sizeof(tag); + spec.iv.data = iv; + spec.iv.len = sizeof(iv); + + ret = GenerateSymKey("AES128", &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|CCM|NoPadding", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesEncrypt(cipher, key, (HcfParamsSpec *)&spec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesEncrypt failed!"); + goto clearup; + } + + (void)memcpy_s(spec.tag.data, 12, cipherText + cipherTextLen - 12, 12); + PrintfHex("ccm tag", spec.tag.data, spec.tag.len); + cipherTextLen -= 12; + + ret = AesDecrypt(cipher, key, (HcfParamsSpec *)&spec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesDecrypt failed!"); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest029, TestSize.Level0) +{ + int ret = 0; + uint8_t aad[8] = {0}; + uint8_t tag[12] = {0}; + uint8_t iv[7] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + HcfCcmParamsSpec spec = {}; + spec.aad.data = aad; + spec.aad.len = sizeof(aad); + spec.tag.data = tag; + spec.tag.len = sizeof(tag); + spec.iv.data = iv; + spec.iv.len = sizeof(iv); + + ret = GenerateSymKey("AES128", &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|CCM|PKCS5", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesEncrypt(cipher, key, (HcfParamsSpec *)&spec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesEncrypt failed!"); + goto clearup; + } + + (void)memcpy_s(spec.tag.data, 12, cipherText + cipherTextLen - 12, 12); + PrintfHex("ccm tag", spec.tag.data, spec.tag.len); + cipherTextLen -= 12; + + ret = AesDecrypt(cipher, key, (HcfParamsSpec *)&spec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesDecrypt failed!"); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + EXPECT_EQ(ret, 0); +} + + +HWTEST_F(AesEncryptTest, AesEncryptTest030, TestSize.Level0) +{ + int ret = 0; + uint8_t aad[8] = {0}; + uint8_t tag[12] = {0}; + uint8_t iv[7] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + HcfCcmParamsSpec spec = {}; + spec.aad.data = aad; + spec.aad.len = sizeof(aad); + spec.tag.data = tag; + spec.tag.len = sizeof(tag); + spec.iv.data = iv; + spec.iv.len = sizeof(iv); + + ret = GenerateSymKey("AES128", &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|CCM|PKCS7", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesEncrypt(cipher, key, (HcfParamsSpec *)&spec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesEncrypt failed!"); + goto clearup; + } + + (void)memcpy_s(spec.tag.data, 12, cipherText + cipherTextLen - 12, 12); + PrintfHex("ccm tag", spec.tag.data, spec.tag.len); + cipherTextLen -= 12; + + ret = AesDecrypt(cipher, key, (HcfParamsSpec *)&spec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesDecrypt failed!"); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest031, TestSize.Level0) +{ + int ret = 0; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + uint8_t codeCipherText[] = { + 0xF5, 0x12, 0xA0, 0x33, 0xCD, 0xCF, 0x0D, 0x32, + 0x3E, 0xFF, 0x80, 0x53, 0x89, 0xB6, 0xE4, 0xFE + }; + + ret = ConvertSymKey("AES128", &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|ECB|PKCS7", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesEncrypt(cipher, key, NULL, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesEncrypt failed! %d", ret); + goto clearup; + } + + ret = memcmp(cipherText, codeCipherText, cipherTextLen); + if (ret != 0) { + LOGE("cipherText cpmpare failed!"); + goto clearup; + } + + ret = AesDecrypt(cipher, key, NULL, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest032, TestSize.Level0) +{ + int ret = 0; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|ECB|NoPadding", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesNoUpdateEncrypt(cipher, key, NULL, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesNoUpdateDecrypt(cipher, key, NULL, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_NE(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest033, TestSize.Level0) +{ + int ret = 0; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|ECB|PKCS5", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesNoUpdateEncrypt(cipher, key, NULL, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesNoUpdateDecrypt(cipher, key, NULL, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest034, TestSize.Level0) +{ + int ret = 0; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|ECB|PKCS5", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesNoUpdateEncrypt(cipher, key, NULL, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesNoUpdateDecrypt(cipher, key, NULL, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest035, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|CBC|NoPadding", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesNoUpdateEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesNoUpdateDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_NE(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest036, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|CBC|PKCS5", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesNoUpdateEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesNoUpdateDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest037, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|CBC|PKCS7", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesNoUpdateEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesNoUpdateDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest038, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|CTR|NoPadding", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesNoUpdateEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesNoUpdateDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest039, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|CTR|PKCS5", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesNoUpdateEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesNoUpdateDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest040, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|CTR|PKCS7", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesNoUpdateEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesNoUpdateDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest041, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|OFB|NoPadding", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesNoUpdateEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesNoUpdateDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest042, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|OFB|PKCS5", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesNoUpdateEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesNoUpdateDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest043, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|OFB|PKCS7", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesNoUpdateEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesNoUpdateDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest044, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|CFB|NoPadding", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesNoUpdateEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesNoUpdateDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest045, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|CFB|PKCS5", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesNoUpdateEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesNoUpdateDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest046, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|CFB|PKCS7", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesNoUpdateEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesNoUpdateDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + + +HWTEST_F(AesEncryptTest, AesEncryptTest047, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|CFB1|NoPadding", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesNoUpdateEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesNoUpdateDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest048, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|CFB1|PKCS5", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesNoUpdateEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesNoUpdateDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest049, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + } + + ret = HcfCipherCreate("AES128|CFB1|PKCS7", &cipher);// CFB1/CFB8/CFB128 bit + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesNoUpdateEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesNoUpdateDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest050, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + } + + ret = HcfCipherCreate("AES128|CFB8|NoPadding", &cipher);// CFB1/CFB8/CFB128 bit + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesNoUpdateEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesNoUpdateDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest051, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + } + + ret = HcfCipherCreate("AES128|CFB8|PKCS5", &cipher);// CFB1/CFB8/CFB128 bit + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesNoUpdateEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesNoUpdateDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest052, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + } + + ret = HcfCipherCreate("AES128|CFB8|PKCS7", &cipher);// CFB1/CFB8/CFB128 bit + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + ret = AesNoUpdateEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesNoUpdateDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest053, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + } + + ret = HcfCipherCreate("AES128|CFB128|NoPadding", &cipher);// CFB1/CFB8/CFB128 bit + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + ret = AesNoUpdateEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesNoUpdateDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest054, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + } + + ret = HcfCipherCreate("AES128|CFB128|PKCS5", &cipher);// CFB1/CFB8/CFB128 bit + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + ret = AesNoUpdateEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesNoUpdateDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest055, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfIvParamsSpec ivSpec = {}; + HcfSymKeyGenerator *generator = NULL; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = HcfSymKeyGeneratorCreate("AES128", &generator); + if (ret != 0) { + LOGE("HcfSymKeyGeneratorCreate failed!%d", ret); + goto clearup; + } + + ret = generator->generateSymKey(generator, &key); + if (ret != 0) { + LOGE("generateSymKey failed!"); + } + + ret = HcfCipherCreate("AES128|CFB128|PKCS7", &cipher);// CFB1/CFB8/CFB128 bit + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + ret = AesNoUpdateEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesNoUpdateDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + OH_HCF_ObjDestroy((HcfObjectBase *)generator); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest056, TestSize.Level0) +{ + int ret = 0; + uint8_t aad[8] = {0}; + uint8_t tag[16] = {0}; + uint8_t iv[12] = {0}; // openssl only support nonce 12 bytes, tag 16bytes + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + + HcfGcmParamsSpec spec = {}; + spec.aad.data = aad; + spec.aad.len = sizeof(aad); + spec.tag.data = tag; + spec.tag.len = sizeof(tag); + spec.iv.data = iv; + spec.iv.len = sizeof(iv); + + ret = GenerateSymKey("AES128", &key); + if (ret != 0) { + LOGE("GenerateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|GCM|NoPadding", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesNoUpdateEncrypt(cipher, key, (HcfParamsSpec *)&spec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateEncrypt failed, ret:%d!", ret); + goto clearup; + } + + (void)memcpy_s(spec.tag.data, 16, cipherText + cipherTextLen - 16, 16); + PrintfHex("gcm tag", spec.tag.data, spec.tag.len); + cipherTextLen -= 16; + + ret = AesNoUpdateDecrypt(cipher, key, (HcfParamsSpec *)&spec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateDecrypt failed, ret:%d!", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest057, TestSize.Level0) +{ + int ret = 0; + uint8_t aad[8] = {0}; + uint8_t tag[16] = {0}; + uint8_t iv[12] = {0}; // openssl only support nonce 12 bytes, tag 16bytes + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + + HcfGcmParamsSpec spec = {}; + spec.aad.data = aad; + spec.aad.len = sizeof(aad); + spec.tag.data = tag; + spec.tag.len = sizeof(tag); + spec.iv.data = iv; + spec.iv.len = sizeof(iv); + + ret = GenerateSymKey("AES128", &key); + if (ret != 0) { + LOGE("GenerateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|GCM|PKCS5", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesNoUpdateEncrypt(cipher, key, (HcfParamsSpec *)&spec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateEncrypt failed, ret:%d!", ret); + goto clearup; + } + + (void)memcpy_s(spec.tag.data, 16, cipherText + cipherTextLen - 16, 16); + PrintfHex("gcm tag", spec.tag.data, spec.tag.len); + cipherTextLen -= 16; + + ret = AesNoUpdateDecrypt(cipher, key, (HcfParamsSpec *)&spec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateDecrypt failed, ret:%d!", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest058, TestSize.Level0) +{ + int ret = 0; + uint8_t aad[8] = {0}; + uint8_t tag[16] = {0}; + uint8_t iv[12] = {0}; // openssl only support nonce 12 bytes, tag 16bytes + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + + HcfGcmParamsSpec spec = {}; + spec.aad.data = aad; + spec.aad.len = sizeof(aad); + spec.tag.data = tag; + spec.tag.len = sizeof(tag); + spec.iv.data = iv; + spec.iv.len = sizeof(iv); + + ret = GenerateSymKey("AES128", &key); + if (ret != 0) { + LOGE("GenerateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|GCM|PKCS7", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesNoUpdateEncrypt(cipher, key, (HcfParamsSpec *)&spec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateEncrypt failed, ret:%d!", ret); + goto clearup; + } + + (void)memcpy_s(spec.tag.data, 16, cipherText + cipherTextLen - 16, 16); + PrintfHex("gcm tag", spec.tag.data, spec.tag.len); + cipherTextLen -= 16; + + ret = AesNoUpdateDecrypt(cipher, key, (HcfParamsSpec *)&spec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateDecrypt failed, ret:%d!", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest059, TestSize.Level0) +{ + int ret = 0; + uint8_t aad[8] = {0}; + uint8_t tag[12] = {0}; + uint8_t iv[7] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + HcfCcmParamsSpec spec = {}; + spec.aad.data = aad; + spec.aad.len = sizeof(aad); + spec.tag.data = tag; + spec.tag.len = sizeof(tag); + spec.iv.data = iv; + spec.iv.len = sizeof(iv); + + ret = GenerateSymKey("AES128", &key); + if (ret != 0) { + LOGE("GenerateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|CCM|NoPadding", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesNoUpdateEncrypt(cipher, key, (HcfParamsSpec *)&spec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateEncrypt failed!"); + goto clearup; + } + + (void)memcpy_s(spec.tag.data, 12, cipherText + cipherTextLen - 12, 12); + PrintfHex("ccm tag", spec.tag.data, spec.tag.len); + cipherTextLen -= 12; + + ret = AesNoUpdateDecrypt(cipher, key, (HcfParamsSpec *)&spec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateDecrypt failed!"); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest060, TestSize.Level0) +{ + int ret = 0; + uint8_t aad[8] = {0}; + uint8_t tag[12] = {0}; + uint8_t iv[7] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + HcfCcmParamsSpec spec = {}; + spec.aad.data = aad; + spec.aad.len = sizeof(aad); + spec.tag.data = tag; + spec.tag.len = sizeof(tag); + spec.iv.data = iv; + spec.iv.len = sizeof(iv); + + ret = GenerateSymKey("AES128", &key); + if (ret != 0) { + LOGE("GenerateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|CCM|PKCS5", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesNoUpdateEncrypt(cipher, key, (HcfParamsSpec *)&spec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateEncrypt failed!"); + goto clearup; + } + + (void)memcpy_s(spec.tag.data, 12, cipherText + cipherTextLen - 12, 12); + PrintfHex("ccm tag", spec.tag.data, spec.tag.len); + cipherTextLen -= 12; + + ret = AesNoUpdateDecrypt(cipher, key, (HcfParamsSpec *)&spec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateDecrypt failed!"); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + EXPECT_EQ(ret, 0); +} + + +HWTEST_F(AesEncryptTest, AesEncryptTest061, TestSize.Level0) +{ + int ret = 0; + uint8_t aad[8] = {0}; + uint8_t tag[12] = {0}; + uint8_t iv[7] = {0}; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + HcfCcmParamsSpec spec = {}; + spec.aad.data = aad; + spec.aad.len = sizeof(aad); + spec.tag.data = tag; + spec.tag.len = sizeof(tag); + spec.iv.data = iv; + spec.iv.len = sizeof(iv); + + ret = GenerateSymKey("AES128", &key); + if (ret != 0) { + LOGE("GenerateSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|CCM|PKCS7", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesNoUpdateEncrypt(cipher, key, (HcfParamsSpec *)&spec, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateEncrypt failed!"); + goto clearup; + } + + (void)memcpy_s(spec.tag.data, 12, cipherText + cipherTextLen - 12, 12); + PrintfHex("ccm tag", spec.tag.data, spec.tag.len); + cipherTextLen -= 12; + + ret = AesNoUpdateDecrypt(cipher, key, (HcfParamsSpec *)&spec, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateDecrypt failed!"); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest062, TestSize.Level0) +{ + int ret = 0; + uint8_t cipherText[128] = {0}; + int cipherTextLen = 128; + + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + uint8_t codeCipherText[] = { + 0xF5, 0x12, 0xA0, 0x33, 0xCD, 0xCF, 0x0D, 0x32, + 0x3E, 0xFF, 0x80, 0x53, 0x89, 0xB6, 0xE4, 0xFE + }; + + ret = ConvertSymKey("AES128", &key); + if (ret != 0) { + LOGE("ConvertSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|ECB|PKCS7", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesNoUpdateEncrypt(cipher, key, NULL, cipherText, &cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = memcmp(cipherText, codeCipherText, cipherTextLen); + if (ret != 0) { + LOGE("cipherText cpmpare failed!"); + goto clearup; + } + + ret = AesNoUpdateDecrypt(cipher, key, NULL, cipherText, cipherTextLen); + if (ret != 0) { + LOGE("AesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest063, TestSize.Level0) +{ + int ret = 0; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + + ret = GeneratorFile("/data/test_aes.txt", 10 * FILE_BLOCK_SIZE); + if (ret != 0) { + LOGE("GeneratorFile failed!"); + goto clearup; + } + ret = ConvertSymKey("AES128", &key); + if (ret != 0) { + LOGE("ConvertSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|ECB|NoPadding", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesMultiBlockEncrypt(cipher, key, NULL); + if (ret != 0) { + LOGE("AesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesMultiBlockDecrypt(cipher, key, NULL); + if (ret != 0) { + LOGE("AesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + ret = CompareFileContent(); + if (ret != 0) { + LOGE("CompareFileContent failed!"); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest064, TestSize.Level0) +{ + int ret = 0; + HcfIvParamsSpec ivSpec = {}; + uint8_t iv[16] = {0}; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + + ret = GeneratorFile("/data/test_aes.txt", 10 * FILE_BLOCK_SIZE); + if (ret != 0) { + LOGE("GeneratorFile failed!"); + goto clearup; + } + + ret = ConvertSymKey("AES128", &key); + if (ret != 0) { + LOGE("ConvertSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|CBC|NoPadding", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + + ret = AesMultiBlockEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec); + if (ret != 0) { + LOGE("AesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesMultiBlockDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec); + if (ret != 0) { + LOGE("AesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + ret = CompareFileContent(); + if (ret != 0) { + LOGE("CompareFileContent failed!"); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest065, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + + HcfIvParamsSpec ivSpec = {}; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = ConvertSymKey("AES128", &key); + if (ret != 0) { + LOGE("ConvertSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|CTR|NoPadding", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + ret = GeneratorFile("/data/test_aes.txt", 10 * FILE_BLOCK_SIZE); + if (ret != 0) { + LOGE("GeneratorFile failed!"); + goto clearup; + } + + ret = AesMultiBlockEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec); + if (ret != 0) { + LOGE("AesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesMultiBlockDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec); + if (ret != 0) { + LOGE("AesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + ret = CompareFileContent(); + if (ret != 0) { + LOGE("CompareFileContent failed!"); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest066, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + + HcfIvParamsSpec ivSpec = {}; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = GenerateSymKey("AES128", &key); + if (ret != 0) { + LOGE("ConvertSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|OFB|NoPadding", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + ret = GeneratorFile("/data/test_aes.txt", 10 * FILE_BLOCK_SIZE); + if (ret != 0) { + LOGE("GeneratorFile failed!"); + goto clearup; + } + + ret = AesMultiBlockEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec); + if (ret != 0) { + LOGE("AesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesMultiBlockDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec); + if (ret != 0) { + LOGE("AesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + ret = CompareFileContent(); + if (ret != 0) { + LOGE("CompareFileContent failed!"); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(AesEncryptTest, AesEncryptTest067, TestSize.Level0) +{ + int ret = 0; + uint8_t iv[16] = {0}; + + HcfIvParamsSpec ivSpec = {}; + HcfCipher *cipher = NULL; + HcfSymKey *key = NULL; + ivSpec.iv.data = iv; + ivSpec.iv.len = 16; + + ret = GenerateSymKey("AES128", &key); + if (ret != 0) { + LOGE("ConvertSymKey failed!"); + goto clearup; + } + + ret = HcfCipherCreate("AES128|CFB|NoPadding", &cipher); + if (ret != 0) { + LOGE("HcfCipherCreate failed!"); + goto clearup; + } + ret = GeneratorFile("/data/test_aes.txt", 10 * FILE_BLOCK_SIZE); + if (ret != 0) { + LOGE("GeneratorFile failed!"); + goto clearup; + } + + ret = AesMultiBlockEncrypt(cipher, key, (HcfParamsSpec *)&ivSpec); + if (ret != 0) { + LOGE("AesNoUpdateEncrypt failed! %d", ret); + goto clearup; + } + + ret = AesMultiBlockDecrypt(cipher, key, (HcfParamsSpec *)&ivSpec); + if (ret != 0) { + LOGE("AesNoUpdateDecrypt failed! %d", ret); + goto clearup; + } + ret = CompareFileContent(); + if (ret != 0) { + LOGE("CompareFileContent failed!"); + goto clearup; + } + +clearup: + OH_HCF_ObjDestroy((HcfObjectBase *)key); + OH_HCF_ObjDestroy((HcfObjectBase *)cipher); + EXPECT_EQ(ret, 0); +} diff --git a/test/unittest/src/crypto_ecc_asy_key_generator_test.cpp b/test/unittest/src/crypto_ecc_asy_key_generator_test.cpp new file mode 100644 index 0000000..bf27a80 --- /dev/null +++ b/test/unittest/src/crypto_ecc_asy_key_generator_test.cpp @@ -0,0 +1,2091 @@ +/* + * Copyright (C) 2022 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 "blob.h" + +using namespace std; +using namespace testing::ext; + +class EccAsyKeyGeneratorTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void EccAsyKeyGeneratorTest::SetUpTestCase() {} +void EccAsyKeyGeneratorTest::TearDownTestCase() {} +void EccAsyKeyGeneratorTest::SetUp() {} +void EccAsyKeyGeneratorTest::TearDown() {} + +#define ECC224_PUB_KEY_LEN 57 +#define ECC224_PRI_KEY_LEN 28 +#define ECC256_PUB_KEY_LEN 65 +#define ECC256_PRI_KEY_LEN 32 +#define ECC384_PUB_KEY_LEN 97 +#define ECC384_PRI_KEY_LEN 48 +#define ECC512_PUB_KEY_LEN 133 +#define ECC512_PRI_KEY_LEN 65 + +static uint8_t mockEcc224PubKeyBlobData[ECC224_PUB_KEY_LEN] = { 4, 189, 186, 122, 21, 9, 8, 231, 90, 111, 68, 222, + 207, 200, 53, 114, 236, 246, 204, 9, 171, 197, 57, 173, 138, 38, 180, 217, 55, 234, 181, 87, 143, 199, 250, 222, + 101, 120, 193, 184, 132, 9, 139, 177, 112, 246, 97, 25, 57, 43, 252, 212, 33, 181, 114, 89, 151 }; + +static uint8_t mockEcc224PriKeyBlobData[ECC224_PRI_KEY_LEN] = { 7, 13, 160, 20, 7, 190, 2, 157, 233, 245, 164, 249, + 218, 30, 241, 3, 198, 136, 155, 15, 168, 198, 237, 117, 95, 45, 142, 183 }; + +static uint8_t mockEcc256PubKeyBlobData[ECC256_PUB_KEY_LEN] = { 4, 15, 195, 182, 51, 78, 219, 41, 100, 231, 64, 119, + 34, 191, 238, 62, 169, 229, 240, 57, 216, 20, 229, 93, 193, 136, 238, 194, 150, 78, 205, 62, 218, 201, 77, 194, + 46, 121, 234, 126, 85, 134, 229, 244, 227, 184, 42, 22, 171, 179, 236, 16, 12, 93, 138, 175, 255, 99, 212, 107, + 83, 128, 49, 194, 215 }; + +static uint8_t mockEcc256PriKeyBlobData[ECC256_PRI_KEY_LEN] = { 218, 130, 176, 177, 252, 163, 236, 3, 204, 22, 211, + 213, 239, 252, 14, 231, 185, 139, 221, 45, 196, 13, 237, 179, 129, 165, 72, 224, 230, 210, 207, 232 }; +static uint8_t mockEcc384PubKeyBlobData[ECC384_PUB_KEY_LEN] = { 4, 246, 111, 226, 33, 39, 150, 111, 50, 96, 228, + 225, 189, 33, 213, 169, 139, 181, 46, 51, 160, 254, 184, 75, 115, 153, 153, 105, 177, 50, 211, 101, 71, 53, + 5, 138, 56, 125, 137, 4, 206, 152, 206, 221, 212, 162, 242, 135, 202, 205, 119, 79, 45, 191, 111, 84, 172, + 34, 159, 112, 149, 197, 102, 56, 235, 212, 171, 234, 162, 11, 188, 146, 137, 203, 180, 46, 241, 44, 235, + 25, 111, 12, 115, 140, 220, 41, 192, 166, 124, 205, 173, 142, 107, 4, 105, 54, 148 }; + +static uint8_t mockEcc384PriKeyBlobData[ECC384_PRI_KEY_LEN] = { 121, 40, 96, 196, 198, 46, 100, 70, 102, 98, 63, 143, + 8, 224, 229, 57, 236, 161, 224, 204, 85, 49, 99, 205, 104, 90, 98, 9, 79, 171, 189, 5, 194, 117, 225, 203, 127, + 17, 214, 77, 6, 99, 162, 9, 191, 192, 76, 174 }; +static uint8_t mockEcc512PubKeyBlobData[ECC512_PUB_KEY_LEN] = { 4, 1, 79, 67, 218, 31, 215, 194, 89, 74, 246, 88, + 151, 232, 47, 159, 60, 56, 23, 159, 12, 123, 12, 239, 81, 75, 92, 15, 118, 101, 27, 69, 147, 76, 151, 91, 59, + 212, 77, 176, 198, 132, 151, 225, 113, 116, 164, 254, 206, 148, 203, 95, 3, 137, 148, 180, 184, 173, 206, 16, + 12, 170, 57, 228, 25, 233, 159, 0, 107, 24, 217, 155, 26, 85, 40, 148, 116, 97, 134, 150, 73, 127, 247, 184, + 132, 188, 2, 165, 236, 146, 150, 103, 213, 206, 185, 124, 13, 166, 213, 238, 39, 18, 10, 164, 226, 139, 86, + 159, 25, 88, 154, 155, 75, 248, 46, 200, 14, 33, 45, 68, 4, 238, 138, 144, 114, 11, 219, 114, 7, 163, 255, 9, 150 }; + +static uint8_t mockEcc512PriKeyBlobData[ECC512_PRI_KEY_LEN] = { 128, 210, 9, 28, 225, 87, 232, 88, 102, 55, 78, 216, + 162, 210, 219, 218, 26, 33, 206, 253, 165, 172, 111, 60, 157, 206, 77, 145, 123, 95, 92, 21, 254, 159, 145, 104, + 194, 49, 0, 108, 38, 40, 204, 1, 231, 162, 34, 64, 118, 191, 163, 143, 33, 44, 55, 231, 54, 64, 210, 54, 201, + 117, 251, 157, 109 }; + +static HcfBlob mockEcc224PubKeyBlob = { + .data = mockEcc224PubKeyBlobData, + .len = ECC224_PUB_KEY_LEN +}; + +static HcfBlob mockEcc224PriKeyBlob = { + .data = mockEcc224PriKeyBlobData, + .len = ECC224_PRI_KEY_LEN +}; + +static HcfBlob mockEcc256PubKeyBlob = { + .data = mockEcc256PubKeyBlobData, + .len = ECC256_PUB_KEY_LEN +}; + +static HcfBlob mockEcc256PriKeyBlob = { + .data = mockEcc256PriKeyBlobData, + .len = ECC256_PRI_KEY_LEN +}; + +static HcfBlob mockEcc384PubKeyBlob = { + .data = mockEcc384PubKeyBlobData, + .len = ECC384_PUB_KEY_LEN +}; + +static HcfBlob mockEcc384PriKeyBlob = { + .data = mockEcc384PriKeyBlobData, + .len = ECC384_PRI_KEY_LEN +}; + +static HcfBlob mockEcc512PubKeyBlob = { + .data = mockEcc512PubKeyBlobData, + .len = ECC512_PUB_KEY_LEN +}; + +static HcfBlob mockEcc512PriKeyBlob = { + .data = mockEcc512PriKeyBlobData, + .len = ECC512_PRI_KEY_LEN +}; + +static const char *GetMockClass(void) +{ + return "HcfSymKeyGenerator"; +} + +static HcfObjectBase obj = { + .getClass = GetMockClass, + .destroy = NULL +}; + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest001, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(generator, nullptr); + + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest002, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC256", &generator); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(generator, nullptr); + + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest003, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC384", &generator); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(generator, nullptr); + + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest004, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC512", &generator); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(generator, nullptr); + + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest005, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate(nullptr, &generator); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + ASSERT_EQ(generator, nullptr); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest006, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCD" + "ABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCD", &generator); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + ASSERT_EQ(generator, nullptr); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest007, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC225", &generator); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + ASSERT_EQ(generator, nullptr); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest008, TestSize.Level0) +{ + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", NULL); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest101, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(generator, nullptr); + + const char *className = generator->base.getClass(); + ASSERT_NE(className, nullptr); + + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest102, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(generator, nullptr); + + generator->base.destroy((HcfObjectBase *)generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest103, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(generator, nullptr); + + generator->base.destroy(NULL); + + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest104, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(generator, nullptr); + + generator->base.destroy(&obj); + + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest105, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(generator, nullptr); + + const char *algName = generator->getAlgoName(generator); + + ASSERT_NE(algName, nullptr); + + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest106, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(generator, nullptr); + + const char *algName = generator->getAlgoName(NULL); + + ASSERT_EQ(algName, nullptr); + + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest107, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(generator, nullptr); + + const char *algName = generator->getAlgoName((HcfAsyKeyGenerator *)&obj); + + ASSERT_EQ(algName, nullptr); + + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest201, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(generator, nullptr); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest202, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC256", &generator); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(generator, nullptr); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest203, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC384", &generator); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(generator, nullptr); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest204, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC512", &generator); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(generator, nullptr); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest205, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(generator, nullptr); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(NULL, NULL, &keyPair); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + ASSERT_EQ(keyPair, nullptr); + + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest206, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(generator, nullptr); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair((HcfAsyKeyGenerator *)&obj, NULL, &keyPair); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + ASSERT_EQ(keyPair, nullptr); + + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest207, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(generator, nullptr); + + res = generator->generateKeyPair(generator, NULL, NULL); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest301, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + const char *className = keyPair->base.getClass(); + + ASSERT_NE(className, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest302, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + keyPair->base.destroy((HcfObjectBase *)(&(keyPair->base))); + + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest303, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + keyPair->base.destroy(NULL); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest304, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + keyPair->base.destroy(&obj); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest305, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + const char *className = keyPair->pubKey->base.base.getClass(); + ASSERT_NE(className, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest306, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + keyPair->pubKey->base.base.destroy((HcfObjectBase *)(&(keyPair->pubKey->base.base))); + keyPair->pubKey = NULL; + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest307, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + keyPair->pubKey->base.base.destroy(NULL); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest308, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + keyPair->pubKey->base.base.destroy(&obj); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest309, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + const char *format = keyPair->pubKey->base.getFormat(&(keyPair->pubKey->base)); + + ASSERT_NE(format, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest310, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + const char *format = keyPair->pubKey->base.getFormat(NULL); + + ASSERT_EQ(format, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest311, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + const char *format = keyPair->pubKey->base.getFormat((HcfKey *)&obj); + + ASSERT_EQ(format, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest312, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + const char *algName = keyPair->pubKey->base.getAlgorithm(&(keyPair->pubKey->base)); + + ASSERT_NE(algName, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest313, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + const char *algName = keyPair->pubKey->base.getAlgorithm(NULL); + + ASSERT_EQ(algName, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest314, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + const char *algName = keyPair->pubKey->base.getAlgorithm((HcfKey *)&obj); + + ASSERT_EQ(algName, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest315, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + HcfBlob blob = { + .data = NULL, + .len = 0 + }; + res = keyPair->pubKey->base.getEncoded(&(keyPair->pubKey->base), &blob); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(blob.data, nullptr); + ASSERT_NE(blob.len, 0); + + free(blob.data); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest316, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + HcfBlob blob = { + .data = NULL, + .len = 0 + }; + res = keyPair->pubKey->base.getEncoded(NULL, &blob); + + ASSERT_NE(res, HCF_SUCCESS); + ASSERT_EQ(blob.data, nullptr); + ASSERT_EQ(blob.len, 0); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest317, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + HcfBlob blob = { + .data = NULL, + .len = 0 + }; + res = keyPair->pubKey->base.getEncoded((HcfKey *)&obj, &blob); + + ASSERT_NE(res, HCF_SUCCESS); + ASSERT_EQ(blob.data, nullptr); + ASSERT_EQ(blob.len, 0); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest318, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + res = keyPair->pubKey->base.getEncoded(&(keyPair->pubKey->base), NULL); + + ASSERT_NE(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest319, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + keyPair->priKey->clearMem(keyPair->priKey); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest320, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + keyPair->priKey->clearMem(NULL); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest321, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + keyPair->priKey->clearMem((HcfPriKey *)&obj); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest322, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + const char *algName = keyPair->priKey->base.base.getClass(); + + ASSERT_NE(algName, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest323, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + keyPair->priKey->base.base.destroy((HcfObjectBase *)(&(keyPair->priKey->base.base))); + keyPair->priKey = NULL; + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest324, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + keyPair->priKey->base.base.destroy(NULL); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest325, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + keyPair->priKey->base.base.destroy(&obj); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest326, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + const char *format = keyPair->priKey->base.getFormat(&keyPair->priKey->base); + + ASSERT_NE(format, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest327, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + const char *format = keyPair->priKey->base.getFormat(NULL); + + ASSERT_EQ(format, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest328, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + const char *format = keyPair->priKey->base.getFormat((HcfKey *)&obj); + + ASSERT_EQ(format, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest329, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + const char *algName = keyPair->priKey->base.getAlgorithm(&keyPair->priKey->base); + + ASSERT_NE(algName, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest330, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + const char *algName = keyPair->priKey->base.getAlgorithm(NULL); + + ASSERT_EQ(algName, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest331, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + const char *algName = keyPair->priKey->base.getAlgorithm((HcfKey *)&obj); + + ASSERT_EQ(algName, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest332, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + HcfBlob blob = { + .data = NULL, + .len = 0 + }; + res = keyPair->priKey->base.getEncoded(&(keyPair->priKey->base), &blob); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(blob.data, nullptr); + ASSERT_NE(blob.len, 0); + + free(blob.data); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest333, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + HcfBlob blob = { + .data = NULL, + .len = 0 + }; + res = keyPair->priKey->base.getEncoded(NULL, &blob); + + ASSERT_NE(res, HCF_SUCCESS); + ASSERT_EQ(blob.data, nullptr); + ASSERT_EQ(blob.len, 0); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest334, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + HcfBlob blob = { + .data = NULL, + .len = 0 + }; + res = keyPair->priKey->base.getEncoded((HcfKey *)&obj, &blob); + + ASSERT_NE(res, HCF_SUCCESS); + ASSERT_EQ(blob.data, nullptr); + ASSERT_EQ(blob.len, 0); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest335, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + res = keyPair->priKey->base.getEncoded(&(keyPair->priKey->base), NULL); + + ASSERT_NE(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest401, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *outKeyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &outKeyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(outKeyPair, nullptr); + + OH_HCF_ObjDestroy(outKeyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest402, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC256", &generator); + + HcfKeyPair *outKeyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc256PubKeyBlob, &mockEcc256PriKeyBlob, &outKeyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(outKeyPair, nullptr); + + OH_HCF_ObjDestroy(outKeyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest403, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC384", &generator); + + HcfKeyPair *outKeyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc384PubKeyBlob, &mockEcc384PriKeyBlob, &outKeyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(outKeyPair, nullptr); + + OH_HCF_ObjDestroy(outKeyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest404, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC512", &generator); + + HcfKeyPair *outKeyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc512PubKeyBlob, &mockEcc512PriKeyBlob, &outKeyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(outKeyPair, nullptr); + + OH_HCF_ObjDestroy(outKeyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest405, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *outKeyPair = NULL; + res = generator->convertKey(NULL, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &outKeyPair); + + ASSERT_NE(res, HCF_SUCCESS); + ASSERT_EQ(outKeyPair, nullptr); + + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest406, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *outKeyPair = NULL; + res = generator->convertKey((HcfAsyKeyGenerator *)&obj, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, + &outKeyPair); + + ASSERT_NE(res, HCF_SUCCESS); + ASSERT_EQ(outKeyPair, nullptr); + + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest407, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *outKeyPair = NULL; + res = generator->convertKey(generator, NULL, NULL, &mockEcc224PriKeyBlob, &outKeyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(outKeyPair, nullptr); + + OH_HCF_ObjDestroy(outKeyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest408, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *outKeyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, NULL, &outKeyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(outKeyPair, nullptr); + + OH_HCF_ObjDestroy(outKeyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest409, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *outKeyPair = NULL; + res = generator->convertKey(generator, NULL, NULL, NULL, &outKeyPair); + + ASSERT_NE(res, HCF_SUCCESS); + ASSERT_EQ(outKeyPair, nullptr); + + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest410, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, NULL); + + ASSERT_NE(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest501, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + const char *className = keyPair->base.getClass(); + + ASSERT_NE(className, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest502, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + keyPair->base.destroy((HcfObjectBase *)(&(keyPair->base))); + + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest503, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + keyPair->base.destroy(NULL); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest504, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + keyPair->base.destroy(&obj); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest505, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + const char *className = keyPair->pubKey->base.base.getClass(); + ASSERT_NE(className, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest506, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + keyPair->pubKey->base.base.destroy((HcfObjectBase *)(&(keyPair->pubKey->base.base))); + keyPair->pubKey = NULL; + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest507, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + keyPair->pubKey->base.base.destroy(NULL); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest508, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + keyPair->pubKey->base.base.destroy(&obj); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest509, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + const char *format = keyPair->pubKey->base.getFormat(&(keyPair->pubKey->base)); + + ASSERT_NE(format, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest510, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + const char *format = keyPair->pubKey->base.getFormat(NULL); + + ASSERT_EQ(format, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest511, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + const char *format = keyPair->pubKey->base.getFormat((HcfKey *)&obj); + + ASSERT_EQ(format, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest512, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + const char *algName = keyPair->pubKey->base.getAlgorithm(&(keyPair->pubKey->base)); + + ASSERT_NE(algName, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest513, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + const char *algName = keyPair->pubKey->base.getAlgorithm(NULL); + + ASSERT_EQ(algName, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest514, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + const char *algName = keyPair->pubKey->base.getAlgorithm((HcfKey *)&obj); + + ASSERT_EQ(algName, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest515, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + HcfBlob blob = { + .data = NULL, + .len = 0 + }; + res = keyPair->pubKey->base.getEncoded(&(keyPair->pubKey->base), &blob); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(blob.data, nullptr); + ASSERT_NE(blob.len, 0); + + free(blob.data); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest516, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + HcfBlob blob = { + .data = NULL, + .len = 0 + }; + res = keyPair->pubKey->base.getEncoded(NULL, &blob); + + ASSERT_NE(res, HCF_SUCCESS); + ASSERT_EQ(blob.data, nullptr); + ASSERT_EQ(blob.len, 0); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest517, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + HcfBlob blob = { + .data = NULL, + .len = 0 + }; + res = keyPair->pubKey->base.getEncoded((HcfKey *)&obj, &blob); + + ASSERT_NE(res, HCF_SUCCESS); + ASSERT_EQ(blob.data, nullptr); + ASSERT_EQ(blob.len, 0); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest518, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + res = keyPair->pubKey->base.getEncoded(&(keyPair->pubKey->base), NULL); + + ASSERT_NE(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest519, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + keyPair->priKey->clearMem(keyPair->priKey); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest520, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + keyPair->priKey->clearMem(NULL); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest521, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + keyPair->priKey->clearMem((HcfPriKey *)&obj); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest522, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + const char *algName = keyPair->priKey->base.base.getClass(); + + ASSERT_NE(algName, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest523, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + keyPair->priKey->base.base.destroy((HcfObjectBase *)(&(keyPair->priKey->base.base))); + keyPair->priKey = NULL; + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest524, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + keyPair->priKey->base.base.destroy(NULL); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest525, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + keyPair->priKey->base.base.destroy(&obj); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest526, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + const char *format = keyPair->priKey->base.getFormat(&keyPair->priKey->base); + + ASSERT_NE(format, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest527, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + const char *format = keyPair->priKey->base.getFormat(NULL); + + ASSERT_EQ(format, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest528, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + const char *format = keyPair->priKey->base.getFormat((HcfKey *)&obj); + + ASSERT_EQ(format, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest529, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + const char *algName = keyPair->priKey->base.getAlgorithm(&keyPair->priKey->base); + + ASSERT_NE(algName, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest530, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + const char *algName = keyPair->priKey->base.getAlgorithm(NULL); + + ASSERT_EQ(algName, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest531, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + const char *algName = keyPair->priKey->base.getAlgorithm((HcfKey *)&obj); + + ASSERT_EQ(algName, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest532, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + HcfBlob blob = { + .data = NULL, + .len = 0 + }; + res = keyPair->priKey->base.getEncoded(&(keyPair->priKey->base), &blob); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(blob.data, nullptr); + ASSERT_NE(blob.len, 0); + + free(blob.data); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest533, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + HcfBlob blob = { + .data = NULL, + .len = 0 + }; + res = keyPair->priKey->base.getEncoded(NULL, &blob); + + ASSERT_NE(res, HCF_SUCCESS); + ASSERT_EQ(blob.data, nullptr); + ASSERT_EQ(blob.len, 0); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest534, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + HcfBlob blob = { + .data = NULL, + .len = 0 + }; + res = keyPair->priKey->base.getEncoded((HcfKey *)&obj, &blob); + + ASSERT_NE(res, HCF_SUCCESS); + ASSERT_EQ(blob.data, nullptr); + ASSERT_EQ(blob.len, 0); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest535, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->convertKey(generator, NULL, &mockEcc224PubKeyBlob, &mockEcc224PriKeyBlob, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + res = keyPair->priKey->base.getEncoded(&(keyPair->priKey->base), NULL); + + ASSERT_NE(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest536, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + HcfBlob pubKeyBlob = { + .data = NULL, + .len = 0 + }; + res = keyPair->pubKey->base.getEncoded(&(keyPair->pubKey->base), &pubKeyBlob); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(pubKeyBlob.data, nullptr); + ASSERT_NE(pubKeyBlob.len, 0); + + HcfBlob priKeyBlob = { + .data = NULL, + .len = 0 + }; + res = keyPair->priKey->base.getEncoded(&(keyPair->priKey->base), &priKeyBlob); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(priKeyBlob.data, nullptr); + ASSERT_NE(priKeyBlob.len, 0); + + HcfKeyPair *outKeyPair = NULL; + res = generator->convertKey(generator, NULL, &pubKeyBlob, &priKeyBlob, &outKeyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(outKeyPair, nullptr); + + HcfBlob outPubKeyBlob = { + .data = NULL, + .len = 0 + }; + res = outKeyPair->pubKey->base.getEncoded(&(outKeyPair->pubKey->base), &outPubKeyBlob); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(outPubKeyBlob.data, nullptr); + ASSERT_NE(outPubKeyBlob.len, 0); + + HcfBlob outPriKeyBlob = { + .data = NULL, + .len = 0 + }; + res = outKeyPair->priKey->base.getEncoded(&(outKeyPair->priKey->base), &outPriKeyBlob); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(outPriKeyBlob.data, nullptr); + ASSERT_NE(outPriKeyBlob.len, 0); + + free(pubKeyBlob.data); + free(priKeyBlob.data); + free(outPubKeyBlob.data); + free(outPriKeyBlob.data); + OH_HCF_ObjDestroy(outKeyPair); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest537, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + HcfBlob pubKeyBlob = { + .data = NULL, + .len = 0 + }; + res = keyPair->pubKey->base.getEncoded(&(keyPair->pubKey->base), &pubKeyBlob); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(pubKeyBlob.data, nullptr); + ASSERT_NE(pubKeyBlob.len, 0); + + HcfKeyPair *outKeyPair = NULL; + res = generator->convertKey(generator, NULL, &pubKeyBlob, NULL, &outKeyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(outKeyPair, nullptr); + ASSERT_NE(outKeyPair->pubKey, nullptr); + ASSERT_EQ(outKeyPair->priKey, nullptr); + + HcfBlob outPubKeyBlob = { + .data = NULL, + .len = 0 + }; + res = outKeyPair->pubKey->base.getEncoded(&(outKeyPair->pubKey->base), &outPubKeyBlob); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(outPubKeyBlob.data, nullptr); + ASSERT_NE(outPubKeyBlob.len, 0); + + free(pubKeyBlob.data); + free(outPubKeyBlob.data); + OH_HCF_ObjDestroy(outKeyPair); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(EccAsyKeyGeneratorTest, EccAsyKeyGeneratorTest538, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + HcfBlob priKeyBlob = { + .data = NULL, + .len = 0 + }; + res = keyPair->priKey->base.getEncoded(&(keyPair->priKey->base), &priKeyBlob); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(priKeyBlob.data, nullptr); + ASSERT_NE(priKeyBlob.len, 0); + + HcfKeyPair *outKeyPair = NULL; + res = generator->convertKey(generator, NULL, NULL, &priKeyBlob, &outKeyPair); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(outKeyPair, nullptr); + ASSERT_EQ(outKeyPair->pubKey, nullptr); + ASSERT_NE(outKeyPair->priKey, nullptr); + + HcfBlob outPriKeyBlob = { + .data = NULL, + .len = 0 + }; + res = outKeyPair->priKey->base.getEncoded(&(outKeyPair->priKey->base), &outPriKeyBlob); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(outPriKeyBlob.data, nullptr); + ASSERT_NE(outPriKeyBlob.len, 0); + + free(priKeyBlob.data); + free(outPriKeyBlob.data); + OH_HCF_ObjDestroy(outKeyPair); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} diff --git a/test/unittest/src/crypto_ecc_key_agreement_test.cpp b/test/unittest/src/crypto_ecc_key_agreement_test.cpp new file mode 100644 index 0000000..b075540 --- /dev/null +++ b/test/unittest/src/crypto_ecc_key_agreement_test.cpp @@ -0,0 +1,505 @@ +/* + * Copyright (C) 2022 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 "key_agreement.h" + +using namespace std; +using namespace testing::ext; + +static const char *GetMockClass(void) +{ + return "HcfSymKeyGenerator"; +} + +static HcfObjectBase obj = { + .getClass = GetMockClass, + .destroy = NULL +}; + +class KeyAgreementTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + + static HcfKeyPair *ecc224KeyPair_; + static HcfKeyPair *ecc256KeyPair_; + static HcfKeyPair *ecc384KeyPair_; + static HcfKeyPair *ecc512KeyPair_; +}; + +HcfKeyPair *KeyAgreementTest::ecc224KeyPair_ = nullptr; +HcfKeyPair *KeyAgreementTest::ecc256KeyPair_ = nullptr; +HcfKeyPair *KeyAgreementTest::ecc384KeyPair_ = nullptr; +HcfKeyPair *KeyAgreementTest::ecc512KeyPair_ = nullptr; + +void KeyAgreementTest::SetUp() {} +void KeyAgreementTest::TearDown() {} + +void KeyAgreementTest::SetUpTestCase() +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(generator, nullptr); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + ecc224KeyPair_ = keyPair; + + OH_HCF_ObjDestroy(generator); + + HcfAsyKeyGenerator *generator2 = NULL; + res = HcfAsyKeyGeneratorCreate("ECC256", &generator2); + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(generator2, nullptr); + + HcfKeyPair *keyPair2 = NULL; + res = generator2->generateKeyPair(generator2, NULL, &keyPair2); + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair2, nullptr); + + ecc256KeyPair_ = keyPair2; + + OH_HCF_ObjDestroy(generator2); + + HcfAsyKeyGenerator *generator3 = NULL; + res = HcfAsyKeyGeneratorCreate("ECC384", &generator3); + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(generator3, nullptr); + + HcfKeyPair *keyPair3 = NULL; + res = generator3->generateKeyPair(generator3, NULL, &keyPair3); + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair3, nullptr); + + ecc384KeyPair_ = keyPair3; + + OH_HCF_ObjDestroy(generator3); + + HcfAsyKeyGenerator *generator4 = NULL; + res = HcfAsyKeyGeneratorCreate("ECC512", &generator4); + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(generator4, nullptr); + + HcfKeyPair *keyPair4 = NULL; + res = generator4->generateKeyPair(generator4, NULL, &keyPair4); + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair4, nullptr); + + ecc512KeyPair_ = keyPair4; + + OH_HCF_ObjDestroy(generator4); +} + +void KeyAgreementTest::TearDownTestCase() +{ + OH_HCF_ObjDestroy(ecc224KeyPair_); + OH_HCF_ObjDestroy(ecc256KeyPair_); + OH_HCF_ObjDestroy(ecc384KeyPair_); + OH_HCF_ObjDestroy(ecc512KeyPair_); +} + +HWTEST_F(KeyAgreementTest, KeyAgreementTest001, TestSize.Level0) +{ + HcfKeyAgreement *keyAgreement = NULL; + int32_t res = HcfKeyAgreementCreate("ECC224", &keyAgreement); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyAgreement, nullptr); + + OH_HCF_ObjDestroy(keyAgreement); +} + +HWTEST_F(KeyAgreementTest, KeyAgreementTest002, TestSize.Level0) +{ + HcfKeyAgreement *keyAgreement = NULL; + int32_t res = HcfKeyAgreementCreate("ECC256", &keyAgreement); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyAgreement, nullptr); + + OH_HCF_ObjDestroy(keyAgreement); +} + +HWTEST_F(KeyAgreementTest, KeyAgreementTest003, TestSize.Level0) +{ + HcfKeyAgreement *keyAgreement = NULL; + int32_t res = HcfKeyAgreementCreate("ECC384", &keyAgreement); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyAgreement, nullptr); + + OH_HCF_ObjDestroy(keyAgreement); +} + +HWTEST_F(KeyAgreementTest, KeyAgreementTest004, TestSize.Level0) +{ + HcfKeyAgreement *keyAgreement = NULL; + int32_t res = HcfKeyAgreementCreate("ECC512", &keyAgreement); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyAgreement, nullptr); + + OH_HCF_ObjDestroy(keyAgreement); +} + +HWTEST_F(KeyAgreementTest, KeyAgreementTest005, TestSize.Level0) +{ + HcfKeyAgreement *keyAgreement = NULL; + int32_t res = HcfKeyAgreementCreate(NULL, &keyAgreement); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + ASSERT_EQ(keyAgreement, nullptr); +} + +HWTEST_F(KeyAgreementTest, KeyAgreementTest006, TestSize.Level0) +{ + HcfKeyAgreement *keyAgreement = NULL; + int32_t res = HcfKeyAgreementCreate("ABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCD" + "ABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCD", &keyAgreement); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + ASSERT_EQ(keyAgreement, nullptr); +} + +HWTEST_F(KeyAgreementTest, KeyAgreementTest007, TestSize.Level0) +{ + HcfKeyAgreement *keyAgreement = NULL; + int32_t res = HcfKeyAgreementCreate("ECC257", &keyAgreement); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + ASSERT_EQ(keyAgreement, nullptr); +} + +HWTEST_F(KeyAgreementTest, KeyAgreementTest008, TestSize.Level0) +{ + int32_t res = HcfKeyAgreementCreate("ECC256", NULL); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); +} + +HWTEST_F(KeyAgreementTest, KeyAgreementTest101, TestSize.Level0) +{ + HcfKeyAgreement *keyAgreement = NULL; + int32_t res = HcfKeyAgreementCreate("ECC256", &keyAgreement); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyAgreement, nullptr); + + const char *className = keyAgreement->base.getClass(); + + ASSERT_NE(className, nullptr); + + OH_HCF_ObjDestroy(keyAgreement); +} + +HWTEST_F(KeyAgreementTest, KeyAgreementTest102, TestSize.Level0) +{ + HcfKeyAgreement *keyAgreement = NULL; + int32_t res = HcfKeyAgreementCreate("ECC256", &keyAgreement); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyAgreement, nullptr); + + keyAgreement->base.destroy((HcfObjectBase *)keyAgreement); +} + +HWTEST_F(KeyAgreementTest, KeyAgreementTest103, TestSize.Level0) +{ + HcfKeyAgreement *keyAgreement = NULL; + int32_t res = HcfKeyAgreementCreate("ECC256", &keyAgreement); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyAgreement, nullptr); + + keyAgreement->base.destroy(NULL); + + OH_HCF_ObjDestroy(keyAgreement); +} + +HWTEST_F(KeyAgreementTest, KeyAgreementTest104, TestSize.Level0) +{ + HcfKeyAgreement *keyAgreement = NULL; + int32_t res = HcfKeyAgreementCreate("ECC256", &keyAgreement); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyAgreement, nullptr); + + keyAgreement->base.destroy(&obj); + + OH_HCF_ObjDestroy(keyAgreement); +} + +HWTEST_F(KeyAgreementTest, KeyAgreementTest105, TestSize.Level0) +{ + HcfKeyAgreement *keyAgreement = NULL; + int32_t res = HcfKeyAgreementCreate("ECC256", &keyAgreement); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyAgreement, nullptr); + + const char *algName = keyAgreement->getAlgoName(keyAgreement); + + ASSERT_NE(algName, nullptr); + + OH_HCF_ObjDestroy(keyAgreement); +} + +HWTEST_F(KeyAgreementTest, KeyAgreementTest106, TestSize.Level0) +{ + HcfKeyAgreement *keyAgreement = NULL; + int32_t res = HcfKeyAgreementCreate("ECC256", &keyAgreement); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyAgreement, nullptr); + + const char *algName = keyAgreement->getAlgoName(NULL); + + ASSERT_EQ(algName, nullptr); + + OH_HCF_ObjDestroy(keyAgreement); +} + +HWTEST_F(KeyAgreementTest, KeyAgreementTest107, TestSize.Level0) +{ + HcfKeyAgreement *keyAgreement = NULL; + int32_t res = HcfKeyAgreementCreate("ECC256", &keyAgreement); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyAgreement, nullptr); + + const char *algName = keyAgreement->getAlgoName((HcfKeyAgreement *)(&obj)); + + ASSERT_EQ(algName, nullptr); + + OH_HCF_ObjDestroy(keyAgreement); +} + +HWTEST_F(KeyAgreementTest, KeyAgreementTest201, TestSize.Level0) +{ + HcfKeyAgreement *keyAgreement = NULL; + int32_t res = HcfKeyAgreementCreate("ECC224", &keyAgreement); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyAgreement, nullptr); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = keyAgreement->generateSecret(keyAgreement, ecc224KeyPair_->priKey, ecc224KeyPair_->pubKey, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(keyAgreement); +} + +HWTEST_F(KeyAgreementTest, KeyAgreementTest202, TestSize.Level0) +{ + HcfKeyAgreement *keyAgreement = NULL; + int32_t res = HcfKeyAgreementCreate("ECC256", &keyAgreement); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyAgreement, nullptr); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = keyAgreement->generateSecret(keyAgreement, ecc256KeyPair_->priKey, ecc256KeyPair_->pubKey, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(keyAgreement); +} + +HWTEST_F(KeyAgreementTest, KeyAgreementTest203, TestSize.Level0) +{ + HcfKeyAgreement *keyAgreement = NULL; + int32_t res = HcfKeyAgreementCreate("ECC384", &keyAgreement); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyAgreement, nullptr); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = keyAgreement->generateSecret(keyAgreement, ecc384KeyPair_->priKey, ecc384KeyPair_->pubKey, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(keyAgreement); +} + +HWTEST_F(KeyAgreementTest, KeyAgreementTest204, TestSize.Level0) +{ + HcfKeyAgreement *keyAgreement = NULL; + int32_t res = HcfKeyAgreementCreate("ECC512", &keyAgreement); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyAgreement, nullptr); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = keyAgreement->generateSecret(keyAgreement, ecc512KeyPair_->priKey, ecc512KeyPair_->pubKey, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(keyAgreement); +} + +HWTEST_F(KeyAgreementTest, KeyAgreementTest205, TestSize.Level0) +{ + HcfKeyAgreement *keyAgreement = NULL; + int32_t res = HcfKeyAgreementCreate("ECC256", &keyAgreement); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyAgreement, nullptr); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = keyAgreement->generateSecret(NULL, ecc256KeyPair_->priKey, ecc256KeyPair_->pubKey, &out); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + ASSERT_EQ(out.data, nullptr); + ASSERT_EQ(out.len, 0); + + OH_HCF_ObjDestroy(keyAgreement); +} + +HWTEST_F(KeyAgreementTest, KeyAgreementTest206, TestSize.Level0) +{ + HcfKeyAgreement *keyAgreement = NULL; + int32_t res = HcfKeyAgreementCreate("ECC256", &keyAgreement); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyAgreement, nullptr); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = keyAgreement->generateSecret((HcfKeyAgreement *)(&obj), ecc256KeyPair_->priKey, ecc256KeyPair_->pubKey, &out); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + ASSERT_EQ(out.data, nullptr); + ASSERT_EQ(out.len, 0); + + OH_HCF_ObjDestroy(keyAgreement); +} + +HWTEST_F(KeyAgreementTest, KeyAgreementTest207, TestSize.Level0) +{ + HcfKeyAgreement *keyAgreement = NULL; + int32_t res = HcfKeyAgreementCreate("ECC256", &keyAgreement); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyAgreement, nullptr); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = keyAgreement->generateSecret(keyAgreement, (HcfPriKey *)(&obj), ecc256KeyPair_->pubKey, &out); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + ASSERT_EQ(out.data, nullptr); + ASSERT_EQ(out.len, 0); + + OH_HCF_ObjDestroy(keyAgreement); +} + +HWTEST_F(KeyAgreementTest, KeyAgreementTest208, TestSize.Level0) +{ + HcfKeyAgreement *keyAgreement = NULL; + int32_t res = HcfKeyAgreementCreate("ECC256", &keyAgreement); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyAgreement, nullptr); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = keyAgreement->generateSecret(keyAgreement, ecc256KeyPair_->priKey, (HcfPubKey *)(&obj), &out); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + ASSERT_EQ(out.data, nullptr); + ASSERT_EQ(out.len, 0); + + OH_HCF_ObjDestroy(keyAgreement); +} + +HWTEST_F(KeyAgreementTest, KeyAgreementTest209, TestSize.Level0) +{ + HcfKeyAgreement *keyAgreement = NULL; + int32_t res = HcfKeyAgreementCreate("ECC256", &keyAgreement); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyAgreement, nullptr); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = keyAgreement->generateSecret(keyAgreement, NULL, NULL, &out); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + ASSERT_EQ(out.data, nullptr); + ASSERT_EQ(out.len, 0); + + OH_HCF_ObjDestroy(keyAgreement); +} + +HWTEST_F(KeyAgreementTest, KeyAgreementTest210, TestSize.Level0) +{ + HcfKeyAgreement *keyAgreement = NULL; + int32_t res = HcfKeyAgreementCreate("ECC256", &keyAgreement); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyAgreement, nullptr); + + res = keyAgreement->generateSecret(keyAgreement, ecc256KeyPair_->priKey, ecc256KeyPair_->pubKey, NULL); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + + OH_HCF_ObjDestroy(keyAgreement); +} diff --git a/test/unittest/src/crypto_ecc_sign_test.cpp b/test/unittest/src/crypto_ecc_sign_test.cpp new file mode 100644 index 0000000..bd91c18 --- /dev/null +++ b/test/unittest/src/crypto_ecc_sign_test.cpp @@ -0,0 +1,2814 @@ +/* + * Copyright (C) 2022 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 + +#include "asy_key_generator.h" +#include "blob.h" +#include "memory.h" +#include "securec.h" +#include "signature.h" + +using namespace std; +using namespace testing::ext; + +static const char *GetMockClass(void) +{ + return "HcfMock"; +} + +static HcfObjectBase obj = { + .getClass = GetMockClass, + .destroy = NULL +}; + +class EccSignTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + + static HcfKeyPair *ecc224KeyPair_; + static HcfKeyPair *ecc256KeyPair_; + static HcfKeyPair *ecc384KeyPair_; + static HcfKeyPair *ecc512KeyPair_; +}; + +HcfKeyPair *EccSignTest::ecc224KeyPair_ = nullptr; +HcfKeyPair *EccSignTest::ecc256KeyPair_ = nullptr; +HcfKeyPair *EccSignTest::ecc384KeyPair_ = nullptr; +HcfKeyPair *EccSignTest::ecc512KeyPair_ = nullptr; + +static const char *g_mockMessage = "hello world"; +static HcfBlob mockInput = { + .data = (uint8_t *)g_mockMessage, + .len = 12 +}; + +void EccSignTest::SetUp() {} +void EccSignTest::TearDown() {} + +void EccSignTest::SetUpTestCase() +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(generator, nullptr); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + ecc224KeyPair_ = keyPair; + + OH_HCF_ObjDestroy(generator); + + HcfAsyKeyGenerator *generator2 = NULL; + res = HcfAsyKeyGeneratorCreate("ECC256", &generator2); + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(generator2, nullptr); + + HcfKeyPair *keyPair2 = NULL; + res = generator2->generateKeyPair(generator2, NULL, &keyPair2); + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair2, nullptr); + + ecc256KeyPair_ = keyPair2; + + OH_HCF_ObjDestroy(generator2); + + HcfAsyKeyGenerator *generator3 = NULL; + res = HcfAsyKeyGeneratorCreate("ECC384", &generator3); + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(generator3, nullptr); + + HcfKeyPair *keyPair3 = NULL; + res = generator3->generateKeyPair(generator3, NULL, &keyPair3); + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair3, nullptr); + + ecc384KeyPair_ = keyPair3; + + OH_HCF_ObjDestroy(generator3); + + HcfAsyKeyGenerator *generator4 = NULL; + res = HcfAsyKeyGeneratorCreate("ECC512", &generator4); + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(generator4, nullptr); + + HcfKeyPair *keyPair4 = NULL; + res = generator4->generateKeyPair(generator4, NULL, &keyPair4); + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair4, nullptr); + + ecc512KeyPair_ = keyPair4; + + OH_HCF_ObjDestroy(generator4); +} + +void EccSignTest::TearDownTestCase() +{ + OH_HCF_ObjDestroy(ecc224KeyPair_); + OH_HCF_ObjDestroy(ecc256KeyPair_); + OH_HCF_ObjDestroy(ecc384KeyPair_); + OH_HCF_ObjDestroy(ecc512KeyPair_); +} + +HWTEST_F(EccSignTest, EccSignTest001, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC224|SHA1", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest002, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC224|SHA224", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest003, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC224|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest004, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC224|SHA384", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest005, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC224|SHA512", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest006, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA1", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest007, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA224", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest008, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest009, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA384", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest010, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA512", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest011, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC384|SHA1", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest012, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC384|SHA224", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest013, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC384|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest014, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC384|SHA384", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest015, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC384|SHA512", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest016, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC512|SHA1", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest017, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC512|SHA224", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest018, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC512|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest019, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC512|SHA384", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest020, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC512|SHA512", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest021, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate(NULL, &sign); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + ASSERT_EQ(sign, nullptr); +} + +HWTEST_F(EccSignTest, EccSignTest022, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCD" + "ABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCD", &sign); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + ASSERT_EQ(sign, nullptr); +} + +HWTEST_F(EccSignTest, EccSignTest023, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC257|SHA256", &sign); + + ASSERT_NE(res, HCF_SUCCESS); + ASSERT_EQ(sign, nullptr); +} + +HWTEST_F(EccSignTest, EccSignTest024, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA257", &sign); + + ASSERT_NE(res, HCF_SUCCESS); + ASSERT_EQ(sign, nullptr); +} + +HWTEST_F(EccSignTest, EccSignTest025, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|MD5", &sign); + + ASSERT_NE(res, HCF_SUCCESS); + ASSERT_EQ(sign, nullptr); +} + +HWTEST_F(EccSignTest, EccSignTest026, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256SHA256", &sign); + + ASSERT_NE(res, HCF_SUCCESS); + ASSERT_EQ(sign, nullptr); +} + +HWTEST_F(EccSignTest, EccSignTest027, TestSize.Level0) +{ + int32_t res = HcfSignCreate("ECC256|SHA256", NULL); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); +} + +HWTEST_F(EccSignTest, EccSignTest101, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + const char *className = sign->base.getClass(); + + ASSERT_NE(className, nullptr); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest102, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + sign->base.destroy((HcfObjectBase *)sign); +} + +HWTEST_F(EccSignTest, EccSignTest103, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + sign->base.destroy(NULL); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest104, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + sign->base.destroy(&obj); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest105, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + const char *algName = sign->getAlgoName(sign); + + ASSERT_NE(algName, nullptr); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest106, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + const char *algName = sign->getAlgoName(NULL); + + ASSERT_EQ(algName, nullptr); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest107, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + const char *algName = sign->getAlgoName((HcfSign *)(&obj)); + + ASSERT_EQ(algName, nullptr); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest201, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC224|SHA1", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc224KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest202, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC224|SHA224", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc224KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest203, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC224|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc224KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest204, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC224|SHA384", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc224KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest205, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC224|SHA512", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc224KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest206, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA1", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest207, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA224", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest208, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest209, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA384", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest210, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA512", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest211, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC384|SHA1", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc384KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest212, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC384|SHA224", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc384KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest213, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC384|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc384KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest214, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC384|SHA384", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc384KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest215, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC384|SHA512", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc384KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest216, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC512|SHA1", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc512KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest217, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC512|SHA224", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc512KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest218, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC512|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc512KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest219, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC512|SHA384", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc512KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest220, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC512|SHA512", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc512KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest221, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(NULL, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest222, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init((HcfSign *)(&obj), NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest223, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, NULL); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest224, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, (HcfPriKey *)(&obj)); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest301, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC224|SHA1", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc224KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest302, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC224|SHA224", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc224KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest303, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC224|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc224KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest304, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC224|SHA384", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc224KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest305, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC224|SHA512", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc224KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest306, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA1", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest307, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA224", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest308, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest309, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA384", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest310, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA512", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest311, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC384|SHA1", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc384KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest312, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC384|SHA224", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc384KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest313, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC384|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc384KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest314, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC384|SHA384", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc384KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest315, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC384|SHA512", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc384KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest316, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC512|SHA1", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc512KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest317, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC512|SHA224", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc512KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest318, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC512|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc512KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest319, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC512|SHA384", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc512KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest320, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC512|SHA512", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc512KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest321, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(NULL, &mockInput); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest322, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update((HcfSign *)(&obj), &mockInput); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest323, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, NULL); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest324, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob input = { + .data = NULL, + .len = 1 + }; + res = sign->update(sign, &input); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest325, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob input = { + .data = (uint8_t *)g_mockMessage, + .len = 0 + }; + res = sign->update(sign, &input); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest401, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC224|SHA1", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc224KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest402, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC224|SHA224", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc224KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest403, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC224|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc224KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest404, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC224|SHA384", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc224KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest405, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC224|SHA512", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc224KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest406, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA1", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest407, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA224", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest408, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest409, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA384", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest410, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA512", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest411, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC384|SHA1", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc384KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest412, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC384|SHA224", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc384KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest413, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC384|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc384KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest414, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC384|SHA384", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc384KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest415, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC384|SHA512", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc384KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest416, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC512|SHA1", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc512KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest417, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC512|SHA224", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc512KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest418, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC512|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc512KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest419, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC512|SHA384", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc512KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest420, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC512|SHA512", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc512KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest421, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC224|SHA1", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc224KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest422, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC224|SHA224", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc224KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest423, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC224|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc224KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest424, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC224|SHA384", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc224KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest425, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC224|SHA512", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc224KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest426, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA1", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest427, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA224", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest428, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest429, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA384", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest430, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA512", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest431, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC384|SHA1", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc384KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest432, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC384|SHA224", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc384KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest433, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC384|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc384KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest434, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC384|SHA384", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc384KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest435, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC384|SHA512", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc384KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest436, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC512|SHA1", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc512KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest437, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC512|SHA224", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc512KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest438, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC512|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc512KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest439, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC512|SHA384", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc512KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest440, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC512|SHA512", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc512KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest441, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(NULL, NULL, &out); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest442, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign((HcfSign *)(&obj), NULL, &out); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest443, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest444, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob input = { + .data = NULL, + .len = 1 + }; + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &input, &out); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest445, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob input = { + .data = (uint8_t *)g_mockMessage, + .len = 0 + }; + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &input, &out); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest446, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->sign(sign, NULL, NULL); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest447, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + const char *message = "hello world"; + HcfBlob input = { + .data = (uint8_t *)message, + .len = 12 + }; + res = sign->update(sign, &input); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + res = sign->update(sign, &input); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out2 = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out2); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC256|SHA256", &verify); + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + verify->init(verify, NULL, ecc256KeyPair_->pubKey); + ASSERT_EQ(res, HCF_SUCCESS); + + verify->update(verify, &input); + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, NULL, &out); + ASSERT_EQ(flag, true); + + verify->update(verify, &input); + ASSERT_EQ(res, HCF_SUCCESS); + + flag = verify->verify(verify, NULL, &out2); + ASSERT_EQ(flag, true); + + free(out.data); + free(out2.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccSignTest, EccSignTest448, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + const char *message = "hello world"; + HcfBlob input = { + .data = (uint8_t *)message, + .len = 12 + }; + res = sign->update(sign, &input); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &input); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out2 = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out2); + + free(out2.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest927, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(generator, nullptr); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + OH_HCF_ObjDestroy(generator); + + HcfSign *sign = NULL; + res = HcfSignCreate("ECC256|SHA256", &sign); + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + HcfParamsSpec params; + res = sign->init(sign, ¶ms, keyPair->priKey); + ASSERT_EQ(res, HCF_SUCCESS); + + const char *message = "hello world"; + HcfBlob input = { + .data = (uint8_t *)message, + .len = 12 + }; + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &input, &out); + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(EccSignTest, EccSignTest928, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(generator, nullptr); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + OH_HCF_ObjDestroy(generator); + + HcfSign *sign = NULL; + res = HcfSignCreate("ECC224|SHA256", &sign); + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + HcfParamsSpec params; + res = sign->init(sign, ¶ms, keyPair->priKey); + ASSERT_EQ(res, HCF_SUCCESS); + + const char *message = "hello world"; + HcfBlob input = { + .data = (uint8_t *)message, + .len = 12 + }; + res = sign->update(sign, &input); + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + free(out.data); + OH_HCF_ObjDestroy(sign); +} diff --git a/test/unittest/src/crypto_ecc_verify_test.cpp b/test/unittest/src/crypto_ecc_verify_test.cpp new file mode 100644 index 0000000..c8f6e0d --- /dev/null +++ b/test/unittest/src/crypto_ecc_verify_test.cpp @@ -0,0 +1,3470 @@ +/* + * Copyright (C) 2022 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 + +#include "asy_key_generator.h" +#include "blob.h" +#include "memory.h" +#include "securec.h" +#include "signature.h" + +using namespace std; +using namespace testing::ext; + +static const char *GetMockClass(void) +{ + return "HcfMock"; +} + +static HcfObjectBase obj = { + .getClass = GetMockClass, + .destroy = NULL +}; + +class EccVerifyTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + + static HcfKeyPair *ecc224KeyPair_; + static HcfKeyPair *ecc256KeyPair_; + static HcfKeyPair *ecc384KeyPair_; + static HcfKeyPair *ecc512KeyPair_; +}; + +HcfKeyPair *EccVerifyTest::ecc224KeyPair_ = nullptr; +HcfKeyPair *EccVerifyTest::ecc256KeyPair_ = nullptr; +HcfKeyPair *EccVerifyTest::ecc384KeyPair_ = nullptr; +HcfKeyPair *EccVerifyTest::ecc512KeyPair_ = nullptr; + +static const char *g_mockMessage = "hello world"; +static HcfBlob mockInput = { + .data = (uint8_t *)g_mockMessage, + .len = 12 +}; + +void EccVerifyTest::SetUp() {} +void EccVerifyTest::TearDown() {} + +void EccVerifyTest::SetUpTestCase() +{ + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("ECC224", &generator); + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(generator, nullptr); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair, nullptr); + + ecc224KeyPair_ = keyPair; + + OH_HCF_ObjDestroy(generator); + + HcfAsyKeyGenerator *generator2 = NULL; + res = HcfAsyKeyGeneratorCreate("ECC256", &generator2); + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(generator2, nullptr); + + HcfKeyPair *keyPair2 = NULL; + res = generator2->generateKeyPair(generator2, NULL, &keyPair2); + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair2, nullptr); + + ecc256KeyPair_ = keyPair2; + + OH_HCF_ObjDestroy(generator2); + + HcfAsyKeyGenerator *generator3 = NULL; + res = HcfAsyKeyGeneratorCreate("ECC384", &generator3); + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(generator3, nullptr); + + HcfKeyPair *keyPair3 = NULL; + res = generator3->generateKeyPair(generator3, NULL, &keyPair3); + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair3, nullptr); + + ecc384KeyPair_ = keyPair3; + + OH_HCF_ObjDestroy(generator3); + + HcfAsyKeyGenerator *generator4 = NULL; + res = HcfAsyKeyGeneratorCreate("ECC512", &generator4); + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(generator4, nullptr); + + HcfKeyPair *keyPair4 = NULL; + res = generator4->generateKeyPair(generator4, NULL, &keyPair4); + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(keyPair4, nullptr); + + ecc512KeyPair_ = keyPair4; + + OH_HCF_ObjDestroy(generator4); +} + +void EccVerifyTest::TearDownTestCase() +{ + OH_HCF_ObjDestroy(ecc224KeyPair_); + OH_HCF_ObjDestroy(ecc256KeyPair_); + OH_HCF_ObjDestroy(ecc384KeyPair_); + OH_HCF_ObjDestroy(ecc512KeyPair_); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest001, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC224|SHA1", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest002, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC224|SHA224", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest003, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC224|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest004, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC224|SHA384", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest005, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC224|SHA512", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest006, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256|SHA1", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest007, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256|SHA224", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest008, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest009, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256|SHA384", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest010, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256|SHA512", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest011, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC384|SHA1", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest012, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC384|SHA224", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest013, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC384|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest014, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC384|SHA384", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest015, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC384|SHA512", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest016, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC512|SHA1", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest017, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC512|SHA224", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest018, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC512|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest019, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC512|SHA384", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest020, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC512|SHA512", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest021, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate(NULL, &verify); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + ASSERT_EQ(verify, nullptr); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest022, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCD" + "ABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCDABCD", &verify); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + ASSERT_EQ(verify, nullptr); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest023, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC257|SHA256", &verify); + + ASSERT_NE(res, HCF_SUCCESS); + ASSERT_EQ(verify, nullptr); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest024, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256|SHA257", &verify); + + ASSERT_NE(res, HCF_SUCCESS); + ASSERT_EQ(verify, nullptr); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest025, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256|MD5", &verify); + + ASSERT_NE(res, HCF_SUCCESS); + ASSERT_EQ(verify, nullptr); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest026, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256SHA256", &verify); + + ASSERT_NE(res, HCF_SUCCESS); + ASSERT_EQ(verify, nullptr); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest027, TestSize.Level0) +{ + int32_t res = HcfVerifyCreate("ECC256|SHA256", NULL); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest101, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + const char *className = verify->base.getClass(); + + ASSERT_NE(className, nullptr); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest102, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + verify->base.destroy((HcfObjectBase *)verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest103, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + verify->base.destroy(NULL); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest104, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + verify->base.destroy(&obj); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest105, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + const char *algName = verify->getAlgoName(verify); + + ASSERT_NE(algName, nullptr); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest106, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + const char *algName = verify->getAlgoName(NULL); + + ASSERT_EQ(algName, nullptr); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest107, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + const char *algName = verify->getAlgoName((HcfVerify *)(&obj)); + + ASSERT_EQ(algName, nullptr); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest201, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC224|SHA1", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc224KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest202, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC224|SHA224", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc224KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest203, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC224|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc224KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest204, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC224|SHA384", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc224KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest205, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC224|SHA512", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc224KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest206, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256|SHA1", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc256KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest207, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256|SHA224", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc256KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest208, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc256KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest209, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256|SHA384", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc256KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest210, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256|SHA512", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc256KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest211, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC384|SHA1", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc384KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest212, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC384|SHA224", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc384KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest213, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC384|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc384KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest214, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC384|SHA384", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc384KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest215, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC384|SHA512", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc384KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest216, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC512|SHA1", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc512KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest217, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC512|SHA224", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc512KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest218, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC512|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc512KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest219, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC512|SHA384", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc512KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest220, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC512|SHA512", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc512KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest221, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(NULL, NULL, ecc256KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest222, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init((HcfVerify *)(&obj), NULL, ecc256KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest223, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, NULL); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest224, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, (HcfPubKey *)(&obj)); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest301, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC224|SHA1", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc224KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest302, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC224|SHA224", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc224KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest303, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC224|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc224KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest304, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC224|SHA384", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc224KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest305, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC224|SHA512", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc224KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest306, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256|SHA1", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc256KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest307, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256|SHA224", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc256KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest308, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc256KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest309, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256|SHA384", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc256KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest310, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256|SHA512", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc256KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest311, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC384|SHA1", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc384KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest312, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC384|SHA224", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc384KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest313, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC384|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc384KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest314, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC384|SHA384", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc384KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest315, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC384|SHA512", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc384KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest316, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC512|SHA1", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc512KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest317, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC512|SHA224", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc512KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest318, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC512|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc512KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest319, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC512|SHA384", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc512KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest320, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC512|SHA512", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc512KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest321, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc256KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(NULL, &mockInput); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest322, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc256KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update((HcfVerify *)(&obj), &mockInput); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest323, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc256KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, NULL); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest324, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc256KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob input = { + .data = NULL, + .len = 1 + }; + res = verify->update(verify, &input); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest325, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc256KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob input = { + .data = (uint8_t *)g_mockMessage, + .len = 0 + }; + res = verify->update(verify, &input); + + ASSERT_EQ(res, HCF_INVALID_PARAMS); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest401, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC224|SHA1", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc224KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC224|SHA1", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc224KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, NULL, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest402, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC224|SHA224", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc224KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC224|SHA224", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc224KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, NULL, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest403, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC224|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc224KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC224|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc224KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, NULL, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest404, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC224|SHA384", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc224KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC224|SHA384", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc224KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, NULL, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest405, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC224|SHA512", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc224KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC224|SHA512", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc224KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, NULL, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest406, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA1", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC256|SHA1", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc256KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, NULL, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest407, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA224", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC256|SHA224", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc256KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, NULL, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest408, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC256|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc256KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, NULL, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest409, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA384", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC256|SHA384", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc256KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, NULL, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest410, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA512", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC256|SHA512", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc256KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, NULL, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest411, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC384|SHA1", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc384KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC384|SHA1", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc384KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, NULL, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest412, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC384|SHA224", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc384KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC384|SHA224", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc384KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, NULL, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest413, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC384|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc384KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC384|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc384KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, NULL, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest414, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC384|SHA384", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc384KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC384|SHA384", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc384KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, NULL, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest415, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC384|SHA512", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc384KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC384|SHA512", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc384KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, NULL, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest416, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC512|SHA1", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc512KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC512|SHA1", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc512KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, NULL, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest417, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC512|SHA224", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc512KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC512|SHA224", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc512KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, NULL, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest418, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC512|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc512KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC512|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc512KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, NULL, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest419, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC512|SHA384", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc512KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC512|SHA384", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc512KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, NULL, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest420, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC512|SHA512", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc512KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC512|SHA512", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc512KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, NULL, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest421, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC224|SHA1", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc224KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC224|SHA1", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc224KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, &mockInput, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest422, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC224|SHA224", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc224KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC224|SHA224", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc224KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, &mockInput, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest423, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC224|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc224KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC224|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc224KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, &mockInput, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest424, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC224|SHA384", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc224KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC224|SHA384", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc224KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, &mockInput, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest425, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC224|SHA512", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc224KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC224|SHA512", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc224KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, &mockInput, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest426, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA1", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC256|SHA1", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc256KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, &mockInput, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest427, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA224", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC256|SHA224", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc256KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, &mockInput, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest428, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC256|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc256KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, &mockInput, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest429, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA384", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC256|SHA384", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc256KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, &mockInput, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest430, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA512", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC256|SHA512", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc256KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, &mockInput, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest431, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC384|SHA1", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc384KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC384|SHA1", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc384KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, &mockInput, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest432, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC384|SHA224", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc384KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC384|SHA224", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc384KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, &mockInput, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest433, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC384|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc384KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC384|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc384KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, &mockInput, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest434, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC384|SHA384", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc384KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC384|SHA384", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc384KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, &mockInput, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest435, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC384|SHA512", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc384KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC384|SHA512", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc384KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, &mockInput, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest436, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC512|SHA1", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc512KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC512|SHA1", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc512KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, &mockInput, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest437, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC512|SHA224", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc512KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC512|SHA224", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc512KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, &mockInput, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest438, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC512|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc512KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC512|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc512KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, &mockInput, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest439, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC512|SHA384", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc512KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC512|SHA384", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc512KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, &mockInput, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest440, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC512|SHA512", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc512KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, &mockInput, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC512|SHA512", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc512KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, &mockInput, &out); + + ASSERT_EQ(flag, true); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest441, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC256|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc256KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(NULL, NULL, &out); + + ASSERT_EQ(flag, false); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest442, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC256|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc256KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify((HcfVerify *)(&obj), NULL, &out); + + ASSERT_EQ(flag, false); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest443, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC256|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc256KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, NULL, &out); + + ASSERT_EQ(flag, false); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest444, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC256|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc256KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob input = { + .data = NULL, + .len = 1 + }; + bool flag = verify->verify(verify, &input, &out); + + ASSERT_EQ(flag, false); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest445, TestSize.Level0) +{ + HcfSign *sign = NULL; + int32_t res = HcfSignCreate("ECC256|SHA256", &sign); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(sign, nullptr); + + res = sign->init(sign, NULL, ecc256KeyPair_->priKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = sign->update(sign, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob out = { + .data = NULL, + .len = 0 + }; + res = sign->sign(sign, NULL, &out); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(out.data, nullptr); + ASSERT_NE(out.len, (const unsigned int)0); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("ECC256|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc256KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob input = { + .data = (uint8_t *)g_mockMessage, + .len = 0 + }; + bool flag = verify->verify(verify, &input, &out); + + ASSERT_EQ(flag, false); + + free(out.data); + OH_HCF_ObjDestroy(sign); + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest446, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc256KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + bool flag = verify->verify(verify, NULL, NULL); + + ASSERT_EQ(flag, false); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest447, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc256KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob mockOut = { + .data = NULL, + .len = 1 + }; + bool flag = verify->verify(verify, NULL, &mockOut); + + ASSERT_EQ(flag, false); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(EccVerifyTest, EccVerifyTest448, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("ECC256|SHA256", &verify); + + ASSERT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + res = verify->init(verify, NULL, ecc256KeyPair_->pubKey); + + ASSERT_EQ(res, HCF_SUCCESS); + + res = verify->update(verify, &mockInput); + + ASSERT_EQ(res, HCF_SUCCESS); + + HcfBlob mockOut = { + .data = (uint8_t *)g_mockMessage, + .len = 0 + }; + bool flag = verify->verify(verify, NULL, &mockOut); + + ASSERT_EQ(flag, false); + + OH_HCF_ObjDestroy(verify); +} diff --git a/test/unittest/src/crypto_mac_test.cpp b/test/unittest/src/crypto_mac_test.cpp new file mode 100644 index 0000000..6f1b4e8 --- /dev/null +++ b/test/unittest/src/crypto_mac_test.cpp @@ -0,0 +1,611 @@ +/* + * Copyright (C) 2022 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 +#include "securec.h" + +#include "mac.h" +#include "sym_key_generator.h" + +#include "log.h" +#include "memory.h" + +using namespace std; +using namespace testing::ext; + +class CryptoFrameworkHmacTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +static char g_testBigData[] = "VqRH5dzdeeturr5zN5vE77DtqjV7kNKbDJqk4mNqyYRTXymhjR\r\n" +"Yz8c2pNvJiCxyFwvLvWfPh2Y2eDAuxbdm2Dt4UzKJtNqEpNYKVZLiyH4a4MhR4BpFhvhJVHy2ALbYq2rW\r\n" +"LqJfNzA6v8kHNaFypNDMgX35kifyCiYkq85XUKDJCdewUzCZ2N8twC8Z9kL37K67bkL35VYFZSXyrNTdV\r\n" +"pB6kqPjwZYrjx5tXzMMgJW8ePqmAhZUVjtPGXTLVt8BUnaVRuWjD97xjS3VH9EwFeyrqJ46B92rkuGexY\r\n" +"cjXuvhHTnQNPbYfake7KMEWG2wgGLmZmjnakULhFgjt6TQhvCWMJAHYn8Zgczd3C3HkPrQgUXJgAiwf3r\r\n" +"jJbgbBpQkkbcfMBZZ3SSLe2J9jw6MkdEf3eBQX9rFVQSgBQgZ9KEW8XLb5kCTcyhRZPBbiHD4qQRyrwKT\r\n" +"mnGZqP5Aru6GDkhFk78jfjtk35HyB7AY7UZXkczRfVYAxa5Mk256MhAHkE3uAvPZTyY7N3qk9U7cLTrce\r\n" +"wJLH6wrymrMvQWgpvrBevMghnURZUcZAWUznDn56WnwGAzYAWmJqdXqAfcvgZwCFTjxdiaEZGpEyUrcS8\r\n" +"nr48ZeXS5aytz5Y7RnU5SxcHbgF8PerWVdftxmghPAvGkQ6f3dcXr9w9bbGqg5KJHyQCxabp8bjZpyFdb\r\n" +"VTq8DpQ6AJjxdjn8cuLTf9giGFxDjtQncicUdqP7YvVDr5AFgWc83cddyryVLZEBGAFfqbbKWF9KnPjRZ\r\n" +"AbuZ7SqrkxhQHu87Hxh3xHUHB8Lb3DGZ4vhnqaLnJBxFK8Ve4F2FfbgfHfQtALFDUWp6dSz8Hvdpj4CGw\r\n" +"FaSb8b5hTemaQRguYAqaUwJVvZ7G2AwkFnV9PHUngmybAFxg8HMAT3K7yAiQJWWqPxdGq8jXPAqZFNkGu\r\n" +"2mnJ5xfnY3z63PFk6TXU9Ga2YmHvtycXxwqMBEctQRa3zVWGVSrh3NF6jXa\r\n"; +constexpr uint32_t MAX_MAC_BLOB_LEN = 5000; + +void CryptoFrameworkHmacTest::SetUpTestCase() {} +void CryptoFrameworkHmacTest::TearDownTestCase() {} + +void CryptoFrameworkHmacTest::SetUp() // add init here, this will be called before test. +{ +} + +void CryptoFrameworkHmacTest::TearDown() // add destroy here, this will be called when test case done. +{ +} + +static void PrintfBlobInHex(uint8_t *data, size_t dataLen) +{ + for (size_t i = 0; i < dataLen; i++) { + printf("%02hhX", data[i]); + } + printf("\n"); +} + +HWTEST_F(CryptoFrameworkHmacTest, CryptoFrameworkHmacCreateTest002, TestSize.Level0) +{ + int32_t ret = 0; + ret = (int)HcfMacCreate("SHA1", nullptr); + EXPECT_NE(ret, 0); +} + +HWTEST_F(CryptoFrameworkHmacTest, CryptoFrameworkHmacAlgoSuppTest001, TestSize.Level0) +{ + int32_t ret = 0; + // create a SHA obj + HcfMac *macObj = nullptr; + ret = (int)HcfMacCreate("SHA1", &macObj); + EXPECT_EQ(ret, 0); + EXPECT_NE(macObj, nullptr); + OH_HCF_ObjDestroy(macObj); +} + +HWTEST_F(CryptoFrameworkHmacTest, CryptoFrameworkHmacAlgoSuppTest002, TestSize.Level0) +{ + int32_t ret = 0; + // create a SHA obj + HcfMac *macObj = nullptr; + ret = (int)HcfMacCreate("SHA3", &macObj); + EXPECT_NE(ret, 0); + EXPECT_EQ(macObj, nullptr); +} + +HWTEST_F(CryptoFrameworkHmacTest, CryptoFrameworkHmacAlgoSuppTest003, TestSize.Level0) +{ + int32_t ret = 0; + // create a SHA obj + HcfMac *macObj = nullptr; + ret = (int)HcfMacCreate(nullptr, &macObj); + EXPECT_NE(ret, 0); + EXPECT_EQ(macObj, nullptr); +} + +HWTEST_F(CryptoFrameworkHmacTest, CryptoFrameworkHmacAlgoNameTest001, TestSize.Level0) +{ + int32_t ret = 0; + // create a SHA obj + HcfMac *macObj = nullptr; + ret = (int)HcfMacCreate("SHA1", &macObj); + EXPECT_EQ(ret, 0); + EXPECT_NE(macObj, nullptr); + // test api functions + const char *algoName = macObj->getAlgoName(macObj); + ret = strcmp(algoName, "SHA1"); + EXPECT_EQ(ret, 0); + OH_HCF_ObjDestroy(macObj); +} + +HWTEST_F(CryptoFrameworkHmacTest, CryptoFrameworkHmacInitTest001, TestSize.Level0) +{ + int32_t ret = 0; + // create a SHA obj + HcfMac *macObj = nullptr; + ret = (int)HcfMacCreate("SHA1", &macObj); + EXPECT_EQ(ret, 0); + // set a nullptr key + HcfSymKey *key = nullptr; + // test api functions + ret = macObj->init(macObj, key); + EXPECT_NE(ret, 0); + OH_HCF_ObjDestroy(macObj); +} + +HWTEST_F(CryptoFrameworkHmacTest, CryptoFrameworkHmacInitTest002, TestSize.Level0) +{ + int32_t ret = 0; + // create a SHA obj + HcfMac *macObj = nullptr; + ret = (int)HcfMacCreate("SHA1", &macObj); + EXPECT_EQ(ret, 0); + // create a symKey generator + HcfSymKeyGenerator *generator = nullptr; + ret = (int)HcfSymKeyGeneratorCreate("AES128", &generator); + EXPECT_EQ(ret, 0); + // get sym key from preset keyBlob + uint8_t testKey[] = "abcdefghijklmnop"; + uint32_t testKeyLen = 16; + HcfSymKey *key = nullptr; + HcfBlob keyMaterialBlob = {.data = (uint8_t *)testKey, .len = testKeyLen}; + generator->convertSymKey(generator, &keyMaterialBlob, &key); + // test api functions + ret = macObj->init(macObj, (HcfSymKey *)key); + EXPECT_EQ(ret, 0); + OH_HCF_ObjDestroy(macObj); + OH_HCF_ObjDestroy(key); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(CryptoFrameworkHmacTest, CryptoFrameworkHmacUpdateTest001, TestSize.Level0) +{ + int32_t ret = 0; + // create a SHA1 obj + HcfMac *macObj = nullptr; + ret = (int)HcfMacCreate("SHA1", &macObj); + EXPECT_EQ(ret, 0); + // set input and output buf + uint8_t testData[] = "My test data"; + uint32_t testDataLen = 12; + // define input and output data in blob form + HcfBlob inBlob= {.data = (uint8_t *)testData, .len = testDataLen}; + // test api functions + ret = macObj->update(macObj, &inBlob); + EXPECT_NE(ret, 0); + OH_HCF_ObjDestroy(macObj); +} + +HWTEST_F(CryptoFrameworkHmacTest, CryptoFrameworkHmacUpdateTest002, TestSize.Level0) +{ + int32_t ret = 0; + // create a SHA1 obj + HcfMac *macObj = nullptr; + ret = (int)HcfMacCreate("SHA1", &macObj); + EXPECT_EQ(ret, 0); + // cteate key generator and set key text + HcfSymKeyGenerator *generator = nullptr; + ret = (int)HcfSymKeyGeneratorCreate("AES128", &generator); + EXPECT_EQ(ret, 0); + // get sym key from preset keyBlob + uint8_t testKey[] = "abcdefghijklmnop"; + uint32_t testKeyLen = 16; + HcfSymKey *key = nullptr; + HcfBlob keyMaterialBlob = {.data = (uint8_t *)testKey, .len = testKeyLen}; + generator->convertSymKey(generator, &keyMaterialBlob, &key); + // define input and output data in blob form + HcfBlob *inBlob= nullptr; + // test api functions + ret = macObj->init(macObj, (HcfSymKey *)key); + EXPECT_EQ(ret, 0); + ret = macObj->update(macObj, inBlob); + EXPECT_NE(ret, 0); + OH_HCF_ObjDestroy(macObj); + OH_HCF_ObjDestroy(key); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(CryptoFrameworkHmacTest, CryptoFrameworkHmacUpdateTest003, TestSize.Level0) +{ + int32_t ret = 0; + // create a API obj with SHA1 + HcfMac *macObj = nullptr; + ret = (int)HcfMacCreate("SHA1", &macObj); + EXPECT_EQ(ret, 0); + // cteate key generator and set key text + HcfSymKeyGenerator *generator = nullptr; + ret = (int)HcfSymKeyGeneratorCreate("AES128", &generator); + EXPECT_EQ(ret, 0); + // get sym key from preset keyBlob + uint8_t testKey[] = "abcdefghijklmnop"; + uint32_t testKeyLen = 16; + HcfSymKey *key = nullptr; + HcfBlob keyMaterialBlob = {.data = (uint8_t *)testKey, .len = testKeyLen}; + generator->convertSymKey(generator, &keyMaterialBlob, &key); + // set input and output buf + uint8_t testData[] = "My test data"; + uint32_t testDataLen = 12; + // define input and output data in blob form + HcfBlob inBlob= {.data = (uint8_t *)testData, .len = testDataLen}; + // test api functions + ret = macObj->init(macObj, (HcfSymKey *)key); + EXPECT_EQ(ret, 0); + ret = macObj->update(macObj, &inBlob); + EXPECT_EQ(ret, 0); + OH_HCF_ObjDestroy(macObj); + OH_HCF_ObjDestroy(key); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(CryptoFrameworkHmacTest, CryptoFrameworkHmacDoFinalTest001, TestSize.Level0) +{ + int32_t ret = 0; + // create a SHA1 obj + HcfMac *macObj = nullptr; + ret = (int)HcfMacCreate("SHA1", &macObj); + EXPECT_EQ(ret, 0); + // set input and output buf + uint8_t outBuf[20] = {0}; + HcfBlob outBlob = {.data = (uint8_t *)outBuf, .len = 0}; + // test api functions + ret = macObj->doFinal(macObj, &outBlob); + EXPECT_NE(ret, 0); + // destroy the API obj and blob data + OH_HCF_ObjDestroy(macObj); +} + +HWTEST_F(CryptoFrameworkHmacTest, CryptoFrameworkHmacDoFinalTest002, TestSize.Level0) +{ + int32_t ret = 0; + // create a SHA1 obj + HcfMac *macObj = nullptr; + ret = (int)HcfMacCreate("SHA1", &macObj); + EXPECT_EQ(ret, 0); + // cteate key generator and set key text + HcfSymKeyGenerator *generator = nullptr; + ret = (int)HcfSymKeyGeneratorCreate("AES128", &generator); + EXPECT_EQ(ret, 0); + // get sym key from preset keyBlob + uint8_t testKey[] = "abcdefghijklmnop"; + uint32_t testKeyLen = 16; + HcfSymKey *key = nullptr; + HcfBlob keyMaterialBlob = {.data = (uint8_t *)testKey, .len = testKeyLen}; + generator->convertSymKey(generator, &keyMaterialBlob, &key); + printf("get symkey finish"); + // set input and output buf + uint8_t outBuf[20] = {0}; + HcfBlob outBlob = {.data = (uint8_t *)outBuf, .len = 0}; + + // test api functions + ret = macObj->init(macObj, (HcfSymKey *)key); + EXPECT_EQ(ret, 0); + printf("test init finish"); + + ret = macObj->doFinal(macObj, &outBlob); + EXPECT_EQ(ret, 0); + printf("test dofinal finish"); + PrintfBlobInHex(outBlob.data, outBlob.len); + + // destroy the API obj and blob data + HcfBlobDataClearAndFree(&outBlob); + printf("HcfBlobDataClearAndFree finish"); + OH_HCF_ObjDestroy(macObj); + printf("OH_HCF_ObjDestroy macObj finish"); + OH_HCF_ObjDestroy(key); + printf("OH_HCF_ObjDestroy key finish"); + OH_HCF_ObjDestroy(generator); + printf("test finish"); +} + +HWTEST_F(CryptoFrameworkHmacTest, CryptoFrameworkHmacDoFinalTest003, TestSize.Level0) +{ + int32_t ret = 0; + // create a SHA1 obj + HcfMac *macObj = nullptr; + ret = (int)HcfMacCreate("SHA1", &macObj); + EXPECT_EQ(ret, 0); + // cteate key generator + HcfSymKeyGenerator *generator = nullptr; + ret = (int)HcfSymKeyGeneratorCreate("AES128", &generator); + EXPECT_EQ(ret, 0); + // get sym key from preset keyBlob + uint8_t testKey[] = "abcdefghijklmnop"; + uint32_t testKeyLen = 16; + HcfSymKey *key = nullptr; + HcfBlob keyMaterialBlob = {.data = (uint8_t *)testKey, .len = testKeyLen}; + generator->convertSymKey(generator, &keyMaterialBlob, &key); + // set input and output buf + uint8_t testData[] = "My test data"; + uint32_t testDataLen = 12; + uint8_t outBuf[20] = {0}; + // define input and output data in blob form + HcfBlob inBlob= {.data = (uint8_t *)testData, .len = testDataLen}; + HcfBlob outBlob = {.data = (uint8_t *)outBuf, .len = 0}; + // test api functions + ret = macObj->init(macObj, (HcfSymKey *)key); + EXPECT_EQ(ret, 0); + ret = macObj->update(macObj, &inBlob); + EXPECT_EQ(ret, 0); + ret = macObj->doFinal(macObj, &outBlob); + EXPECT_EQ(ret, 0); + // destroy the API obj and blob data + HcfBlobDataClearAndFree(&outBlob); + OH_HCF_ObjDestroy(macObj); + OH_HCF_ObjDestroy(key); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(CryptoFrameworkHmacTest, CryptoFrameworkHmacDoFinalTest004, TestSize.Level0) +{ + int32_t ret = 0; + // create a SHA1 obj + HcfMac *macObj = nullptr; + ret = (int)HcfMacCreate("SHA256", &macObj); + EXPECT_EQ(ret, 0); + // cteate key generator + HcfSymKeyGenerator *generator = nullptr; + ret = (int)HcfSymKeyGeneratorCreate("AES128", &generator); + EXPECT_EQ(ret, 0); + // get sym key from preset keyBlob + uint8_t testKey[] = "abcdefghijklmnop"; + uint32_t testKeyLen = 16; + HcfSymKey *key = nullptr; + HcfBlob keyMaterialBlob = {.data = (uint8_t *)testKey, .len = testKeyLen}; + generator->convertSymKey(generator, &keyMaterialBlob, &key); + // set input and output buf + uint8_t outBuf[20] = {0}; + // define input and output data in blob form + HcfBlob inBlob= {.data = (uint8_t *)g_testBigData, .len = strnlen(g_testBigData, MAX_MAC_BLOB_LEN)}; + HcfBlob outBlob = {.data = (uint8_t *)outBuf, .len = 0}; + // test api functions + ret = macObj->init(macObj, (HcfSymKey *)key); + EXPECT_EQ(ret, 0); + ret = macObj->update(macObj, &inBlob); + EXPECT_EQ(ret, 0); + ret = macObj->doFinal(macObj, &outBlob); + EXPECT_EQ(ret, 0); + PrintfBlobInHex(outBlob.data, outBlob.len); + // destroy the API obj and blob data + HcfBlobDataClearAndFree(&outBlob); + OH_HCF_ObjDestroy(macObj); + OH_HCF_ObjDestroy(key); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(CryptoFrameworkHmacTest, CryptoFrameworkHmacLenTest001, TestSize.Level0) +{ + int32_t ret = 0; + // create a SHA1 obj + HcfMac *macObj = nullptr; + ret = (int)HcfMacCreate("SHA1", &macObj); + EXPECT_EQ(ret, 0); + // test api functions + ret = macObj->getMacLength(macObj); + EXPECT_EQ(ret, 0); + OH_HCF_ObjDestroy(macObj); +} + +HWTEST_F(CryptoFrameworkHmacTest, CryptoFrameworkHmacLenTest002, TestSize.Level0) +{ + int32_t ret = 0; + // create a SHA1 obj + HcfMac *macObj = nullptr; + ret = (int)HcfMacCreate("SHA1", &macObj); + EXPECT_EQ(ret, 0); + // cteate key generator + HcfSymKeyGenerator *generator = nullptr; + ret = (int)HcfSymKeyGeneratorCreate("AES128", &generator); + EXPECT_EQ(ret, 0); + // get sym key from preset keyBlob + uint8_t testKey[] = "abcdefghijklmnop"; + uint32_t testKeyLen = 16; + HcfSymKey *key = nullptr; + HcfBlob keyMaterialBlob = {.data = (uint8_t *)testKey, .len = testKeyLen}; + generator->convertSymKey(generator, &keyMaterialBlob, &key); + // test api functions + ret = macObj->init(macObj, (HcfSymKey *)key); + EXPECT_EQ(ret, 0); + ret = macObj->getMacLength(macObj); + EXPECT_EQ(ret, 20); + OH_HCF_ObjDestroy(macObj); + OH_HCF_ObjDestroy(key); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(CryptoFrameworkHmacTest, CryptoFrameworkHmacAlgoTest001, TestSize.Level0) +{ + int32_t ret = 0; + // create a SHA1 obj + HcfMac *macObj = nullptr; + ret = (int)HcfMacCreate("SHA1", &macObj); + EXPECT_EQ(ret, 0); + // create a symKey generator + HcfSymKeyGenerator *generator = nullptr; + ret = (int)HcfSymKeyGeneratorCreate("AES128", &generator); + EXPECT_EQ(ret, 0); + // set key data and convert it to key obj + uint8_t testKey[] = "abcdefghijklmnop"; + uint32_t testKeyLen = 16; + HcfSymKey *key = nullptr; + HcfBlob keyMaterialBlob = {.data = (uint8_t *)testKey, .len = testKeyLen}; + generator->convertSymKey(generator, &keyMaterialBlob, &key); + // set input and output blob + uint8_t testData[] = "My test data"; + uint32_t testDataLen = 12; + uint8_t outBuf[20] = {0}; + HcfBlob inBlob= {.data = (uint8_t *)testData, .len = testDataLen}; + HcfBlob outBlob = {.data = (uint8_t *)outBuf, .len = 0}; + // test api funcitons + ret = macObj->init(macObj, (HcfSymKey *)key); + EXPECT_EQ(ret, 0); + ret = macObj->update(macObj, &inBlob); + EXPECT_EQ(ret, 0); + ret = macObj->doFinal(macObj, &outBlob); + EXPECT_EQ(ret, 0); + ret = macObj->getMacLength(macObj); + EXPECT_EQ(ret, 20); + // destroy the API obj and blob data + HcfBlobDataClearAndFree(&outBlob); + OH_HCF_ObjDestroy(macObj); + OH_HCF_ObjDestroy(key); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(CryptoFrameworkHmacTest, CryptoFrameworkHmacAlgoTest002, TestSize.Level0) +{ + int32_t ret = 0; + // create a SHA1 obj + HcfMac *macObj = nullptr; + ret = (int)HcfMacCreate("SHA224", &macObj); + EXPECT_EQ(ret, 0); + // create a symKey generator + HcfSymKeyGenerator *generator = nullptr; + ret = (int)HcfSymKeyGeneratorCreate("AES128", &generator); + EXPECT_EQ(ret, 0); + // set key data and convert it to key obj + uint8_t testKey[] = "abcdefghijklmnop"; + uint32_t testKeyLen = 16; + HcfSymKey *key = nullptr; + HcfBlob keyMaterialBlob = {.data = (uint8_t *)testKey, .len = testKeyLen}; + generator->convertSymKey(generator, &keyMaterialBlob, &key); + // set input and output blob + uint8_t testData[] = "My test data"; + uint32_t testDataLen = 12; + uint8_t outBuf[28] = {0}; + HcfBlob inBlob= {.data = (uint8_t *)testData, .len = testDataLen}; + HcfBlob outBlob = {.data = (uint8_t *)outBuf, .len = 0}; + // test api funcitons + ret = macObj->init(macObj, (HcfSymKey *)key); + EXPECT_EQ(ret, 0); + ret = macObj->update(macObj, &inBlob); + EXPECT_EQ(ret, 0); + ret = macObj->doFinal(macObj, &outBlob); + EXPECT_EQ(ret, 0); + ret = macObj->getMacLength(macObj); + EXPECT_EQ(ret, 28); + // destroy the API obj and blob data + HcfBlobDataClearAndFree(&outBlob); + OH_HCF_ObjDestroy(macObj); + OH_HCF_ObjDestroy(key); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(CryptoFrameworkHmacTest, CryptoFrameworkHmacAlgoTest003, TestSize.Level0) +{ + int32_t ret = 0; + // create a SHA1 obj + HcfMac *macObj = nullptr; + ret = (int)HcfMacCreate("SHA256", &macObj); + EXPECT_EQ(ret, 0); + // create a symKey generator + HcfSymKeyGenerator *generator = nullptr; + ret = (int)HcfSymKeyGeneratorCreate("AES128", &generator); + EXPECT_EQ(ret, 0); + // set key data and convert it to key obj + uint8_t testKey[] = "abcdefghijklmnop"; + uint32_t testKeyLen = 16; + HcfSymKey *key = nullptr; + HcfBlob keyMaterialBlob = {.data = (uint8_t *)testKey, .len = testKeyLen}; + generator->convertSymKey(generator, &keyMaterialBlob, &key); + // set input and output blob + uint8_t testData[] = "My test data"; + uint32_t testDataLen = 12; + uint8_t outBuf[32] = {0}; + HcfBlob inBlob= {.data = (uint8_t *)testData, .len = testDataLen}; + HcfBlob outBlob = {.data = (uint8_t *)outBuf, .len = 0}; + // test api funcitons + ret = macObj->init(macObj, (HcfSymKey *)key); + EXPECT_EQ(ret, 0); + ret = macObj->update(macObj, &inBlob); + EXPECT_EQ(ret, 0); + ret = macObj->doFinal(macObj, &outBlob); + EXPECT_EQ(ret, 0); + ret = macObj->getMacLength(macObj); + EXPECT_EQ(ret, 32); + // destroy the API obj and blob data + HcfBlobDataClearAndFree(&outBlob); + OH_HCF_ObjDestroy(macObj); + OH_HCF_ObjDestroy(key); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(CryptoFrameworkHmacTest, CryptoFrameworkHmacAlgoTest004, TestSize.Level0) +{ + int32_t ret = 0; + // create a SHA1 obj + HcfMac *macObj = nullptr; + ret = (int)HcfMacCreate("SHA384", &macObj); + EXPECT_EQ(ret, 0); + // create a symKey generator + HcfSymKeyGenerator *generator = nullptr; + ret = (int)HcfSymKeyGeneratorCreate("AES128", &generator); + EXPECT_EQ(ret, 0); + // set key data and convert it to key obj + uint8_t testKey[] = "abcdefghijklmnop"; + uint32_t testKeyLen = 16; + HcfSymKey *key = nullptr; + HcfBlob keyMaterialBlob = {.data = (uint8_t *)testKey, .len = testKeyLen}; + generator->convertSymKey(generator, &keyMaterialBlob, &key); + // set input and output blob + uint8_t testData[] = "My test data"; + uint32_t testDataLen = 12; + uint8_t outBuf[48] = {0}; + HcfBlob inBlob= {.data = (uint8_t *)testData, .len = testDataLen}; + HcfBlob outBlob = {.data = (uint8_t *)outBuf, .len = 0}; + // test api funcitons + ret = macObj->init(macObj, (HcfSymKey *)key); + EXPECT_EQ(ret, 0); + ret = macObj->update(macObj, &inBlob); + EXPECT_EQ(ret, 0); + ret = macObj->doFinal(macObj, &outBlob); + EXPECT_EQ(ret, 0); + ret = macObj->getMacLength(macObj); + EXPECT_EQ(ret, 48); + // destroy the API obj and blob data + HcfBlobDataClearAndFree(&outBlob); + OH_HCF_ObjDestroy(macObj); + OH_HCF_ObjDestroy(key); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(CryptoFrameworkHmacTest, CryptoFrameworkHmacAlgoTest005, TestSize.Level0) +{ + int32_t ret = 0; + // create a SHA1 obj + HcfMac *macObj = nullptr; + ret = (int)HcfMacCreate("SHA512", &macObj); + EXPECT_EQ(ret, 0); + // create a symKey generator + HcfSymKeyGenerator *generator = nullptr; + ret = (int)HcfSymKeyGeneratorCreate("AES128", &generator); + EXPECT_EQ(ret, 0); + // set key data and convert it to key obj + uint8_t testKey[] = "abcdefghijklmnop"; + uint32_t testKeyLen = 16; + HcfSymKey *key = nullptr; + HcfBlob keyMaterialBlob = {.data = (uint8_t *)testKey, .len = testKeyLen}; + generator->convertSymKey(generator, &keyMaterialBlob, &key); + // set input and output blob + uint8_t testData[] = "My test data"; + uint32_t testDataLen = 12; + uint8_t outBuf[64] = {0}; + HcfBlob inBlob= {.data = (uint8_t *)testData, .len = testDataLen}; + HcfBlob outBlob = {.data = (uint8_t *)outBuf, .len = 0}; + // test api funcitons + ret = macObj->init(macObj, (HcfSymKey *)key); + EXPECT_EQ(ret, 0); + ret = macObj->update(macObj, &inBlob); + EXPECT_EQ(ret, 0); + ret = macObj->doFinal(macObj, &outBlob); + EXPECT_EQ(ret, 0); + ret = macObj->getMacLength(macObj); + EXPECT_EQ(ret, 64); + // destroy the API obj and blob data + HcfBlobDataClearAndFree(&outBlob); + OH_HCF_ObjDestroy(macObj); + OH_HCF_ObjDestroy(key); + OH_HCF_ObjDestroy(generator); +} \ No newline at end of file diff --git a/test/unittest/src/crypto_md_test.cpp b/test/unittest/src/crypto_md_test.cpp new file mode 100644 index 0000000..72ddd61 --- /dev/null +++ b/test/unittest/src/crypto_md_test.cpp @@ -0,0 +1,406 @@ +/* + * Copyright (C) 2022 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 "md.h" + +#include "log.h" +#include "memory.h" + +using namespace std; +using namespace testing::ext; + +class CryptoFrameworkMdTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +static char g_testBigData[] = "VqRH5dzdeeturr5zN5vE77DtqjV7kNKbDJqk4mNqyYRTXymhjR\r\n" +"Yz8c2pNvJiCxyFwvLvWfPh2Y2eDAuxbdm2Dt4UzKJtNqEpNYKVZLiyH4a4MhR4BpFhvhJVHy2ALbYq2rW\r\n" +"LqJfNzA6v8kHNaFypNDMgX35kifyCiYkq85XUKDJCdewUzCZ2N8twC8Z9kL37K67bkL35VYFZSXyrNTdV\r\n" +"pB6kqPjwZYrjx5tXzMMgJW8ePqmAhZUVjtPGXTLVt8BUnaVRuWjD97xjS3VH9EwFeyrqJ46B92rkuGexY\r\n" +"cjXuvhHTnQNPbYfake7KMEWG2wgGLmZmjnakULhFgjt6TQhvCWMJAHYn8Zgczd3C3HkPrQgUXJgAiwf3r\r\n" +"jJbgbBpQkkbcfMBZZ3SSLe2J9jw6MkdEf3eBQX9rFVQSgBQgZ9KEW8XLb5kCTcyhRZPBbiHD4qQRyrwKT\r\n" +"mnGZqP5Aru6GDkhFk78jfjtk35HyB7AY7UZXkczRfVYAxa5Mk256MhAHkE3uAvPZTyY7N3qk9U7cLTrce\r\n" +"wJLH6wrymrMvQWgpvrBevMghnURZUcZAWUznDn56WnwGAzYAWmJqdXqAfcvgZwCFTjxdiaEZGpEyUrcS8\r\n" +"nr48ZeXS5aytz5Y7RnU5SxcHbgF8PerWVdftxmghPAvGkQ6f3dcXr9w9bbGqg5KJHyQCxabp8bjZpyFdb\r\n" +"VTq8DpQ6AJjxdjn8cuLTf9giGFxDjtQncicUdqP7YvVDr5AFgWc83cddyryVLZEBGAFfqbbKWF9KnPjRZ\r\n" +"AbuZ7SqrkxhQHu87Hxh3xHUHB8Lb3DGZ4vhnqaLnJBxFK8Ve4F2FfbgfHfQtALFDUWp6dSz8Hvdpj4CGw\r\n" +"FaSb8b5hTemaQRguYAqaUwJVvZ7G2AwkFnV9PHUngmybAFxg8HMAT3K7yAiQJWWqPxdGq8jXPAqZFNkGu\r\n" +"2mnJ5xfnY3z63PFk6TXU9Ga2YmHvtycXxwqMBEctQRa3zVWGVSrh3NF6jXa\r\n"; +constexpr uint32_t MAX_MD_BLOB_LEN = 5000; + +void CryptoFrameworkMdTest::SetUpTestCase() {} +void CryptoFrameworkMdTest::TearDownTestCase() {} + +void CryptoFrameworkMdTest::SetUp() // add init here, this will be called before test. +{ +} + +void CryptoFrameworkMdTest::TearDown() // add destroy here, this will be called when test case done. +{ +} + +static void PrintfBlobInHex(uint8_t *data, size_t dataLen) +{ + for (size_t i = 0; i < dataLen; i++) { + printf("%02hhX", data[i]); + } + printf("\n"); +} + +HWTEST_F(CryptoFrameworkMdTest, CryptoFrameworkMdCreateTest001, TestSize.Level0) +{ + int32_t ret = 0; + // create a SHA1 obj + ret = (int)HcfMdCreate("SHA1", nullptr); + EXPECT_NE(ret, 0); +} + +HWTEST_F(CryptoFrameworkMdTest, CryptoFrameworkMdAlgoSuppTest001, TestSize.Level0) +{ + int32_t ret = 0; + // create a SHA1 obj + HcfMd *mdObj = nullptr; + ret = (int)HcfMdCreate("SHA1", &mdObj); + EXPECT_EQ(ret, 0); + EXPECT_NE(mdObj, nullptr); + OH_HCF_ObjDestroy(mdObj); +} + +HWTEST_F(CryptoFrameworkMdTest, CryptoFrameworkMdAlgoSuppTest002, TestSize.Level0) +{ + int32_t ret = 0; + // create a SHA3 obj (not supported) + HcfMd *mdObj = nullptr; + ret = (int)HcfMdCreate("SHA3", &mdObj); + EXPECT_NE(ret, 0); + EXPECT_EQ(mdObj, nullptr); +} + +HWTEST_F(CryptoFrameworkMdTest, CryptoFrameworkMdAlgoSuppTest003, TestSize.Level0) +{ + int32_t ret = 0; + // create an obj with null algoInput (not supported) + HcfMd *mdObj = nullptr; + ret = (int)HcfMdCreate(nullptr, &mdObj); + EXPECT_NE(ret, 0); + EXPECT_EQ(mdObj, nullptr); +} + +HWTEST_F(CryptoFrameworkMdTest, CryptoFrameworkMdAlgoNameTest001, TestSize.Level0) +{ + int32_t ret = 0; + // create a SHA1 obj + HcfMd *mdObj = nullptr; + ret = (int)HcfMdCreate("SHA1", &mdObj); + EXPECT_EQ(ret, 0); + EXPECT_NE(mdObj, nullptr); + // test api functions + const char *algoName = mdObj->getAlgoName(mdObj); + ret = strcmp(algoName, "SHA1"); + EXPECT_EQ(ret, 0); + OH_HCF_ObjDestroy(mdObj); +} + +HWTEST_F(CryptoFrameworkMdTest, CryptoFrameworkMdUpdateTest001, TestSize.Level0) +{ + int32_t ret = 0; + // create a SHA1 obj + HcfMd *mdObj = nullptr; + ret = (int)HcfMdCreate("SHA1", &mdObj); + EXPECT_EQ(ret, 0); + // define input and output data in blob form + HcfBlob *inBlob= nullptr; + // test api functions + ret = mdObj->update(mdObj, inBlob); + EXPECT_NE(ret, 0); + OH_HCF_ObjDestroy(mdObj); +} + +HWTEST_F(CryptoFrameworkMdTest, CryptoFrameworkMdUpdateTest002, TestSize.Level0) +{ + int32_t ret = 0; + // create a SHA1 obj + HcfMd *mdObj = nullptr; + ret = (int)HcfMdCreate("SHA1", &mdObj); + EXPECT_EQ(ret, 0); + // set input and output buf + uint8_t testData[] = "My test data"; + uint32_t testDataLen = 12; + // define input and output data in blob form + HcfBlob inBlob= {.data = (uint8_t *)testData, .len = testDataLen}; + // test api functions + ret = mdObj->update(mdObj, &inBlob); + EXPECT_EQ(ret, 0); + OH_HCF_ObjDestroy(mdObj); +} + +HWTEST_F(CryptoFrameworkMdTest, CryptoFrameworkMdDoFinalTest001, TestSize.Level0) +{ + int32_t ret = 0; + // create a SHA1 obj + HcfMd *mdObj = nullptr; + ret = (int)HcfMdCreate("SHA1", &mdObj); + EXPECT_EQ(ret, 0); + // set input and output buf + uint8_t outBuf[20] = {0}; + HcfBlob outBlob = {.data = (uint8_t *)outBuf, .len = 0}; + // test api functions + ret = mdObj->doFinal(mdObj, &outBlob); + EXPECT_EQ(ret, 0); + // destroy the API obj and blob data + HcfBlobDataClearAndFree(&outBlob); + OH_HCF_ObjDestroy(mdObj); +} + +HWTEST_F(CryptoFrameworkMdTest, CryptoFrameworkMdDoFinalTest002, TestSize.Level0) +{ + int32_t ret = 0; + // create a SHA1 obj + HcfMd *mdObj = nullptr; + ret = (int)HcfMdCreate("SHA1", &mdObj); + EXPECT_EQ(ret, 0); + // set input and output buf + uint8_t testData[] = "My test data"; + uint32_t testDataLen = 12; + uint8_t outBuf[20] = {0}; + // define input and output data in blob form + HcfBlob inBlob= {.data = (uint8_t *)testData, .len = testDataLen}; + HcfBlob outBlob = {.data = (uint8_t *)outBuf, .len = 0}; + // test api functions + ret = mdObj->update(mdObj, &inBlob); + EXPECT_EQ(ret, 0); + ret = mdObj->doFinal(mdObj, &outBlob); + EXPECT_EQ(ret, 0); + // destroy the API obj and blob data + HcfBlobDataClearAndFree(&outBlob); + OH_HCF_ObjDestroy(mdObj); +} + +HWTEST_F(CryptoFrameworkMdTest, CryptoFrameworkMdDoFinalTest003, TestSize.Level0) +{ + int32_t ret = 0; + // create a SHA1 obj + HcfMd *mdObj = nullptr; + ret = (int)HcfMdCreate("SHA256", &mdObj); + EXPECT_EQ(ret, 0); + // set input and output buf + uint8_t outBuf[20] = {0}; + // define input and output data in blob form + HcfBlob inBlob= {.data = (uint8_t *)g_testBigData, .len = strnlen(g_testBigData, MAX_MD_BLOB_LEN)}; + HcfBlob outBlob = {.data = (uint8_t *)outBuf, .len = 0}; + // test api functions + ret = mdObj->update(mdObj, &inBlob); + EXPECT_EQ(ret, 0); + ret = mdObj->doFinal(mdObj, &outBlob); + EXPECT_EQ(ret, 0); + PrintfBlobInHex(outBlob.data, outBlob.len); + // destroy the API obj and blob data + HcfBlobDataClearAndFree(&outBlob); + OH_HCF_ObjDestroy(mdObj); +} + +HWTEST_F(CryptoFrameworkMdTest, CryptoFrameworkMdLenTest001, TestSize.Level0) +{ + int32_t ret = 0; + // create a API obj with SHA1 + HcfMd *mdObj = nullptr; + ret = (int)HcfMdCreate("SHA1", &mdObj); + EXPECT_EQ(ret, 0); + // test api functions + ret = mdObj->getMdLength(mdObj); + EXPECT_EQ(ret, 20); + OH_HCF_ObjDestroy(mdObj); +} + +HWTEST_F(CryptoFrameworkMdTest, CryptoFrameworkMdAlgoTest001, TestSize.Level0) +{ + int32_t ret = 0; + // create a API obj with SHA1 + HcfMd *mdObj = nullptr; + ret = (int)HcfMdCreate("SHA1", &mdObj); + EXPECT_EQ(ret, 0); + // set input and output buf + uint8_t testData[] = "My test data"; + size_t testDataLen = 12; + uint8_t outBuf[20] = {0}; + // define input and output data in blob form + struct HcfBlob inBlob= {.data = (uint8_t *)testData, .len = testDataLen}; + struct HcfBlob outBlob = {.data = (uint8_t *)outBuf, .len = 0}; + // test api functions + ret = mdObj->update(mdObj, &inBlob); + EXPECT_EQ(ret, 0); + ret = mdObj->doFinal(mdObj, &outBlob); + EXPECT_EQ(ret, 0); + ret = mdObj->getMdLength(mdObj); + EXPECT_EQ(ret, 20); + // destroy the API obj and blob data + HcfBlobDataClearAndFree(&outBlob); + OH_HCF_ObjDestroy(mdObj); +} + +HWTEST_F(CryptoFrameworkMdTest, CryptoFrameworkMdAlgoTest002, TestSize.Level0) +{ + int32_t ret = 0; + // create a API obj with SHA1 + HcfMd *mdObj = nullptr; + ret = (int)HcfMdCreate("SHA224", &mdObj); + EXPECT_EQ(ret, 0); + + // set input and output buf + uint8_t testData[] = "My test data"; + size_t testDataLen = 12; + uint8_t outBuf[28] = {0}; + + // define input and output data in blob form + struct HcfBlob inBlob= {.data = (uint8_t *)testData, .len = testDataLen}; + struct HcfBlob outBlob = {.data = (uint8_t *)outBuf, .len = 0}; + + // test api functions + ret = mdObj->update(mdObj, &inBlob); + EXPECT_EQ(ret, 0); + ret = mdObj->doFinal(mdObj, &outBlob); + EXPECT_EQ(ret, 0); + ret = mdObj->getMdLength(mdObj); + EXPECT_EQ(ret, 28); + + // destroy the API obj and blob data + HcfBlobDataClearAndFree(&outBlob); + OH_HCF_ObjDestroy(mdObj); +} + +HWTEST_F(CryptoFrameworkMdTest, CryptoFrameworkMdAlgoTest003, TestSize.Level0) +{ + int32_t ret = 0; + // create a API obj with SHA1 + HcfMd *mdObj = nullptr; + ret = (int)HcfMdCreate("SHA256", &mdObj); + EXPECT_EQ(ret, 0); + // set input and output buf + uint8_t testData[] = "My test data"; + size_t testDataLen = 12; + uint8_t outBuf[32] = {0}; + + // define input and output data in blob form + struct HcfBlob inBlob= {.data = (uint8_t *)testData, .len = testDataLen}; + struct HcfBlob outBlob = {.data = (uint8_t *)outBuf, .len = 0}; + + // test api functions + ret = mdObj->update(mdObj, &inBlob); + EXPECT_EQ(ret, 0); + ret = mdObj->doFinal(mdObj, &outBlob); + EXPECT_EQ(ret, 0); + ret = mdObj->getMdLength(mdObj); + EXPECT_EQ(ret, 32); + // destroy the API obj and blob data + HcfBlobDataClearAndFree(&outBlob); + OH_HCF_ObjDestroy(mdObj); +} + +HWTEST_F(CryptoFrameworkMdTest, CryptoFrameworkMdAlgoTest004, TestSize.Level0) +{ + int32_t ret = 0; + // create a API obj with SHA1 + HcfMd *mdObj = nullptr; + ret = (int)HcfMdCreate("SHA384", &mdObj); + EXPECT_EQ(ret, 0); + + // set input and output buf + uint8_t testData[] = "My test data"; + size_t testDataLen = 12; + uint8_t outBuf[48] = {0}; + + // define input and output data in blob form + struct HcfBlob inBlob= {.data = (uint8_t *)testData, .len = testDataLen}; + struct HcfBlob outBlob = {.data = (uint8_t *)outBuf, .len = 0}; + + // test api functions + ret = mdObj->update(mdObj, &inBlob); + EXPECT_EQ(ret, 0); + ret = mdObj->doFinal(mdObj, &outBlob); + EXPECT_EQ(ret, 0); + ret = mdObj->getMdLength(mdObj); + EXPECT_EQ(ret, 48); + + // destroy the API obj and blob data + HcfBlobDataClearAndFree(&outBlob); + OH_HCF_ObjDestroy(mdObj); +} + +HWTEST_F(CryptoFrameworkMdTest, CryptoFrameworkMdAlgoTest005, TestSize.Level0) +{ + int32_t ret = 0; + // create a API obj with SHA1 + HcfMd *mdObj = nullptr; + ret = (int)HcfMdCreate("SHA512", &mdObj); + EXPECT_EQ(ret, 0); + + // set input and output buf + uint8_t testData[] = "My test data"; + size_t testDataLen = 12; + uint8_t outBuf[64] = {0}; + + // define input and output data in blob form + struct HcfBlob inBlob= {.data = (uint8_t *)testData, .len = testDataLen}; + struct HcfBlob outBlob = {.data = (uint8_t *)outBuf, .len = 0}; + + // test api functions + ret = mdObj->update(mdObj, &inBlob); + EXPECT_EQ(ret, 0); + ret = mdObj->doFinal(mdObj, &outBlob); + EXPECT_EQ(ret, 0); + ret = mdObj->getMdLength(mdObj); + EXPECT_EQ(ret, 64); + + // destroy the API obj and blob data + HcfBlobDataClearAndFree(&outBlob); + OH_HCF_ObjDestroy(mdObj); +} + +HWTEST_F(CryptoFrameworkMdTest, CryptoFrameworkMdAlgoTest006, TestSize.Level0) +{ + int32_t ret = 0; + // create a API obj with SHA1 + HcfMd *mdObj = nullptr; + ret = (int)HcfMdCreate("MD5", &mdObj); + EXPECT_EQ(ret, 0); + + // set input and output buf + uint8_t testData[] = "My test data"; + size_t testDataLen = 12; + uint8_t outBuf[16] = {0}; + + // define input and output data in blob form + struct HcfBlob inBlob= {.data = (uint8_t *)testData, .len = testDataLen}; + struct HcfBlob outBlob = {.data = (uint8_t *)outBuf, .len = 0}; + + // test api functions + ret = mdObj->update(mdObj, &inBlob); + EXPECT_EQ(ret, 0); + ret = mdObj->doFinal(mdObj, &outBlob); + EXPECT_EQ(ret, 0); + ret = mdObj->getMdLength(mdObj); + EXPECT_EQ(ret, 16); + + // destroy the API obj and blob data + HcfBlobDataClearAndFree(&outBlob); + OH_HCF_ObjDestroy(mdObj); +} \ No newline at end of file diff --git a/test/unittest/src/crypto_rand_test.cpp b/test/unittest/src/crypto_rand_test.cpp new file mode 100644 index 0000000..53cc0d2 --- /dev/null +++ b/test/unittest/src/crypto_rand_test.cpp @@ -0,0 +1,171 @@ +/* + * Copyright (C) 2022 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 "rand.h" + +#include "log.h" +#include "memory.h" + +using namespace std; +using namespace testing::ext; + +class CryptoFrameworkRandTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void CryptoFrameworkRandTest::SetUpTestCase() {} +void CryptoFrameworkRandTest::TearDownTestCase() {} + +void CryptoFrameworkRandTest::SetUp() // add init here, this will be called before test. +{ +} + +void CryptoFrameworkRandTest::TearDown() // add destroy here, this will be called when test case done. +{ +} + +HWTEST_F(CryptoFrameworkRandTest, CryptoFrameworkRandCreateTest001, TestSize.Level0) +{ + int32_t ret = 0; + ret = (int)HcfRandCreate(nullptr); + EXPECT_NE(ret, 0); +} + +HWTEST_F(CryptoFrameworkRandTest, CryptoFrameworkRandGenerateTest001, TestSize.Level0) +{ + int32_t ret = 0; + // create a rand obj + HcfRand *randObj = nullptr; + ret = (int)HcfRandCreate(&randObj); + EXPECT_EQ(ret, 0); + // preset params + int32_t randomLen = 0; + uint8_t randomBuf[32] = {0}; + // define randomBlob and seedBlob + struct HcfBlob randomBlob = {.data = (uint8_t *)randomBuf, .len = 0}; + // test generate random with length 0 + ret = randObj->generateRandom(randObj, randomLen, &randomBlob); + EXPECT_NE(ret, 0); + OH_HCF_ObjDestroy(randObj); +} + +HWTEST_F(CryptoFrameworkRandTest, CryptoFrameworkRandGenerateTest002, TestSize.Level0) +{ + int32_t ret = 0; + // create a rand obj + HcfRand *randObj = nullptr; + ret = (int)HcfRandCreate(&randObj); + EXPECT_EQ(ret, 0); + // preset params + int32_t randomLen = 32; + uint8_t randomBuf[32] = {0}; + // define randomBlob and seedBlob + struct HcfBlob randomBlob = {.data = (uint8_t *)randomBuf, .len = 0}; + // test generate random + ret = randObj->generateRandom(randObj, randomLen, &randomBlob); + EXPECT_EQ(ret, 0); + // destroy the API obj and blob data + HcfBlobDataClearAndFree(&randomBlob); + OH_HCF_ObjDestroy(randObj); +} + +HWTEST_F(CryptoFrameworkRandTest, CryptoFrameworkRandGenerateTest003, TestSize.Level0) +{ + int32_t ret = 0; + // create a rand obj + HcfRand *randObj = nullptr; + ret = (int)HcfRandCreate(&randObj); + EXPECT_EQ(ret, 0); + // preset params + int32_t randomLen = 1000; + uint8_t randomBuf[1000] = {0}; + // define randomBlob and seedBlob + struct HcfBlob randomBlob = {.data = (uint8_t *)randomBuf, .len = 0}; + // test generate random + ret = randObj->generateRandom(randObj, randomLen, &randomBlob); + EXPECT_EQ(ret, 0); + // destroy the API obj and blob data + HcfBlobDataClearAndFree(&randomBlob); + OH_HCF_ObjDestroy(randObj); +} + +HWTEST_F(CryptoFrameworkRandTest, CryptoFrameworkSetSeedTest001, TestSize.Level0) +{ + int32_t ret = 0; + // create a rand obj + HcfRand *randObj = nullptr; + ret = (int)HcfRandCreate(&randObj); + EXPECT_EQ(ret, 0); + // define randomBlob and seedBlob + struct HcfBlob *seedBlob = nullptr; + // test set seed + ret = randObj->setSeed(randObj, seedBlob); + EXPECT_NE(ret, 0); + // destroy the API obj and blob data + OH_HCF_ObjDestroy(randObj); +} + +HWTEST_F(CryptoFrameworkRandTest, CryptoFrameworkSetSeedTest002, TestSize.Level0) +{ + int32_t ret = 0; + // create a rand obj + HcfRand *randObj = nullptr; + ret = (int)HcfRandCreate(&randObj); + EXPECT_EQ(ret, 0); + // preset params + int32_t seedLen = 32; + uint8_t seedBuf[32] = {0}; + // define randomBlob and seedBlob + struct HcfBlob seedBlob = {.data = (uint8_t *)seedBuf, .len = 0}; + // test generate seed + ret = randObj->generateRandom(randObj, seedLen, &seedBlob); + EXPECT_EQ(ret, 0); + // test set seed + ret = randObj->setSeed(randObj, &seedBlob); + EXPECT_EQ(ret, 0); + // destroy the API obj and blob data + HcfBlobDataClearAndFree(&seedBlob); + OH_HCF_ObjDestroy(randObj); +} + +HWTEST_F(CryptoFrameworkRandTest, CryptoFrameworkSetSeedTest003, TestSize.Level0) +{ + int32_t ret = 0; + // create a rand obj + HcfRand *randObj = nullptr; + ret = (int)HcfRandCreate(&randObj); + EXPECT_EQ(ret, 0); + // preset params + int32_t seedLen = 1000; + uint8_t seedBuf[1000] = {0}; + // define randomBlob and seedBlob + struct HcfBlob seedBlob = {.data = (uint8_t *)seedBuf, .len = 0}; + // test generate seed + ret = randObj->generateRandom(randObj, seedLen, &seedBlob); + EXPECT_EQ(ret, 0); + // test set seed + ret = randObj->setSeed(randObj, &seedBlob); + EXPECT_EQ(ret, 0); + // destroy the API obj and blob data + HcfBlobDataClearAndFree(&seedBlob); + OH_HCF_ObjDestroy(randObj); +} \ No newline at end of file diff --git a/test/unittest/src/crypto_rsa_asy_key_generator_test.cpp b/test/unittest/src/crypto_rsa_asy_key_generator_test.cpp new file mode 100644 index 0000000..f0c9eea --- /dev/null +++ b/test/unittest/src/crypto_rsa_asy_key_generator_test.cpp @@ -0,0 +1,847 @@ +/* + * Copyright (C) 2022 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 "blob.h" +#include "memory.h" + +using namespace std; +using namespace testing::ext; + +class RsaAsyKeyGeneratorTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void RsaAsyKeyGeneratorTest::SetUpTestCase() {} +void RsaAsyKeyGeneratorTest::TearDownTestCase() {} +void RsaAsyKeyGeneratorTest::SetUp() {} +void RsaAsyKeyGeneratorTest::TearDown() {} + +// HcfAsyKeyGeneratorCreate correct case: no primes +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest100, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA512", &generator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(generator, nullptr); + EXPECT_NE(generator->base.getClass(), nullptr); + EXPECT_NE(generator->base.destroy, nullptr); + EXPECT_NE(generator->generateKeyPair, nullptr); + EXPECT_NE(generator->getAlgoName, nullptr); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest110, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA768", &generator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(generator, nullptr); + EXPECT_NE(generator->base.getClass(), nullptr); + EXPECT_NE(generator->base.destroy, nullptr); + EXPECT_NE(generator->generateKeyPair, nullptr); + EXPECT_NE(generator->getAlgoName, nullptr); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest120, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA1024", &generator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(generator, nullptr); + EXPECT_NE(generator->base.getClass(), nullptr); + EXPECT_NE(generator->base.destroy, nullptr); + EXPECT_NE(generator->generateKeyPair, nullptr); + EXPECT_NE(generator->getAlgoName, nullptr); + OH_HCF_ObjDestroy(generator); +} + + +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest130, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA2048", &generator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(generator, nullptr); + EXPECT_NE(generator->base.getClass(), nullptr); + EXPECT_NE(generator->base.destroy, nullptr); + EXPECT_NE(generator->generateKeyPair, nullptr); + EXPECT_NE(generator->getAlgoName, nullptr); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest140, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA3072", &generator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(generator, nullptr); + EXPECT_NE(generator->base.getClass(), nullptr); + EXPECT_NE(generator->base.destroy, nullptr); + EXPECT_NE(generator->generateKeyPair, nullptr); + EXPECT_NE(generator->getAlgoName, nullptr); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest150, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA4096", &generator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(generator, nullptr); + EXPECT_NE(generator->base.getClass(), nullptr); + EXPECT_NE(generator->base.destroy, nullptr); + EXPECT_NE(generator->generateKeyPair, nullptr); + EXPECT_NE(generator->getAlgoName, nullptr); + OH_HCF_ObjDestroy(generator); +} + +// HcfAsyKeyGeneratorCreate correct case: with primes +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest200, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA512|PRIMES_2", &generator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(generator, nullptr); + EXPECT_NE(generator->base.getClass(), nullptr); + EXPECT_NE(generator->base.destroy, nullptr); + EXPECT_NE(generator->generateKeyPair, nullptr); + EXPECT_NE(generator->getAlgoName, nullptr); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest210, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA768|PRIMES_2", &generator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(generator, nullptr); + EXPECT_NE(generator->base.getClass(), nullptr); + EXPECT_NE(generator->base.destroy, nullptr); + EXPECT_NE(generator->generateKeyPair, nullptr); + EXPECT_NE(generator->getAlgoName, nullptr); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest220, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA1024|PRIMES_2", &generator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(generator, nullptr); + EXPECT_NE(generator->base.getClass(), nullptr); + EXPECT_NE(generator->base.destroy, nullptr); + EXPECT_NE(generator->generateKeyPair, nullptr); + EXPECT_NE(generator->getAlgoName, nullptr); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest230, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA1024|PRIMES_3", &generator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(generator, nullptr); + EXPECT_NE(generator->base.getClass(), nullptr); + EXPECT_NE(generator->base.destroy, nullptr); + EXPECT_NE(generator->generateKeyPair, nullptr); + EXPECT_NE(generator->getAlgoName, nullptr); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest240, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA2048|PRIMES_2", &generator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(generator, nullptr); + EXPECT_NE(generator->base.getClass(), nullptr); + EXPECT_NE(generator->base.destroy, nullptr); + EXPECT_NE(generator->generateKeyPair, nullptr); + EXPECT_NE(generator->getAlgoName, nullptr); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest250, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA2048|PRIMES_3", &generator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(generator, nullptr); + EXPECT_NE(generator->base.getClass(), nullptr); + EXPECT_NE(generator->base.destroy, nullptr); + EXPECT_NE(generator->generateKeyPair, nullptr); + EXPECT_NE(generator->getAlgoName, nullptr); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest260, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA3072|PRIMES_3", &generator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(generator, nullptr); + EXPECT_NE(generator->base.getClass(), nullptr); + EXPECT_NE(generator->base.destroy, nullptr); + EXPECT_NE(generator->generateKeyPair, nullptr); + EXPECT_NE(generator->getAlgoName, nullptr); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest270, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA4096|PRIMES_4", &generator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(generator, nullptr); + EXPECT_NE(generator->base.getClass(), nullptr); + EXPECT_NE(generator->base.destroy, nullptr); + EXPECT_NE(generator->generateKeyPair, nullptr); + EXPECT_NE(generator->getAlgoName, nullptr); + OH_HCF_ObjDestroy(generator); +} + +// HcfAsyKeyGeneratorCreate Incorrect case : algname is null +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest300, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate(NULL, &generator); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(generator, nullptr); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest310, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("111111111111111111111111111111111111111111111111111111111111111111111111" + "111111111111111111111111111111111111111111111111111111111111111111111", &generator); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(generator, nullptr); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest320, TestSize.Level0) +{ + HcfResult res = HcfAsyKeyGeneratorCreate("RSA1024", NULL); + EXPECT_NE(res, HCF_SUCCESS); +} + +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest330, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA12315", &generator); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(generator, nullptr); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest340, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA512|PRIMES_777", &generator); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(generator, nullptr); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest350, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA512|PRIMES_3", &generator); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(generator, nullptr); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest360, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA768|PRIMES_3", &generator); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(generator, nullptr); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest370, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA1024|PRIMES_4", &generator); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(generator, nullptr); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest380, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA3072|PRIMES_4", &generator); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(generator, nullptr); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest390, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA4096|PRIMES_5", &generator); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(generator, nullptr); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest400, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA1024", &generator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(generator, nullptr); + OH_HCF_ObjDestroy(generator); + generator = NULL; + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest410, TestSize.Level0) +{ + OH_HCF_ObjDestroy(NULL); +} + +// generateKeyPair correct case +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest500, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA1024|PRIMES_2", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(keyPair, nullptr); + EXPECT_NE(keyPair->priKey, nullptr); + EXPECT_NE(keyPair->pubKey, nullptr); + EXPECT_NE(keyPair->base.getClass(), nullptr); + EXPECT_NE(keyPair->base.destroy, nullptr); + + HcfPubKey *pubkey = keyPair->pubKey; + EXPECT_NE(pubkey->base.getAlgorithm((HcfKey *)pubkey), nullptr); + EXPECT_NE(pubkey->base.getFormat((HcfKey *)pubkey), nullptr); + EXPECT_NE(pubkey->base.base.getClass(), nullptr); + EXPECT_NE(pubkey->base.base.destroy, nullptr); + + HcfPriKey *prikey = keyPair->priKey; + EXPECT_NE(prikey->base.getAlgorithm((HcfKey *)prikey), nullptr); + EXPECT_NE(prikey->base.getFormat((HcfKey *)prikey), nullptr); + EXPECT_NE(prikey->base.base.getClass(), nullptr); + EXPECT_NE(prikey->base.base.destroy, nullptr); + EXPECT_NE(prikey->clearMem, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest510, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA2048|PRIMES_2", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(keyPair, nullptr); + EXPECT_NE(keyPair->priKey, nullptr); + EXPECT_NE(keyPair->pubKey, nullptr); + EXPECT_NE(keyPair->base.getClass(), nullptr); + EXPECT_NE(keyPair->base.destroy, nullptr); + + HcfPubKey *pubkey = keyPair->pubKey; + EXPECT_NE(pubkey->base.getAlgorithm((HcfKey *)pubkey), nullptr); + EXPECT_NE(pubkey->base.getFormat((HcfKey *)pubkey), nullptr); + EXPECT_NE(pubkey->base.base.getClass(), nullptr); + EXPECT_NE(pubkey->base.base.destroy, nullptr); + + HcfPriKey *prikey = keyPair->priKey; + EXPECT_NE(prikey->base.getAlgorithm((HcfKey *)prikey), nullptr); + EXPECT_NE(prikey->base.getFormat((HcfKey *)prikey), nullptr); + EXPECT_NE(prikey->base.base.getClass(), nullptr); + EXPECT_NE(prikey->base.base.destroy, nullptr); + EXPECT_NE(prikey->clearMem, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +// generateKeyPair conrrect case: use getEncode encode pubkey and prikey +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest520, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA1024", &generator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(generator, nullptr); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + HcfBlob pubKeyBlob = {.data = NULL, .len = 0}; + HcfBlob priKeyBlob = {.data = NULL, .len = 0}; + res = keyPair->pubKey->base.getEncoded((HcfKey *)keyPair->pubKey, &pubKeyBlob); + EXPECT_EQ(res, HCF_SUCCESS); + res = keyPair->priKey->base.getEncoded((HcfKey *)keyPair->priKey, &priKeyBlob); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfKeyPair *dupKeyPair = NULL; + res = generator->convertKey(generator, NULL, &pubKeyBlob, &priKeyBlob, &dupKeyPair); + EXPECT_EQ(res, HCF_SUCCESS); + HcfPubKey *pubkey = dupKeyPair->pubKey; + EXPECT_NE(pubkey->base.getAlgorithm((HcfKey *)pubkey), nullptr); + EXPECT_NE(pubkey->base.getFormat((HcfKey *)pubkey), nullptr); + EXPECT_NE(pubkey->base.base.getClass(), nullptr); + EXPECT_NE(pubkey->base.base.destroy, nullptr); + + HcfPriKey *prikey = dupKeyPair->priKey; + EXPECT_NE(prikey->base.getAlgorithm((HcfKey *)prikey), nullptr); + EXPECT_NE(prikey->base.getFormat((HcfKey *)prikey), nullptr); + EXPECT_NE(prikey->base.base.getClass(), nullptr); + EXPECT_NE(prikey->base.base.destroy, nullptr); + EXPECT_NE(prikey->clearMem, nullptr); + + HcfFree(pubKeyBlob.data); + HcfFree(priKeyBlob.data); + OH_HCF_ObjDestroy(generator); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(dupKeyPair); +} + +// generateKeyPair correct case: getEncode encode pubkey +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest530, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA1024", &generator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(generator, nullptr); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + HcfBlob pubKeyBlob = {.data = NULL, .len = 0}; + res = keyPair->pubKey->base.getEncoded((HcfKey *)keyPair->pubKey, &pubKeyBlob); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfKeyPair *dupKeyPair = NULL; + res = generator->convertKey(generator, NULL, &pubKeyBlob, NULL, &dupKeyPair); + EXPECT_EQ(res, HCF_SUCCESS); + HcfPubKey *pubkey = dupKeyPair->pubKey; + EXPECT_NE(pubkey->base.getAlgorithm((HcfKey *)pubkey), nullptr); + EXPECT_NE(pubkey->base.getFormat((HcfKey *)pubkey), nullptr); + EXPECT_NE(pubkey->base.base.getClass(), nullptr); + EXPECT_NE(pubkey->base.base.destroy, nullptr); + + HcfFree(pubKeyBlob.data); + OH_HCF_ObjDestroy(generator); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(dupKeyPair); +} + +// generateKeyPair correct case: getEncode encode prikey +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest540, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA1024", &generator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(generator, nullptr); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + HcfBlob priKeyBlob = {.data = NULL, .len = 0}; + res = keyPair->priKey->base.getEncoded((HcfKey *)keyPair->priKey, &priKeyBlob); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfKeyPair *dupKeyPair = NULL; + res = generator->convertKey(generator, NULL, NULL, &priKeyBlob, &dupKeyPair); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfPriKey *prikey = dupKeyPair->priKey; + EXPECT_NE(prikey->base.getAlgorithm((HcfKey *)prikey), nullptr); + EXPECT_NE(prikey->base.getFormat((HcfKey *)prikey), nullptr); + EXPECT_NE(prikey->base.base.getClass(), nullptr); + EXPECT_NE(prikey->base.base.destroy, nullptr); + EXPECT_NE(prikey->clearMem, nullptr); + + HcfFree(priKeyBlob.data); + OH_HCF_ObjDestroy(generator); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(dupKeyPair); +} + +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest550, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA3072", &generator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(generator, nullptr); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + HcfBlob pubKeyBlob = {.data = NULL, .len = 0}; + HcfBlob priKeyBlob = {.data = NULL, .len = 0}; + res = keyPair->pubKey->base.getEncoded((HcfKey *)keyPair->pubKey, &pubKeyBlob); + EXPECT_EQ(res, HCF_SUCCESS); + res = keyPair->priKey->base.getEncoded((HcfKey *)keyPair->priKey, &priKeyBlob); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfKeyPair *dupKeyPair = NULL; + res = generator->convertKey(generator, NULL, &pubKeyBlob, &priKeyBlob, &dupKeyPair); + EXPECT_EQ(res, HCF_SUCCESS); + HcfPubKey *pubkey = dupKeyPair->pubKey; + EXPECT_NE(pubkey->base.getAlgorithm((HcfKey *)pubkey), nullptr); + EXPECT_NE(pubkey->base.getFormat((HcfKey *)pubkey), nullptr); + EXPECT_NE(pubkey->base.base.getClass(), nullptr); + EXPECT_NE(pubkey->base.base.destroy, nullptr); + + HcfPriKey *prikey = dupKeyPair->priKey; + EXPECT_NE(prikey->base.getAlgorithm((HcfKey *)prikey), nullptr); + EXPECT_NE(prikey->base.getFormat((HcfKey *)prikey), nullptr); + EXPECT_NE(prikey->base.base.getClass(), nullptr); + EXPECT_NE(prikey->base.base.destroy, nullptr); + EXPECT_NE(prikey->clearMem, nullptr); + + HcfFree(pubKeyBlob.data); + HcfFree(priKeyBlob.data); + OH_HCF_ObjDestroy(generator); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(dupKeyPair); +} + +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest560, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA4096", &generator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(generator, nullptr); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + HcfBlob pubKeyBlob = {.data = NULL, .len = 0}; + HcfBlob priKeyBlob = {.data = NULL, .len = 0}; + res = keyPair->pubKey->base.getEncoded((HcfKey *)keyPair->pubKey, &pubKeyBlob); + EXPECT_EQ(res, HCF_SUCCESS); + res = keyPair->priKey->base.getEncoded((HcfKey *)keyPair->priKey, &priKeyBlob); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfKeyPair *dupKeyPair = NULL; + res = generator->convertKey(generator, NULL, &pubKeyBlob, &priKeyBlob, &dupKeyPair); + EXPECT_EQ(res, HCF_SUCCESS); + HcfPubKey *pubkey = dupKeyPair->pubKey; + EXPECT_NE(pubkey->base.getAlgorithm((HcfKey *)pubkey), nullptr); + EXPECT_NE(pubkey->base.getFormat((HcfKey *)pubkey), nullptr); + EXPECT_NE(pubkey->base.base.getClass(), nullptr); + EXPECT_NE(pubkey->base.base.destroy, nullptr); + + HcfPriKey *prikey = dupKeyPair->priKey; + EXPECT_NE(prikey->base.getAlgorithm((HcfKey *)prikey), nullptr); + EXPECT_NE(prikey->base.getFormat((HcfKey *)prikey), nullptr); + EXPECT_NE(prikey->base.base.getClass(), nullptr); + EXPECT_NE(prikey->base.base.destroy, nullptr); + EXPECT_NE(prikey->clearMem, nullptr); + + HcfFree(pubKeyBlob.data); + HcfFree(priKeyBlob.data); + OH_HCF_ObjDestroy(generator); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(dupKeyPair); +} + +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest570, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA512", &generator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(generator, nullptr); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + HcfBlob pubKeyBlob = {.data = NULL, .len = 0}; + HcfBlob priKeyBlob = {.data = NULL, .len = 0}; + res = keyPair->pubKey->base.getEncoded((HcfKey *)keyPair->pubKey, &pubKeyBlob); + EXPECT_EQ(res, HCF_SUCCESS); + res = keyPair->priKey->base.getEncoded((HcfKey *)keyPair->priKey, &priKeyBlob); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfKeyPair *dupKeyPair = NULL; + res = generator->convertKey(generator, NULL, &pubKeyBlob, &priKeyBlob, &dupKeyPair); + EXPECT_EQ(res, HCF_SUCCESS); + HcfPubKey *pubkey = dupKeyPair->pubKey; + EXPECT_NE(pubkey->base.getAlgorithm((HcfKey *)pubkey), nullptr); + EXPECT_NE(pubkey->base.getFormat((HcfKey *)pubkey), nullptr); + EXPECT_NE(pubkey->base.base.getClass(), nullptr); + EXPECT_NE(pubkey->base.base.destroy, nullptr); + + HcfPriKey *prikey = dupKeyPair->priKey; + EXPECT_NE(prikey->base.getAlgorithm((HcfKey *)prikey), nullptr); + EXPECT_NE(prikey->base.getFormat((HcfKey *)prikey), nullptr); + EXPECT_NE(prikey->base.base.getClass(), nullptr); + EXPECT_NE(prikey->base.base.destroy, nullptr); + EXPECT_NE(prikey->clearMem, nullptr); + + HcfFree(pubKeyBlob.data); + HcfFree(priKeyBlob.data); + OH_HCF_ObjDestroy(generator); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(dupKeyPair); +} + +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest580, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA768", &generator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(generator, nullptr); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + HcfBlob pubKeyBlob = {.data = NULL, .len = 0}; + HcfBlob priKeyBlob = {.data = NULL, .len = 0}; + res = keyPair->pubKey->base.getEncoded((HcfKey *)keyPair->pubKey, &pubKeyBlob); + EXPECT_EQ(res, HCF_SUCCESS); + res = keyPair->priKey->base.getEncoded((HcfKey *)keyPair->priKey, &priKeyBlob); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfKeyPair *dupKeyPair = NULL; + res = generator->convertKey(generator, NULL, &pubKeyBlob, &priKeyBlob, &dupKeyPair); + EXPECT_EQ(res, HCF_SUCCESS); + HcfPubKey *pubkey = dupKeyPair->pubKey; + EXPECT_NE(pubkey->base.getAlgorithm((HcfKey *)pubkey), nullptr); + EXPECT_NE(pubkey->base.getFormat((HcfKey *)pubkey), nullptr); + EXPECT_NE(pubkey->base.base.getClass(), nullptr); + EXPECT_NE(pubkey->base.base.destroy, nullptr); + + HcfPriKey *prikey = dupKeyPair->priKey; + EXPECT_NE(prikey->base.getAlgorithm((HcfKey *)prikey), nullptr); + EXPECT_NE(prikey->base.getFormat((HcfKey *)prikey), nullptr); + EXPECT_NE(prikey->base.base.getClass(), nullptr); + EXPECT_NE(prikey->base.base.destroy, nullptr); + EXPECT_NE(prikey->clearMem, nullptr); + + HcfFree(pubKeyBlob.data); + HcfFree(priKeyBlob.data); + OH_HCF_ObjDestroy(generator); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(dupKeyPair); +} + +// generateKeyPair incorrect case: user wrong ECC class, ignore in this version +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest600, TestSize.Level0) +{ + HcfAsyKeyGenerator *eccGenerator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("ECC224", &eccGenerator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(eccGenerator, nullptr); + + HcfAsyKeyGenerator *rsaGenerator = NULL; + res = HcfAsyKeyGeneratorCreate("RSA1024", &rsaGenerator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(rsaGenerator, nullptr); + + HcfKeyPair *keyPair = NULL; + res = rsaGenerator->generateKeyPair(eccGenerator, NULL, &keyPair); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(eccGenerator); + OH_HCF_ObjDestroy(rsaGenerator); +} + +// generateKeyPair incorrect case: generator class is null +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest610, TestSize.Level0) +{ + HcfAsyKeyGenerator *rsaGenerator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA1024", &rsaGenerator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(rsaGenerator, nullptr); + + HcfKeyPair *keyPair = NULL; + res = rsaGenerator->generateKeyPair(NULL, NULL, &keyPair); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(keyPair, nullptr); + + OH_HCF_ObjDestroy(rsaGenerator); +} + +// generateKeyPair incorrect case: keypair is null +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest620, TestSize.Level0) +{ + HcfAsyKeyGenerator *rsaGenerator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA1024", &rsaGenerator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(rsaGenerator, nullptr); + + res = rsaGenerator->generateKeyPair(rsaGenerator, NULL, NULL); + EXPECT_NE(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(rsaGenerator); +} + +// convertKey correct case +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest700, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA2048", &generator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(generator, nullptr); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + HcfBlob pubKeyBlob = {.data = NULL, .len = 0}; + HcfBlob priKeyBlob = {.data = NULL, .len = 0}; + res = keyPair->pubKey->base.getEncoded((HcfKey *)keyPair->pubKey, &pubKeyBlob); + EXPECT_EQ(res, HCF_SUCCESS); + res = keyPair->priKey->base.getEncoded((HcfKey *)keyPair->priKey, &priKeyBlob); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfKeyPair *dupKeyPair = NULL; + res = generator->convertKey(generator, NULL, &pubKeyBlob, &priKeyBlob, &dupKeyPair); + EXPECT_EQ(res, HCF_SUCCESS); + HcfPubKey *pubkey = dupKeyPair->pubKey; + EXPECT_NE(pubkey->base.getAlgorithm((HcfKey *)pubkey), nullptr); + EXPECT_NE(pubkey->base.getFormat((HcfKey *)pubkey), nullptr); + EXPECT_NE(pubkey->base.base.getClass(), nullptr); + EXPECT_NE(pubkey->base.base.destroy, nullptr); + + HcfPriKey *prikey = dupKeyPair->priKey; + EXPECT_NE(prikey->base.getAlgorithm((HcfKey *)prikey), nullptr); + EXPECT_NE(prikey->base.getFormat((HcfKey *)prikey), nullptr); + EXPECT_NE(prikey->base.base.getClass(), nullptr); + EXPECT_NE(prikey->base.base.destroy, nullptr); + EXPECT_NE(prikey->clearMem, nullptr); + + HcfFree(pubKeyBlob.data); + HcfFree(priKeyBlob.data); + OH_HCF_ObjDestroy(generator); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(dupKeyPair); +} + +// convertKey incorrect case: input ECC class +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest710, TestSize.Level0) +{ + HcfAsyKeyGenerator *eccGenerator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("ECC224", &eccGenerator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(eccGenerator, nullptr); + + HcfAsyKeyGenerator *rsaGenerator = NULL; + res = HcfAsyKeyGeneratorCreate("RSA1024", &rsaGenerator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(rsaGenerator, nullptr); + + HcfKeyPair *dupKeyPair = NULL; + res = rsaGenerator->convertKey(eccGenerator, NULL, NULL, NULL, &dupKeyPair); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(dupKeyPair, nullptr); + + OH_HCF_ObjDestroy(eccGenerator); + OH_HCF_ObjDestroy(rsaGenerator); +} + + +// convertKey incorrect case: input null generator +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest720, TestSize.Level0) +{ + HcfAsyKeyGenerator *rsaGenerator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA1024", &rsaGenerator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(rsaGenerator, nullptr); + + HcfKeyPair *keyPair = NULL; + res = rsaGenerator->generateKeyPair(rsaGenerator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + HcfBlob pubKeyBlob = {.data = NULL, .len = 0}; + HcfBlob priKeyBlob = {.data = NULL, .len = 0}; + res = keyPair->pubKey->base.getEncoded((HcfKey *)keyPair->pubKey, &pubKeyBlob); + EXPECT_EQ(res, HCF_SUCCESS); + res = keyPair->priKey->base.getEncoded((HcfKey *)keyPair->priKey, &priKeyBlob); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfKeyPair *dupKeyPair = NULL; + res = rsaGenerator->convertKey(NULL, NULL, &pubKeyBlob, &priKeyBlob, &dupKeyPair); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(dupKeyPair, nullptr); + + HcfFree(pubKeyBlob.data); + HcfFree(priKeyBlob.data); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(rsaGenerator); +} + +// convertKey incorrect case: input null dupkeypair +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest730, TestSize.Level0) +{ + HcfAsyKeyGenerator *rsaGenerator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA1024", &rsaGenerator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(rsaGenerator, nullptr); + + HcfKeyPair *keyPair = NULL; + res = rsaGenerator->generateKeyPair(rsaGenerator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + HcfBlob pubKeyBlob = {.data = NULL, .len = 0}; + HcfBlob priKeyBlob = {.data = NULL, .len = 0}; + res = keyPair->pubKey->base.getEncoded((HcfKey *)keyPair->pubKey, &pubKeyBlob); + EXPECT_EQ(res, HCF_SUCCESS); + res = keyPair->priKey->base.getEncoded((HcfKey *)keyPair->priKey, &priKeyBlob); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfKeyPair *dupKeyPair = NULL; + res = rsaGenerator->convertKey(rsaGenerator, NULL, &pubKeyBlob, &priKeyBlob, NULL); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(dupKeyPair, nullptr); + + HcfFree(pubKeyBlob.data); + HcfFree(priKeyBlob.data); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(rsaGenerator); +} + +// Incorrect case: use wrong bits or primes +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest800, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA1111", &generator); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(generator, nullptr); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaAsyKeyGeneratorTest, RsaAsyKeyGeneratorTest810, TestSize.Level0) +{ + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA1024|Primessf", &generator); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(generator, nullptr); + OH_HCF_ObjDestroy(generator); +} diff --git a/test/unittest/src/crypto_rsa_cipher_test.cpp b/test/unittest/src/crypto_rsa_cipher_test.cpp new file mode 100644 index 0000000..32d8243 --- /dev/null +++ b/test/unittest/src/crypto_rsa_cipher_test.cpp @@ -0,0 +1,984 @@ +/* + * Copyright (C) 2022 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 "cipher.h" +#include "key_pair.h" +#include "memory.h" +#include "cstring" + +using namespace std; +using namespace testing::ext; + +class RsaCipherTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void RsaCipherTest::SetUpTestCase() {} +void RsaCipherTest::TearDownTestCase() {} +void RsaCipherTest::SetUp() {} +void RsaCipherTest::TearDown() {} + +// HcfCipherCreate correct case: RSAXXX + padding +HWTEST_F(RsaCipherTest, RsaCipherTest100, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA1024|NoPadding", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(cipher, nullptr); + EXPECT_NE(cipher->base.getClass(), nullptr); + EXPECT_NE(cipher->base.destroy, nullptr); + EXPECT_NE(cipher->init, nullptr); + EXPECT_NE(cipher->update, nullptr); + EXPECT_NE(cipher->doFinal, nullptr); + OH_HCF_ObjDestroy(cipher); +} + +HWTEST_F(RsaCipherTest, RsaCipherTest110, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA1024|NoPadding", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(cipher, nullptr); + EXPECT_NE(cipher->base.getClass(), nullptr); + EXPECT_NE(cipher->base.destroy, nullptr); + EXPECT_NE(cipher->init, nullptr); + EXPECT_NE(cipher->update, nullptr); + EXPECT_NE(cipher->doFinal, nullptr); + OH_HCF_ObjDestroy(cipher); +} + +HWTEST_F(RsaCipherTest, RsaCipherTest120, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA1024|PKCS1", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(cipher, nullptr); + EXPECT_NE(cipher->base.getClass(), nullptr); + EXPECT_NE(cipher->base.destroy, nullptr); + EXPECT_NE(cipher->init, nullptr); + EXPECT_NE(cipher->update, nullptr); + EXPECT_NE(cipher->doFinal, nullptr); + OH_HCF_ObjDestroy(cipher); +} + +HWTEST_F(RsaCipherTest, RsaCipherTest130, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA1024|PKCS1_OAEP|SHA1|MGF1_SHA1", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(cipher, nullptr); + EXPECT_NE(cipher->base.getClass(), nullptr); + EXPECT_NE(cipher->base.destroy, nullptr); + EXPECT_NE(cipher->init, nullptr); + EXPECT_NE(cipher->update, nullptr); + EXPECT_NE(cipher->doFinal, nullptr); + OH_HCF_ObjDestroy(cipher); +} + +HWTEST_F(RsaCipherTest, RsaCipherTest140, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA1024|PKCS1_OAEP|SHA256|MGF1_SHA256", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(cipher, nullptr); + EXPECT_NE(cipher->base.getClass(), nullptr); + EXPECT_NE(cipher->base.destroy, nullptr); + EXPECT_NE(cipher->init, nullptr); + EXPECT_NE(cipher->update, nullptr); + EXPECT_NE(cipher->doFinal, nullptr); + OH_HCF_ObjDestroy(cipher); +} + +HWTEST_F(RsaCipherTest, RsaCipherTest150, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA1024|PKCS1_OAEP|SHA512|MGF1_SHA256", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(cipher, nullptr); + EXPECT_NE(cipher->base.getClass(), nullptr); + EXPECT_NE(cipher->base.destroy, nullptr); + EXPECT_NE(cipher->init, nullptr); + EXPECT_NE(cipher->update, nullptr); + EXPECT_NE(cipher->doFinal, nullptr); + OH_HCF_ObjDestroy(cipher); +} + +HWTEST_F(RsaCipherTest, RsaCipherTest160, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA1024|PKCS1_OAEP|SHA1|MGF1_SHA256", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(cipher, nullptr); + EXPECT_NE(cipher->base.getClass(), nullptr); + EXPECT_NE(cipher->base.destroy, nullptr); + EXPECT_NE(cipher->init, nullptr); + EXPECT_NE(cipher->update, nullptr); + EXPECT_NE(cipher->doFinal, nullptr); + OH_HCF_ObjDestroy(cipher); +} + +HWTEST_F(RsaCipherTest, RsaCipherTest170, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA1024|PKCS1_OAEP|SHA1|MGF1_SHA1", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(cipher, nullptr); + EXPECT_NE(cipher->base.getClass(), nullptr); + EXPECT_NE(cipher->base.destroy, nullptr); + EXPECT_NE(cipher->init, nullptr); + EXPECT_NE(cipher->update, nullptr); + EXPECT_NE(cipher->doFinal, nullptr); + OH_HCF_ObjDestroy(cipher); +} + +HWTEST_F(RsaCipherTest, RsaCipherTest180, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA1024|PKCS1_OAEP|SHA1|MGF1_MD5", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(cipher, nullptr); + EXPECT_NE(cipher->base.getClass(), nullptr); + EXPECT_NE(cipher->base.destroy, nullptr); + EXPECT_NE(cipher->init, nullptr); + EXPECT_NE(cipher->update, nullptr); + EXPECT_NE(cipher->doFinal, nullptr); + OH_HCF_ObjDestroy(cipher); +} + +HWTEST_F(RsaCipherTest, RsaCipherTest190, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA1024|PKCS1_OAEP|SHA1|MGF1_SHA512", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(cipher, nullptr); + EXPECT_NE(cipher->base.getClass(), nullptr); + EXPECT_NE(cipher->base.destroy, nullptr); + EXPECT_NE(cipher->init, nullptr); + EXPECT_NE(cipher->update, nullptr); + EXPECT_NE(cipher->doFinal, nullptr); + OH_HCF_ObjDestroy(cipher); +} + +HWTEST_F(RsaCipherTest, RsaCipherTest200, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA512|NoPadding", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(cipher, nullptr); + EXPECT_NE(cipher->base.getClass(), nullptr); + EXPECT_NE(cipher->base.destroy, nullptr); + EXPECT_NE(cipher->init, nullptr); + EXPECT_NE(cipher->update, nullptr); + EXPECT_NE(cipher->doFinal, nullptr); + OH_HCF_ObjDestroy(cipher); +} + +HWTEST_F(RsaCipherTest, RsaCipherTest210, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA768|NoPadding", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(cipher, nullptr); + EXPECT_NE(cipher->base.getClass(), nullptr); + EXPECT_NE(cipher->base.destroy, nullptr); + EXPECT_NE(cipher->init, nullptr); + EXPECT_NE(cipher->update, nullptr); + EXPECT_NE(cipher->doFinal, nullptr); + OH_HCF_ObjDestroy(cipher); +} + +HWTEST_F(RsaCipherTest, RsaCipherTest220, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA2048|NoPadding", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(cipher, nullptr); + EXPECT_NE(cipher->base.getClass(), nullptr); + EXPECT_NE(cipher->base.destroy, nullptr); + EXPECT_NE(cipher->init, nullptr); + EXPECT_NE(cipher->update, nullptr); + EXPECT_NE(cipher->doFinal, nullptr); + OH_HCF_ObjDestroy(cipher); +} + +HWTEST_F(RsaCipherTest, RsaCipherTest230, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA512|PKCS1", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(cipher, nullptr); + EXPECT_NE(cipher->base.getClass(), nullptr); + EXPECT_NE(cipher->base.destroy, nullptr); + EXPECT_NE(cipher->init, nullptr); + EXPECT_NE(cipher->update, nullptr); + EXPECT_NE(cipher->doFinal, nullptr); + OH_HCF_ObjDestroy(cipher); +} + +HWTEST_F(RsaCipherTest, RsaCipherTest240, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA768|PKCS1", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(cipher, nullptr); + EXPECT_NE(cipher->base.getClass(), nullptr); + EXPECT_NE(cipher->base.destroy, nullptr); + EXPECT_NE(cipher->init, nullptr); + EXPECT_NE(cipher->update, nullptr); + EXPECT_NE(cipher->doFinal, nullptr); + OH_HCF_ObjDestroy(cipher); +} + +HWTEST_F(RsaCipherTest, RsaCipherTest250, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA2048|PKCS1", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(cipher, nullptr); + EXPECT_NE(cipher->base.getClass(), nullptr); + EXPECT_NE(cipher->base.destroy, nullptr); + EXPECT_NE(cipher->init, nullptr); + EXPECT_NE(cipher->update, nullptr); + EXPECT_NE(cipher->doFinal, nullptr); + OH_HCF_ObjDestroy(cipher); +} + +HWTEST_F(RsaCipherTest, RsaCipherTest260, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA512|PKCS1_OAEP|SHA256|MGF1_SHA256", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(cipher, nullptr); + EXPECT_NE(cipher->base.getClass(), nullptr); + EXPECT_NE(cipher->base.destroy, nullptr); + EXPECT_NE(cipher->init, nullptr); + EXPECT_NE(cipher->update, nullptr); + EXPECT_NE(cipher->doFinal, nullptr); + OH_HCF_ObjDestroy(cipher); +} + +HWTEST_F(RsaCipherTest, RsaCipherTest270, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA768|PKCS1_OAEP|SHA256|MGF1_SHA256", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(cipher, nullptr); + EXPECT_NE(cipher->base.getClass(), nullptr); + EXPECT_NE(cipher->base.destroy, nullptr); + EXPECT_NE(cipher->init, nullptr); + EXPECT_NE(cipher->update, nullptr); + EXPECT_NE(cipher->doFinal, nullptr); + OH_HCF_ObjDestroy(cipher); +} + +HWTEST_F(RsaCipherTest, RsaCipherTest280, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA2048|PKCS1_OAEP|SHA256|MGF1_SHA256", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(cipher, nullptr); + EXPECT_NE(cipher->base.getClass(), nullptr); + EXPECT_NE(cipher->base.destroy, nullptr); + EXPECT_NE(cipher->init, nullptr); + EXPECT_NE(cipher->update, nullptr); + EXPECT_NE(cipher->doFinal, nullptr); + OH_HCF_ObjDestroy(cipher); +} + + +// HcfCipherCreate Incorrect case +HWTEST_F(RsaCipherTest, RsaCipherTest300, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + res = HcfCipherCreate("RSA2048|PKCS1_OAEP|SHA256|MGF1_SHA256", NULL); + EXPECT_NE(res, HCF_SUCCESS); +} + +HWTEST_F(RsaCipherTest, RsaCipherTest310, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfCipher *cipher = NULL; + res = HcfCipherCreate(NULL, &cipher); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(cipher, nullptr); +} + +HWTEST_F(RsaCipherTest, RsaCipherTest320, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA2048|PKCS1_OAEP|SHA256|MGF1_SHA256|2111111111111111111111111111111111111111111111" + "111111111111123123", &cipher); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(cipher, nullptr); +} + +HWTEST_F(RsaCipherTest, RsaCipherTest330, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA2048|PKCS1_OAEP|SHA256|MGF1_SHA333", &cipher); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(cipher, nullptr); +} + +HWTEST_F(RsaCipherTest, RsaCipherTest340, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA2048|PKCS1_OAEP111|SHA256|MGF1_SHA333", &cipher); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(cipher, nullptr); +} + +HWTEST_F(RsaCipherTest, RsaCipherTest350, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA2111048|PKCS1_OAEP|SHA256|MGF1_SHA256", &cipher); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(cipher, nullptr); +} + +HWTEST_F(RsaCipherTest, RsaCipherTest360, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA2048|PKCS1_OAEP|SHA256111|MGF1_SHA256", &cipher); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(cipher, nullptr); +} + +// destroyCipher +HWTEST_F(RsaCipherTest, RsaCipherTest400, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA2048|PKCS1_OAEP|SHA256|MGF1_SHA256", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(cipher, nullptr); + OH_HCF_ObjDestroy(cipher); + cipher = NULL; + OH_HCF_ObjDestroy(cipher); +} + +// init correct case +HWTEST_F(RsaCipherTest, RsaCipherTest500, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfAsyKeyGenerator *generator = NULL; + res = HcfAsyKeyGeneratorCreate("RSA1024|PRIMES_2", &generator); + EXPECT_EQ(res, HCF_SUCCESS); + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA1024|PKCS1", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + res = cipher->init(cipher, ENCRYPT_MODE, (HcfKey *)keyPair->pubKey, NULL); + EXPECT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); + OH_HCF_ObjDestroy(cipher); +} + +HWTEST_F(RsaCipherTest, RsaCipherTest510, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfAsyKeyGenerator *generator = NULL; + res = HcfAsyKeyGeneratorCreate("RSA1024|PRIMES_2", &generator); + EXPECT_EQ(res, HCF_SUCCESS); + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA1024|PKCS1", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + res = cipher->init(cipher, DECRYPT_MODE, (HcfKey *)keyPair->priKey, NULL); + EXPECT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); + OH_HCF_ObjDestroy(cipher); +} + +// init incorrect case +HWTEST_F(RsaCipherTest, RsaCipherTest600, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfAsyKeyGenerator *generator = NULL; + res = HcfAsyKeyGeneratorCreate("RSA1024|PRIMES_2", &generator); + EXPECT_EQ(res, HCF_SUCCESS); + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA1024|PKCS1", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + res = cipher->init(cipher, ENCRYPT_MODE, (HcfKey *)keyPair->priKey, NULL); + EXPECT_NE(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); + OH_HCF_ObjDestroy(cipher); +} + +HWTEST_F(RsaCipherTest, RsaCipherTest610, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfAsyKeyGenerator *generator = NULL; + res = HcfAsyKeyGeneratorCreate("RSA1024|PRIMES_2", &generator); + EXPECT_EQ(res, HCF_SUCCESS); + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA1024|PKCS1", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + res = cipher->init(cipher, DECRYPT_MODE, (HcfKey *)keyPair->pubKey, NULL); + EXPECT_NE(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); + OH_HCF_ObjDestroy(cipher); +} + +HWTEST_F(RsaCipherTest, RsaCipherTest620, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfAsyKeyGenerator *generator = NULL; + res = HcfAsyKeyGeneratorCreate("RSA1024|PRIMES_2", &generator); + EXPECT_EQ(res, HCF_SUCCESS); + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA1024|PKCS1", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + res = cipher->init(NULL, DECRYPT_MODE, (HcfKey *)keyPair->pubKey, NULL); + EXPECT_NE(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); + OH_HCF_ObjDestroy(cipher); +} + +// incorrect case: use diff class, we ignore it in this version +HWTEST_F(RsaCipherTest, RsaCipherTest630, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfAsyKeyGenerator *generator = NULL; + res = HcfAsyKeyGeneratorCreate("RSA1024|PRIMES_2", &generator); + EXPECT_EQ(res, HCF_SUCCESS); + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfCipher *aesCipher = NULL; + res = HcfCipherCreate("AES128|ECB|PKCS7", &aesCipher); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA1024|PKCS1", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + res = cipher->init(aesCipher, DECRYPT_MODE, (HcfKey *)keyPair->pubKey, NULL); + EXPECT_NE(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); + OH_HCF_ObjDestroy(cipher); + OH_HCF_ObjDestroy(aesCipher); +} + +HWTEST_F(RsaCipherTest, RsaCipherTest640, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA1024|PKCS1", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + res = cipher->init(cipher, DECRYPT_MODE, NULL, NULL); + EXPECT_NE(res, HCF_SUCCESS); + OH_HCF_ObjDestroy(cipher); +} + +// correct case: update not support +HWTEST_F(RsaCipherTest, RsaCipherTest700, TestSize.Level0) +{ + uint8_t plan[] = "this is rsa cipher test!\0"; + HcfResult res = HCF_SUCCESS; + HcfAsyKeyGenerator *generator = NULL; + res = HcfAsyKeyGeneratorCreate("RSA1024|PRIMES_2", &generator); + EXPECT_EQ(res, HCF_SUCCESS); + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfBlob input = {.data = (uint8_t *)plan, .len = strlen((char *)plan)}; + HcfBlob encoutput = {.data = NULL, .len = 0}; + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA1024|PKCS1", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + res = cipher->init(cipher, ENCRYPT_MODE, (HcfKey *)keyPair->pubKey, NULL); + EXPECT_EQ(res, HCF_SUCCESS); + res = cipher->update(cipher, &input, &encoutput); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(encoutput.data, nullptr); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); + OH_HCF_ObjDestroy(cipher); +} + +// dofinal correct case +HWTEST_F(RsaCipherTest, RsaCipherTest800, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + uint8_t plan[] = "this is rsa cipher test!\0"; + HcfAsyKeyGenerator *generator = NULL; + res = HcfAsyKeyGeneratorCreate("RSA1024|PRIMES_2", &generator); + EXPECT_EQ(res, HCF_SUCCESS); + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(keyPair, nullptr); + EXPECT_NE(keyPair->priKey, nullptr); + EXPECT_NE(keyPair->pubKey, nullptr); + + HcfBlob input = {.data = (uint8_t *)plan, .len = strlen((char *)plan)}; + HcfBlob encoutput = {.data = NULL, .len = 0}; + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA1024|PKCS1", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + + res = cipher->init(cipher, ENCRYPT_MODE, (HcfKey *)keyPair->pubKey, NULL); + EXPECT_EQ(res, HCF_SUCCESS); + res = cipher->doFinal(cipher, &input, &encoutput); + EXPECT_EQ(res, HCF_SUCCESS); + OH_HCF_ObjDestroy(cipher); + + HcfBlob decoutput = {.data = NULL, .len = 0}; + cipher = NULL; + res = HcfCipherCreate("RSA1024|PKCS1", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + res = cipher->init(cipher, DECRYPT_MODE, (HcfKey *)keyPair->priKey, NULL); + EXPECT_EQ(res, HCF_SUCCESS); + res = cipher->doFinal(cipher, &encoutput, &decoutput); + EXPECT_EQ(res, HCF_SUCCESS); + OH_HCF_ObjDestroy(cipher); + EXPECT_STREQ((char *)plan, (char *)decoutput.data); + + HcfFree(encoutput.data); + HcfFree(decoutput.data); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaCipherTest, RsaCipherTest810, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + uint8_t plan[] = "this is rsa cipher test!\0"; + HcfAsyKeyGenerator *generator = NULL; + res = HcfAsyKeyGeneratorCreate("RSA4096|PRIMES_3", &generator); + EXPECT_EQ(res, HCF_SUCCESS); + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(keyPair, nullptr); + EXPECT_NE(keyPair->priKey, nullptr); + EXPECT_NE(keyPair->pubKey, nullptr); + + HcfBlob input = {.data = (uint8_t *)plan, .len = strlen((char *)plan)}; + HcfBlob encoutput = {.data = NULL, .len = 0}; + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA1024|PKCS1", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + + res = cipher->init(cipher, ENCRYPT_MODE, (HcfKey *)keyPair->pubKey, NULL); + EXPECT_EQ(res, HCF_SUCCESS); + res = cipher->doFinal(cipher, &input, &encoutput); + EXPECT_EQ(res, HCF_SUCCESS); + OH_HCF_ObjDestroy(cipher); + + HcfBlob decoutput = {.data = NULL, .len = 0}; + cipher = NULL; + res = HcfCipherCreate("RSA1024|PKCS1", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + res = cipher->init(cipher, DECRYPT_MODE, (HcfKey *)keyPair->priKey, NULL); + EXPECT_EQ(res, HCF_SUCCESS); + res = cipher->doFinal(cipher, &encoutput, &decoutput); + EXPECT_EQ(res, HCF_SUCCESS); + OH_HCF_ObjDestroy(cipher); + EXPECT_STREQ((char *)plan, (char *)decoutput.data); + + HcfFree(encoutput.data); + HcfFree(decoutput.data); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaCipherTest, RsaCipherTest820, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + uint8_t plan[] = "this is rsa cipher test!\0"; + HcfAsyKeyGenerator *generator = NULL; + res = HcfAsyKeyGeneratorCreate("RSA1024|PRIMES_2", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(keyPair, nullptr); + EXPECT_NE(keyPair->priKey, nullptr); + EXPECT_NE(keyPair->pubKey, nullptr); + + HcfBlob input = {.data = (uint8_t *)plan, .len = strlen((char *)plan)}; + HcfBlob encoutput = {.data = NULL, .len = 0}; + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA1024|PKCS1_OAEP|SHA256|MGF1_SHA256", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + + res = cipher->init(cipher, ENCRYPT_MODE, (HcfKey *)keyPair->pubKey, NULL); + EXPECT_EQ(res, HCF_SUCCESS); + res = cipher->doFinal(cipher, &input, &encoutput); + EXPECT_EQ(res, HCF_SUCCESS); + OH_HCF_ObjDestroy(cipher); + + HcfBlob decoutput = {.data = NULL, .len = 0}; + cipher = NULL; + res = HcfCipherCreate("RSA1024|PKCS1_OAEP|SHA256|MGF1_SHA256", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + res = cipher->init(cipher, DECRYPT_MODE, (HcfKey *)keyPair->priKey, NULL); + EXPECT_EQ(res, HCF_SUCCESS); + res = cipher->doFinal(cipher, &encoutput, &decoutput); + EXPECT_EQ(res, HCF_SUCCESS); + OH_HCF_ObjDestroy(cipher); + EXPECT_STREQ((char *)plan, (char *)decoutput.data); + + HcfFree(encoutput.data); + HcfFree(decoutput.data); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +// incorrect case: algName out of boundary +HWTEST_F(RsaCipherTest, RsaCipherTest830, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + uint8_t plan[] = "this is rsa cipher test aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!\0"; + HcfAsyKeyGenerator *generator = NULL; + res = HcfAsyKeyGeneratorCreate("RSA1024|PRIMES_2", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(keyPair, nullptr); + EXPECT_NE(keyPair->priKey, nullptr); + EXPECT_NE(keyPair->pubKey, nullptr); + + HcfBlob input = {.data = (uint8_t *)plan, .len = strlen((char *)plan)}; + HcfBlob encoutput = {.data = NULL, .len = 0}; + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA1024|PKCS1_OAEP|SHA256|MGF1_SHA256", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + + res = cipher->init(cipher, ENCRYPT_MODE, (HcfKey *)keyPair->pubKey, NULL); + EXPECT_EQ(res, HCF_SUCCESS); + res = cipher->doFinal(cipher, &input, &encoutput); + EXPECT_NE(res, HCF_SUCCESS); + OH_HCF_ObjDestroy(cipher); + + HcfBlob decoutput = {.data = NULL, .len = 0}; + cipher = NULL; + res = HcfCipherCreate("RSA1024|PKCS1_OAEP|SHA256|MGF1_SHA256", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + res = cipher->init(cipher, DECRYPT_MODE, (HcfKey *)keyPair->priKey, NULL); + EXPECT_EQ(res, HCF_SUCCESS); + res = cipher->doFinal(cipher, &encoutput, &decoutput); + EXPECT_NE(res, HCF_SUCCESS); + OH_HCF_ObjDestroy(cipher); + EXPECT_STRNE((char *)plan, (char *)decoutput.data); + + HcfFree(encoutput.data); + HcfFree(decoutput.data); + + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + + +// Incorrect case: use OAEP pading without mgf1md +HWTEST_F(RsaCipherTest, RsaCipherTest840, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + + HcfAsyKeyGenerator *generator = NULL; + res = HcfAsyKeyGeneratorCreate("RSA1024|PRIMES_2", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + OH_HCF_ObjDestroy(generator); + OH_HCF_ObjDestroy(keyPair); + + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA1024|PKCS1_OAEP|SHA256", &cipher); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(cipher, nullptr); +} + +// Incorrect case: use OAEP pading without md +HWTEST_F(RsaCipherTest, RsaCipherTest845, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + + HcfAsyKeyGenerator *generator = NULL; + res = HcfAsyKeyGeneratorCreate("RSA1024|PRIMES_2", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + OH_HCF_ObjDestroy(generator); + OH_HCF_ObjDestroy(keyPair); + + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA1024|PKCS1_OAEP|MGF1_SHA256", &cipher); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(cipher, nullptr); +} + +// Correct case: test genEncoded and convert key +HWTEST_F(RsaCipherTest, RsaCipherTest850, TestSize.Level0) +{ + uint8_t plan[] = "this is rsa cipher test!\0"; + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA1024", &generator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(generator, nullptr); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + HcfBlob pubKeyBlob = {.data = NULL, .len = 0}; + HcfBlob priKeyBlob = {.data = NULL, .len = 0}; + res = keyPair->pubKey->base.getEncoded((HcfKey *)keyPair->pubKey, &pubKeyBlob); + EXPECT_EQ(res, HCF_SUCCESS); + res = keyPair->priKey->base.getEncoded((HcfKey *)keyPair->priKey, &priKeyBlob); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfKeyPair *dupKeyPair = NULL; + res = generator->convertKey(generator, NULL, &pubKeyBlob, &priKeyBlob, &dupKeyPair); + EXPECT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(generator); + OH_HCF_ObjDestroy(keyPair); + + HcfBlob input = {.data = (uint8_t *)plan, .len = strlen((char *)plan)}; + HcfBlob encoutput = {.data = NULL, .len = 0}; + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA1024|PKCS1", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + + res = cipher->init(cipher, ENCRYPT_MODE, (HcfKey *)dupKeyPair->pubKey, NULL); + EXPECT_EQ(res, HCF_SUCCESS); + res = cipher->doFinal(cipher, &input, &encoutput); + EXPECT_EQ(res, HCF_SUCCESS); + OH_HCF_ObjDestroy(cipher); + + HcfBlob decoutput = {.data = NULL, .len = 0}; + cipher = NULL; + res = HcfCipherCreate("RSA1024|PKCS1", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + res = cipher->init(cipher, DECRYPT_MODE, (HcfKey *)dupKeyPair->priKey, NULL); + EXPECT_EQ(res, HCF_SUCCESS); + res = cipher->doFinal(cipher, &encoutput, &decoutput); + EXPECT_EQ(res, HCF_SUCCESS); + OH_HCF_ObjDestroy(cipher); + EXPECT_STREQ((char *)plan, (char *)decoutput.data); + + HcfFree(encoutput.data); + HcfFree(decoutput.data); + HcfFree(pubKeyBlob.data); + HcfFree(priKeyBlob.data); + OH_HCF_ObjDestroy(dupKeyPair); +} + +// correct case: test OAEP Plaintext boundary: +// RSA_size - (md_result_len * mgf1md_result_len) - 2 = 128 - (32 + 32) - 2 = 62 +HWTEST_F(RsaCipherTest, RsaCipherTest860, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + uint8_t plan1[] = "00112233445566778899aabbccddeeff0aaaaaaaaaaaaaaaaaaaaaaaaaa"; + uint8_t plan2[] = "00112233445566778899aabbccddeeffaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + uint8_t plan3[] = "00112233445566778899aabbccddeeff00112233445566778899aaaaaaaaaa"; + HcfAsyKeyGenerator *generator = NULL; + res = HcfAsyKeyGeneratorCreate("RSA1024|PRIMES_2", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(keyPair, nullptr); + EXPECT_NE(keyPair->priKey, nullptr); + EXPECT_NE(keyPair->pubKey, nullptr); + + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA1024|PKCS1_OAEP|SHA256|MGF1_SHA256", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + + res = cipher->init(cipher, ENCRYPT_MODE, (HcfKey *)keyPair->pubKey, NULL); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfBlob encoutput1 = {.data = NULL, .len = 0}; + HcfBlob encoutput2 = {.data = NULL, .len = 0}; + HcfBlob encoutput3 = {.data = NULL, .len = 0}; + HcfBlob input1 = {.data = (uint8_t *)plan1, .len = strlen((char *)plan1)}; + HcfBlob input2 = {.data = (uint8_t *)plan2, .len = strlen((char *)plan2)}; + HcfBlob input3 = {.data = (uint8_t *)plan3, .len = strlen((char *)plan3)}; + res = cipher->doFinal(cipher, &input1, &encoutput1); + EXPECT_EQ(res, HCF_SUCCESS); + res = cipher->doFinal(cipher, &input2, &encoutput2); + EXPECT_NE(res, HCF_SUCCESS); + res = cipher->doFinal(cipher, &input3, &encoutput2); + EXPECT_EQ(res, HCF_SUCCESS); + + + OH_HCF_ObjDestroy(cipher); + HcfFree(encoutput1.data); + HcfFree(encoutput2.data); + HcfFree(encoutput3.data); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +// correct case: test nopadding boundary < RSA_size(rsa) +HWTEST_F(RsaCipherTest, RsaCipherTest870, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + uint8_t plan1[] = "00112233445566778899aabbccddeeff00112233445566778899aabbccddeeffasdasdbccddeeff0011223344556600" + "1122334455111111111116"; + uint8_t plan2[] = "00112233445566778899aabbccddeeff00112233445566778899aabbccddeeffasdasdbccddeeff0011223344556600" + "112233445511111111111611111111111"; + + HcfAsyKeyGenerator *generator = NULL; + res = HcfAsyKeyGeneratorCreate("RSA1024|PRIMES_2", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(keyPair, nullptr); + EXPECT_NE(keyPair->priKey, nullptr); + EXPECT_NE(keyPair->pubKey, nullptr); + + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA1024|NoPadding", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + + res = cipher->init(cipher, ENCRYPT_MODE, (HcfKey *)keyPair->pubKey, NULL); + EXPECT_EQ(res, HCF_SUCCESS); + + + HcfBlob encoutput1 = {.data = NULL, .len = 0}; + HcfBlob encoutput2 = {.data = NULL, .len = 0}; + + HcfBlob input1 = {.data = (uint8_t *)plan1, .len = strlen((char *)plan1)}; + HcfBlob input2 = {.data = (uint8_t *)plan2, .len = strlen((char *)plan2)}; + + res = cipher->doFinal(cipher, &input1, &encoutput1); + EXPECT_NE(res, HCF_SUCCESS); + res = cipher->doFinal(cipher, &input2, &encoutput2); + EXPECT_EQ(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(cipher); + HcfFree(encoutput1.data); + HcfFree(encoutput2.data); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +// correct case: test PKCS1 boundary < RSA_size(rsa) - 11 +HWTEST_F(RsaCipherTest, RsaCipherTest880, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + uint8_t plan1[] = "00112233445566778899aabbccddeeff00112233445566778899aabbccddeeffasdasdbccddeeff0011223344556600" + "1122334455111111111116"; + uint8_t plan2[] = "00112233445566778899aabbccddeeff00112233445566778899aabbccddeeffasdasdbccddeeff0011223344556600" + "11223344551111111111161"; + + HcfAsyKeyGenerator *generator = NULL; + res = HcfAsyKeyGeneratorCreate("RSA1024|PRIMES_2", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(keyPair, nullptr); + EXPECT_NE(keyPair->priKey, nullptr); + EXPECT_NE(keyPair->pubKey, nullptr); + + HcfCipher *cipher = NULL; + res = HcfCipherCreate("RSA1024|PKCS1", &cipher); + EXPECT_EQ(res, HCF_SUCCESS); + + res = cipher->init(cipher, ENCRYPT_MODE, (HcfKey *)keyPair->pubKey, NULL); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfBlob encoutput1 = {.data = NULL, .len = 0}; + HcfBlob encoutput2 = {.data = NULL, .len = 0}; + + HcfBlob input1 = {.data = (uint8_t *)plan1, .len = strlen((char *)plan1)}; + HcfBlob input2 = {.data = (uint8_t *)plan2, .len = strlen((char *)plan2)}; + + res = cipher->doFinal(cipher, &input1, &encoutput1); + EXPECT_EQ(res, HCF_SUCCESS); + res = cipher->doFinal(cipher, &input2, &encoutput2); + EXPECT_NE(res, HCF_SUCCESS); + + OH_HCF_ObjDestroy(cipher); + HcfFree(encoutput1.data); + HcfFree(encoutput2.data); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} diff --git a/test/unittest/src/crypto_rsa_sign_test.cpp b/test/unittest/src/crypto_rsa_sign_test.cpp new file mode 100644 index 0000000..5fb5d69 --- /dev/null +++ b/test/unittest/src/crypto_rsa_sign_test.cpp @@ -0,0 +1,509 @@ +/* + * Copyright (C) 2022 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 "cstring" +#include "securec.h" +#include "asy_key_generator.h" +#include "blob.h" +#include "signature.h" +#include "memory.h" + +using namespace std; +using namespace testing::ext; + +class RsaSignTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void RsaSignTest::SetUp() {} +void RsaSignTest::TearDown() {} +void RsaSignTest::SetUpTestCase() {} +void RsaSignTest::TearDownTestCase() {} + +// HcfSignCreate correct_case +HWTEST_F(RsaSignTest, RsaSignTest100, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfSign *sign = NULL; + res = HcfSignCreate("RSA1024|PKCS1|MD5", &sign); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(sign, nullptr); + EXPECT_NE(sign->base.getClass(), nullptr); + EXPECT_NE(sign->base.destroy, nullptr); + EXPECT_NE(sign->init, nullptr); + EXPECT_NE(sign->update, nullptr); + EXPECT_NE(sign->sign, nullptr); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(RsaSignTest, RsaSignTest110, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfSign *sign = NULL; + res = HcfSignCreate("RSA1024|PKCS1|SHA1", &sign); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(sign, nullptr); + EXPECT_NE(sign->base.getClass(), nullptr); + EXPECT_NE(sign->base.destroy, nullptr); + EXPECT_NE(sign->init, nullptr); + EXPECT_NE(sign->update, nullptr); + EXPECT_NE(sign->sign, nullptr); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(RsaSignTest, RsaSignTest120, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfSign *sign = NULL; + res = HcfSignCreate("RSA1024|PKCS1|SHA256", &sign); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(sign, nullptr); + EXPECT_NE(sign->base.getClass(), nullptr); + EXPECT_NE(sign->base.destroy, nullptr); + EXPECT_NE(sign->init, nullptr); + EXPECT_NE(sign->update, nullptr); + EXPECT_NE(sign->sign, nullptr); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(RsaSignTest, RsaSignTest130, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfSign *sign = NULL; + res = HcfSignCreate("RSA1024|PKCS1|SHA512", &sign); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(sign, nullptr); + EXPECT_NE(sign->base.getClass(), nullptr); + EXPECT_NE(sign->base.destroy, nullptr); + EXPECT_NE(sign->init, nullptr); + EXPECT_NE(sign->update, nullptr); + EXPECT_NE(sign->sign, nullptr); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(RsaSignTest, RsaSignTest140, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfSign *sign = NULL; + res = HcfSignCreate("RSA1024|PSS|SHA1|MGF1_SHA1", &sign); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(sign, nullptr); + EXPECT_NE(sign->base.getClass(), nullptr); + EXPECT_NE(sign->base.destroy, nullptr); + EXPECT_NE(sign->init, nullptr); + EXPECT_NE(sign->update, nullptr); + EXPECT_NE(sign->sign, nullptr); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(RsaSignTest, RsaSignTest150, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfSign *sign = NULL; + res = HcfSignCreate("RSA1024|PSS|SHA256|MGF1_SHA512", &sign); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(sign, nullptr); + EXPECT_NE(sign->base.getClass(), nullptr); + EXPECT_NE(sign->base.destroy, nullptr); + EXPECT_NE(sign->init, nullptr); + EXPECT_NE(sign->update, nullptr); + EXPECT_NE(sign->sign, nullptr); + OH_HCF_ObjDestroy(sign); +} + +HWTEST_F(RsaSignTest, RsaSignTest160, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfSign *sign = NULL; + res = HcfSignCreate("RSA1024|PSS|SHA256|MGF1_SHA256", &sign); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(sign, nullptr); + EXPECT_NE(sign->base.getClass(), nullptr); + EXPECT_NE(sign->base.destroy, nullptr); + EXPECT_NE(sign->init, nullptr); + EXPECT_NE(sign->update, nullptr); + EXPECT_NE(sign->sign, nullptr); + OH_HCF_ObjDestroy(sign); +} + +// HcfSignCreate Incorrect case +HWTEST_F(RsaSignTest, RsaSignTest200, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfSign *sign = NULL; + res = HcfSignCreate("RSA1024|PSSaa|SHA256|MGF1_SHA256", &sign); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(sign, nullptr); +} + +HWTEST_F(RsaSignTest, RsaSignTest210, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfSign *sign = NULL; + res = HcfSignCreate(NULL, &sign); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(sign, nullptr); +} + +HWTEST_F(RsaSignTest, RsaSignTest220, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfSign *sign = NULL; + res = HcfSignCreate("RSA1024|PSS|SHA256|MGF1_SHA256|123123123123123123212312312321" + "123123123123213asdasdasdasdasdasdasdasdasdasdasdasdasdsasdasds12", &sign); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(sign, nullptr); +} + +HWTEST_F(RsaSignTest, RsaSignTest230, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfSign *sign = NULL; + res = HcfSignCreate("RSA1024|PSS|SHA256aa|MGF1_SHA256", &sign); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(sign, nullptr); +} + +HWTEST_F(RsaSignTest, RsaSignTest240, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfSign *sign = NULL; + res = HcfSignCreate("RSA1024|PSS|SHA256aa|MGF1_SHA256asdasdas", &sign); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(sign, nullptr); +} + +HWTEST_F(RsaSignTest, RsaSignTest250, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + HcfSign *sign = NULL; + res = HcfSignCreate("RSA1024|PSS|SHA256aa|MGF1_SHA256", &sign); + EXPECT_NE(res, HCF_SUCCESS); + EXPECT_EQ(sign, nullptr); +} + +HWTEST_F(RsaSignTest, RsaSignTest260, TestSize.Level0) +{ + HcfResult res = HCF_SUCCESS; + res = HcfSignCreate("RSA1024|PSS|SHA256aa|MGF1_SHA256", NULL); + EXPECT_NE(res, HCF_SUCCESS); +} + +// correct case: sign and update +HWTEST_F(RsaSignTest, RsaSignTest300, TestSize.Level0) +{ + uint8_t plan[] = "this is rsa verify test."; + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA768|PRIMES_2", &generator); + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfPriKey *prikey = keyPair->priKey; + HcfBlob input = {.data = plan, .len = strlen((char *)plan)}; + HcfBlob verifyData = {.data = NULL, .len = 0}; + HcfSign *sign = NULL; + res = HcfSignCreate("RSA768|PKCS1|SHA1", &sign); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->init(sign, NULL, prikey); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->sign(sign, &input, &verifyData); + + OH_HCF_ObjDestroy(sign); + HcfFree(verifyData.data); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaSignTest, RsaSignTest310, TestSize.Level0) +{ + uint8_t plan[] = "this is rsa verify test."; + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA1024|PRIMES_2", &generator); + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfPriKey *prikey = keyPair->priKey; + HcfBlob input = {.data = plan, .len = strlen((char *)plan)}; + HcfBlob verifyData = {.data = NULL, .len = 0}; + HcfSign *sign = NULL; + res = HcfSignCreate("RSA1024|PKCS1|SHA256", &sign); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->init(sign, NULL, prikey); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->sign(sign, &input, &verifyData); + + OH_HCF_ObjDestroy(sign); + HcfFree(verifyData.data); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaSignTest, RsaSignTest320, TestSize.Level0) +{ + uint8_t plan[] = "this is rsa verify test."; + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA2048|PRIMES_2", &generator); + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfPriKey *prikey = keyPair->priKey; + HcfBlob input = {.data = plan, .len = strlen((char *)plan)}; + HcfBlob verifyData = {.data = NULL, .len = 0}; + HcfSign *sign = NULL; + res = HcfSignCreate("RSA2048|PKCS1|SHA256", &sign); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->init(sign, NULL, prikey); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->sign(sign, &input, &verifyData); + + OH_HCF_ObjDestroy(sign); + HcfFree(verifyData.data); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaSignTest, RsaSignTest330, TestSize.Level0) +{ + uint8_t plan[] = "this is rsa verify test."; + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA4096|PRIMES_2", &generator); + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfPriKey *prikey = keyPair->priKey; + HcfBlob input = {.data = plan, .len = strlen((char *)plan)}; + HcfBlob verifyData = {.data = NULL, .len = 0}; + HcfSign *sign = NULL; + res = HcfSignCreate("RSA4096|PKCS1|SHA256", &sign); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->init(sign, NULL, prikey); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->sign(sign, &input, &verifyData); + + OH_HCF_ObjDestroy(sign); + HcfFree(verifyData.data); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaSignTest, RsaSignTest340, TestSize.Level0) +{ + uint8_t plan[] = "this is rsa verify test."; + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA4096|PRIMES_2", &generator); + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfPriKey *prikey = keyPair->priKey; + HcfBlob input = {.data = plan, .len = strlen((char *)plan)}; + HcfBlob verifyData = {.data = NULL, .len = 0}; + HcfSign *sign = NULL; + res = HcfSignCreate("RSA4096|PKCS1|SHA512", &sign); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->init(sign, NULL, prikey); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->sign(sign, &input, &verifyData); + + OH_HCF_ObjDestroy(sign); + HcfFree(verifyData.data); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaSignTest, RsaSignTest350, TestSize.Level0) +{ + uint8_t plan[] = "this is rsa verify test."; + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA1024|PRIMES_2", &generator); + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfPriKey *prikey = keyPair->priKey; + HcfBlob input = {.data = plan, .len = strlen((char *)plan)}; + HcfBlob verifyData = {.data = NULL, .len = 0}; + HcfSign *sign = NULL; + res = HcfSignCreate("RSA1024|PSS|SHA256|MGF1_SHA256", &sign); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->init(sign, NULL, prikey); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->sign(sign, &input, &verifyData); + + OH_HCF_ObjDestroy(sign); + HcfFree(verifyData.data); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaSignTest, RsaSignTest360, TestSize.Level0) +{ + uint8_t plan[] = "this is rsa verify test."; + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA2048|PRIMES_2", &generator); + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfPriKey *prikey = keyPair->priKey; + HcfBlob input = {.data = plan, .len = strlen((char *)plan)}; + HcfBlob verifyData = {.data = NULL, .len = 0}; + HcfSign *sign = NULL; + res = HcfSignCreate("RSA2048|PSS|SHA256|MGF1_SHA256", &sign); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->init(sign, NULL, prikey); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->sign(sign, &input, &verifyData); + + OH_HCF_ObjDestroy(sign); + HcfFree(verifyData.data); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaSignTest, RsaSignTest370, TestSize.Level0) +{ + uint8_t plan[] = "this is rsa verify test."; + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA3072|PRIMES_2", &generator); + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfPriKey *prikey = keyPair->priKey; + HcfBlob input = {.data = plan, .len = strlen((char *)plan)}; + HcfBlob verifyData = {.data = NULL, .len = 0}; + HcfSign *sign = NULL; + res = HcfSignCreate("RSA3072|PSS|SHA256|MGF1_SHA256", &sign); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->init(sign, NULL, prikey); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->sign(sign, &input, &verifyData); + + OH_HCF_ObjDestroy(sign); + HcfFree(verifyData.data); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaSignTest, RsaSignTest380, TestSize.Level0) +{ + uint8_t plan[] = "this is rsa verify test."; + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA4096|PRIMES_2", &generator); + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfPriKey *prikey = keyPair->priKey; + HcfBlob input = {.data = plan, .len = strlen((char *)plan)}; + HcfBlob verifyData = {.data = NULL, .len = 0}; + HcfSign *sign = NULL; + res = HcfSignCreate("RSA4096|PSS|SHA256|MGF1_SHA256", &sign); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->init(sign, NULL, prikey); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->sign(sign, &input, &verifyData); + + OH_HCF_ObjDestroy(sign); + HcfFree(verifyData.data); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaSignTest, RsaSignTest390, TestSize.Level0) +{ + uint8_t plan[] = "this is rsa verify test."; + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA4096|PRIMES_2", &generator); + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfPriKey *prikey = keyPair->priKey; + HcfBlob input = {.data = plan, .len = strlen((char *)plan)}; + HcfBlob verifyData = {.data = NULL, .len = 0}; + HcfSign *sign = NULL; + res = HcfSignCreate("RSA4096|PSS|SHA512|MGF1_SHA256", &sign); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->init(sign, NULL, prikey); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->sign(sign, &input, &verifyData); + + OH_HCF_ObjDestroy(sign); + HcfFree(verifyData.data); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaSignTest, RsaSignTest400, TestSize.Level0) +{ + uint8_t plan[] = "this is rsa verify test."; + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA4096|PRIMES_2", &generator); + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfPriKey *prikey = keyPair->priKey; + HcfBlob input = {.data = plan, .len = strlen((char *)plan)}; + HcfBlob verifyData = {.data = NULL, .len = 0}; + HcfSign *sign = NULL; + res = HcfSignCreate("RSA4096|PSS|SHA1|MGF1_SHA256", &sign); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->init(sign, NULL, prikey); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->sign(sign, &input, &verifyData); + + OH_HCF_ObjDestroy(sign); + HcfFree(verifyData.data); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaSignTest, RsaSignTest410, TestSize.Level0) +{ + uint8_t plan[] = "this is rsa verify test."; + HcfAsyKeyGenerator *generator = NULL; + HcfResult res = HcfAsyKeyGeneratorCreate("RSA4096|PRIMES_2", &generator); + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfPriKey *prikey = keyPair->priKey; + HcfBlob input = {.data = plan, .len = strlen((char *)plan)}; + HcfBlob verifyData = {.data = NULL, .len = 0}; + HcfSign *sign = NULL; + res = HcfSignCreate("RSA4096|PSS|SHA256|MGF1_MD5", &sign); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->init(sign, NULL, prikey); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->sign(sign, &input, &verifyData); + + OH_HCF_ObjDestroy(sign); + HcfFree(verifyData.data); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + diff --git a/test/unittest/src/crypto_rsa_verify_test.cpp b/test/unittest/src/crypto_rsa_verify_test.cpp new file mode 100644 index 0000000..f7e1f40 --- /dev/null +++ b/test/unittest/src/crypto_rsa_verify_test.cpp @@ -0,0 +1,468 @@ +/* + * Copyright (C) 2022 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 "blob.h" +#include "memory.h" +#include "signature.h" +#include "cstring" + + +using namespace std; +using namespace testing::ext; + +class RsaVerifyTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void RsaVerifyTest::SetUp() {} +void RsaVerifyTest::TearDown() {} +void RsaVerifyTest::SetUpTestCase() {} +void RsaVerifyTest::TearDownTestCase() {} + +HWTEST_F(RsaVerifyTest, RsaVerifyTest100, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("RSA1024|PSS|SHA256", &verify); + EXPECT_NE(res, HCF_SUCCESS); + ASSERT_EQ(verify, nullptr); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(RsaVerifyTest, RsaVerifyTest110, TestSize.Level0) +{ + HcfVerify *verify = NULL; + int32_t res = HcfVerifyCreate("RSA1024|PSS|SHA256|MGF1_SHA256", &verify); + EXPECT_EQ(res, HCF_SUCCESS); + ASSERT_NE(verify, nullptr); + + OH_HCF_ObjDestroy(verify); +} + +HWTEST_F(RsaVerifyTest, RsaVerifyTest200, TestSize.Level0) +{ + uint8_t plan[] = "this is rsa verify test."; + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("RSA2048|PRIMES_2", &generator); + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfPubKey *pubkey = keyPair->pubKey; + HcfPriKey *prikey = keyPair->priKey; + HcfBlob input = {.data = plan, .len = strlen((char *)plan)}; + HcfBlob verifyData = {.data = NULL, .len = 0}; + HcfSign *sign = NULL; + res = HcfSignCreate("RSA1024|PSS|SHA256|MGF1_SHA256", &sign); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->init(sign, NULL, prikey); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->sign(sign, &input, &verifyData); + OH_HCF_ObjDestroy(sign); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("RSA1024|PSS|SHA256|MGF1_SHA256", &verify); + EXPECT_EQ(res, HCF_SUCCESS); + res = verify->init(verify, NULL, pubkey); + EXPECT_EQ(res, HCF_SUCCESS); + res = verify->verify(verify, &input, &verifyData); + EXPECT_EQ(res, 1); + OH_HCF_ObjDestroy(verify); + + HcfFree(verifyData.data); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaVerifyTest, RsaVerifyTest210, TestSize.Level0) +{ + uint8_t plan[] = "this is rsa verify test aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa."; + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("RSA2048|PRIMES_2", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfPubKey *pubkey = keyPair->pubKey; + HcfPriKey *prikey = keyPair->priKey; + + HcfBlob input = {.data = plan, .len = strlen((char *)plan)}; + HcfBlob verifyData = {.data = NULL, .len = 0}; + HcfSign *sign = NULL; + res = HcfSignCreate("RSA1024|PSS|SHA256|MGF1_SHA256", &sign); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->init(sign, NULL, prikey); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->sign(sign, &input, &verifyData); + OH_HCF_ObjDestroy(sign); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("RSA1024|PSS|SHA256|MGF1_SHA256", &verify); + EXPECT_EQ(res, HCF_SUCCESS); + res = verify->init(verify, NULL, pubkey); + EXPECT_EQ(res, HCF_SUCCESS); + res = verify->verify(verify, &input, &verifyData); + EXPECT_EQ(res, 1); + OH_HCF_ObjDestroy(verify); + + HcfFree(verifyData.data); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaVerifyTest, RsaVerifyTest220, TestSize.Level0) +{ + uint8_t plan[] = "this is rsa verify test aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa."; + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("RSA2048|PRIMES_2", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfPubKey *pubkey = keyPair->pubKey; + HcfPriKey *prikey = keyPair->priKey; + + HcfBlob input = {.data = plan, .len = strlen((char *)plan)}; + HcfBlob verifyData = {.data = NULL, .len = 0}; + HcfSign *sign = NULL; + res = HcfSignCreate("RSA1024|PSS|SHA256|MGF1_SHA512", &sign); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->init(sign, NULL, prikey); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->sign(sign, &input, &verifyData); + OH_HCF_ObjDestroy(sign); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("RSA1024|PSS|SHA256|MGF1_SHA512", &verify); + EXPECT_EQ(res, HCF_SUCCESS); + res = verify->init(verify, NULL, pubkey); + EXPECT_EQ(res, HCF_SUCCESS); + res = verify->verify(verify, &input, &verifyData); + EXPECT_EQ(res, 1); + OH_HCF_ObjDestroy(verify); + + HcfFree(verifyData.data); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaVerifyTest, RsaVerifyTest230, TestSize.Level0) +{ + uint8_t plan[] = "this is rsa verify test aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa."; + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("RSA2048|PRIMES_2", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfPubKey *pubkey = keyPair->pubKey; + HcfPriKey *prikey = keyPair->priKey; + + HcfBlob input = {.data = plan, .len = strlen((char *)plan)}; + HcfBlob verifyData = {.data = NULL, .len = 0}; + HcfSign *sign = NULL; + res = HcfSignCreate("RSA1024|PKCS1|SHA256", &sign); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->init(sign, NULL, prikey); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->sign(sign, &input, &verifyData); + OH_HCF_ObjDestroy(sign); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("RSA1024|PKCS1|SHA256", &verify); + EXPECT_EQ(res, HCF_SUCCESS); + res = verify->init(verify, NULL, pubkey); + EXPECT_EQ(res, HCF_SUCCESS); + res = verify->verify(verify, &input, &verifyData); + EXPECT_EQ(res, 1); + OH_HCF_ObjDestroy(verify); + + HcfFree(verifyData.data); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +HWTEST_F(RsaVerifyTest, RsaVerifyTest240, TestSize.Level0) +{ + uint8_t plan[] = "this is rsa verify test aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa."; + uint8_t errorverify[] = "asdfasdfasdfasf"; + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("RSA2048|PRIMES_2", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfPubKey *pubkey = keyPair->pubKey; + HcfPriKey *prikey = keyPair->priKey; + + HcfBlob input = {.data = plan, .len = strlen((char *)plan)}; + HcfBlob verifyData = {.data = NULL, .len = 0}; + HcfBlob invalidverifyData = {.data = errorverify, .len = strlen((char *)errorverify)}; + HcfSign *sign = NULL; + res = HcfSignCreate("RSA1024|PKCS1|SHA256", &sign); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->init(sign, NULL, prikey); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->sign(sign, &input, &verifyData); + OH_HCF_ObjDestroy(sign); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("RSA1024|PKCS1|SHA256", &verify); + EXPECT_EQ(res, HCF_SUCCESS); + res = verify->init(verify, NULL, pubkey); + EXPECT_EQ(res, HCF_SUCCESS); + res = verify->verify(verify, &input, &invalidverifyData); + EXPECT_EQ(res, 0); + OH_HCF_ObjDestroy(verify); + + HcfFree(verifyData.data); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +// Incorrect case: different mode +HWTEST_F(RsaVerifyTest, RsaVerifyTest250, TestSize.Level0) +{ + uint8_t plan[] = "this is rsa verify test aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa."; + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("RSA2048|PRIMES_2", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfPubKey *pubkey = keyPair->pubKey; + HcfPriKey *prikey = keyPair->priKey; + + HcfBlob input = {.data = plan, .len = strlen((char *)plan)}; + HcfBlob verifyData = {.data = NULL, .len = 0}; + HcfSign *sign = NULL; + res = HcfSignCreate("RSA1024|PKCS1|SHA256", &sign); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->init(sign, NULL, prikey); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->sign(sign, &input, &verifyData); + OH_HCF_ObjDestroy(sign); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("RSA1024|PSS|SHA256|MGF1_SHA512", &verify); + EXPECT_EQ(res, HCF_SUCCESS); + res = verify->init(verify, NULL, pubkey); + EXPECT_EQ(res, HCF_SUCCESS); + res = verify->verify(verify, &input, &verifyData); + EXPECT_EQ(res, 0); + OH_HCF_ObjDestroy(verify); + + HcfFree(verifyData.data); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +// Incorrect case: different mgf1md +HWTEST_F(RsaVerifyTest, RsaVerifyTest260, TestSize.Level0) +{ + uint8_t plan[] = "this is rsa verify test aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa."; + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("RSA2048|PRIMES_2", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfPubKey *pubkey = keyPair->pubKey; + HcfPriKey *prikey = keyPair->priKey; + + HcfBlob input = {.data = plan, .len = strlen((char *)plan)}; + HcfBlob verifyData = {.data = NULL, .len = 0}; + HcfSign *sign = NULL; + res = HcfSignCreate("RSA1024|PSS|SHA256|MGF1_SHA256", &sign); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->init(sign, NULL, prikey); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->sign(sign, &input, &verifyData); + OH_HCF_ObjDestroy(sign); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("RSA1024|PSS|SHA256|MGF1_SHA512", &verify); + EXPECT_EQ(res, HCF_SUCCESS); + res = verify->init(verify, NULL, pubkey); + EXPECT_EQ(res, HCF_SUCCESS); + res = verify->verify(verify, &input, &verifyData); + EXPECT_EQ(res, 0); + OH_HCF_ObjDestroy(verify); + + HcfFree(verifyData.data); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + + +// Incorrect case: different pkcs1 md, verifu fail +HWTEST_F(RsaVerifyTest, RsaVerifyTest270, TestSize.Level0) +{ + uint8_t plan[] = "this is rsa verify test aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa."; + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("RSA2048|PRIMES_2", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfPubKey *pubkey = keyPair->pubKey; + HcfPriKey *prikey = keyPair->priKey; + + HcfBlob input = {.data = plan, .len = strlen((char *)plan)}; + HcfBlob verifyData = {.data = NULL, .len = 0}; + HcfSign *sign = NULL; + res = HcfSignCreate("RSA1024|PKCS1|SHA256", &sign); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->init(sign, NULL, prikey); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->sign(sign, &input, &verifyData); + OH_HCF_ObjDestroy(sign); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("RSA1024|PKCS1|SHA512", &verify); + EXPECT_EQ(res, HCF_SUCCESS); + res = verify->init(verify, NULL, pubkey); + EXPECT_EQ(res, HCF_SUCCESS); + res = verify->verify(verify, &input, &verifyData); + EXPECT_EQ(res, 0); + OH_HCF_ObjDestroy(verify); + + HcfFree(verifyData.data); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +// check update_func in PSS padding +HWTEST_F(RsaVerifyTest, RsaVerifyTest280, TestSize.Level0) +{ + uint8_t plan1[] = "this is rsa verify test plane1 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa."; + uint8_t plan2[] = "this is rsa verify test plane2 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa."; + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("RSA2048|PRIMES_2", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfPubKey *pubkey = keyPair->pubKey; + HcfPriKey *prikey = keyPair->priKey; + + HcfBlob input = {.data = plan1, .len = strlen((char *)plan1)}; + HcfBlob inputEx = {.data = plan2, .len = strlen((char *)plan2)}; + HcfBlob verifyData = {.data = NULL, .len = 0}; + HcfSign *sign = NULL; + res = HcfSignCreate("RSA1024|PSS|SHA256|MGF1_SHA256", &sign); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->init(sign, NULL, prikey); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->update(sign, &input); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->sign(sign, &inputEx, &verifyData); + EXPECT_EQ(res, HCF_SUCCESS); + OH_HCF_ObjDestroy(sign); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("RSA1024|PSS|SHA256|MGF1_SHA256", &verify); + EXPECT_EQ(res, HCF_SUCCESS); + res = verify->init(verify, NULL, pubkey); + EXPECT_EQ(res, HCF_SUCCESS); + res = verify->update(verify, &input); + EXPECT_EQ(res, HCF_SUCCESS); + res = verify->verify(verify, &inputEx, &verifyData); + EXPECT_EQ(res, 1); + OH_HCF_ObjDestroy(verify); + + HcfFree(verifyData.data); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +// check update in PKCS1 padding +HWTEST_F(RsaVerifyTest, RsaVerifyTest290, TestSize.Level0) +{ + uint8_t plan1[] = "this is rsa verify test plane1 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa."; + uint8_t plan2[] = "this is rsa verify test plane2 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa."; + uint8_t plan3[] = "this is rsa verify test plane3 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa."; + + HcfAsyKeyGenerator *generator = NULL; + int32_t res = HcfAsyKeyGeneratorCreate("RSA2048|PRIMES_2", &generator); + + HcfKeyPair *keyPair = NULL; + res = generator->generateKeyPair(generator, NULL, &keyPair); + EXPECT_EQ(res, HCF_SUCCESS); + + HcfPubKey *pubkey = keyPair->pubKey; + HcfPriKey *prikey = keyPair->priKey; + + HcfBlob input1 = {.data = plan1, .len = strlen((char *)plan1)}; + HcfBlob input2 = {.data = plan2, .len = strlen((char *)plan2)}; + HcfBlob input3 = {.data = plan3, .len = strlen((char *)plan3)}; + HcfBlob verifyData = {.data = NULL, .len = 0}; + HcfSign *sign = NULL; + res = HcfSignCreate("RSA1024|PKCS1|SHA256", &sign); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->init(sign, NULL, prikey); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->update(sign, &input1); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->update(sign, &input2); + EXPECT_EQ(res, HCF_SUCCESS); + res = sign->sign(sign, &input3, &verifyData); + EXPECT_EQ(res, HCF_SUCCESS); + OH_HCF_ObjDestroy(sign); + + HcfVerify *verify = NULL; + res = HcfVerifyCreate("RSA1024|PKCS1|SHA256", &verify); + EXPECT_EQ(res, HCF_SUCCESS); + res = verify->init(verify, NULL, pubkey); + EXPECT_EQ(res, HCF_SUCCESS); + res = verify->update(verify, &input1); + EXPECT_EQ(res, HCF_SUCCESS); + res = verify->update(verify, &input2); + EXPECT_EQ(res, HCF_SUCCESS); + res = verify->verify(verify, &input3, &verifyData); + EXPECT_EQ(res, 1); + OH_HCF_ObjDestroy(verify); + + HcfFree(verifyData.data); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} diff --git a/test/unittest/src/crypto_x509_certificate_test.cpp b/test/unittest/src/crypto_x509_certificate_test.cpp new file mode 100644 index 0000000..453be95 --- /dev/null +++ b/test/unittest/src/crypto_x509_certificate_test.cpp @@ -0,0 +1,1062 @@ +/* + * Copyright (C) 2022 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 "x509_certificate.h" +#include "blob.h" + +using namespace std; +using namespace testing::ext; + +class X509CertTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +static char g_deviceTestCert[] = +"-----BEGIN CERTIFICATE-----\r\n" +"MIIEQDCCAyigAwIBAgIQICAIMRlDU0ytSEUfNeOUJTANBgkqhkiG9w0BAQsFADBcMQswCQYDVQQG\r\n" +"EwJDTjEPMA0GA1UECgwGSHVhd2VpMRMwEQYDVQQLDApIdWF3ZWkgQ0JHMScwJQYDVQQDDB5IdWF3\r\n" +"ZWkgQ0JHIE1vYmlsZSBFcXVpcG1lbnQgQ0EwHhcNMjAwODMxMTE0MzUzWhcNMzAwODI5MTE0MzUz\r\n" +"WjBvMQswCQYDVQQGEwJDTjEPMA0GA1UECgwGSHVhd2VpMRMwEQYDVQQLDApIdWF3ZWkgQ0JHMTow\r\n" +"OAYDVQQDDDFIVUFXRUlfSFdKQURfODE4ZjhjNDUtOGNmNC00ZTM2LTkxOTMtNTQ5OWMwNzM0YzM4\r\n" +"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArZcfL6ot4z6k3T4X3C26EI557Zvrx9Ci\r\n" +"hNx6RMy+vjXa3E4BkxwZ3r0ADbc+msJOq0IyQJNujaLq35oQvJgMIvBn1xFurBXdOzbygc7G9GKt\r\n" +"sb4rmKUP0QEPHM2/TrxAJT2LNPLrOE047ESe2X76FpDY6oZdsoGJ5I9m/mlfGsxR1l1TeUjwA/Rs\r\n" +"UtISR66aastBy2tU7IubP0B0Gceqy9DnjTQtY9OpkOql08H20C30iCVijK6BmP43X4OMz2MS0leV\r\n" +"K0AHmhiv6ufu166Xtc2JOXRk/MJ+53iprvVEUowKY/ZATUz6iDHDZYM3MdQV+VbFrOevUceOSweY\r\n" +"PaXCzwIDAQABo4HqMIHnMB8GA1UdIwQYMBaAFDXT2UhPcFFNI7Ey1dXdJSHOBS7dMB0GA1UdDgQW\r\n" +"BBSndBqCYYcTB1kMNhYMM4r/vDLteTARBglghkgBhvhCAQEEBAMCBsAwCwYDVR0PBAQDAgTwMGYG\r\n" +"A1UdHwRfMF0wW6BZoFeGVWh0dHA6Ly9jcGtpLWNhd2ViLmh1YXdlaS5jb20vY3BraS9zZXJ2bGV0\r\n" +"L2NybEZpbGVEb3duLmNybD9jZXJ0eXBlPTQmeWVhcj0vY3JsMjAyMC5jcmwwHQYDVR0lBBYwFAYI\r\n" +"KwYBBQUHAwEGCCsGAQUFBwMCMA0GCSqGSIb3DQEBCwUAA4IBAQCNTqZHRy7BJ+KFOflqwYkeD1Yd\r\n" +"K5XxcZUykw8AefX3SMYzSBzy7IIIhM5bvhWF6r5NnBJYqmyQfy+3K0Z0LQXfsY95U9JBkKl3nQPn\r\n" +"p1PzV8wLp/XYE7ePsbIbjQ1gQdC47sTDjoA73X4wEchdEVJBNUs2e15HRxbzaVJ6ABSKI9AHkxKv\r\n" +"o9iYKFozQaL4y+3Y+Yei/N1kiZZayJqC1uXq45kelc3SCJrVPE4g/Uspf2jjp7xsS+MkmxvSAT9X\r\n" +"OJeDWEeXyt7tvJeodRQgGZVhdtN78mtoaqWqD9Z6a6wpWdC4sZCWJfMjCu4Wd889Pn4MT5DBKBN3\r\n" +"f3+JpOzUJlM9\r\n" +"-----END CERTIFICATE-----\r\n"; + +static char g_rootCert[] = +"-----BEGIN CERTIFICATE-----\r\n" +"MIIGQDCCBCigAwIBAgIUKNQFxqguJbKjFXanBmC2ZwUv9dkwDQYJKoZIhvcNAQEL\r\n" +"BQAwejELMAkGA1UEBhMCQ04xETAPBgNVBAgMCFNIQU5HSEFJMREwDwYDVQQHDAhT\r\n" +"SEFOR0hBSTELMAkGA1UECgwCQUExCzAJBgNVBAsMAkJCMQswCQYDVQQDDAJDQzEe\r\n" +"MBwGCSqGSIb3DQEJARYPZmlyc3RAaGVsbG8uY29tMCAXDTIyMDgyMzExMjk0MVoY\r\n" +"DzIwNjIwODIzMTEyOTQxWjB6MQswCQYDVQQGEwJDTjERMA8GA1UECAwIU0hBTkdI\r\n" +"QUkxETAPBgNVBAcMCFNIQU5HSEFJMQswCQYDVQQKDAJBQTELMAkGA1UECwwCQkIx\r\n" +"CzAJBgNVBAMMAkNDMR4wHAYJKoZIhvcNAQkBFg9maXJzdEBoZWxsby5jb20wggIi\r\n" +"MA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCr4nXrmskgHytDYcp8/BRORk71\r\n" +"f2idSs6cxxSOycILA3fbhbCB3qA8Bj4k1bT592j99MsKm+djMFvUOW/mS6iEWcoS\r\n" +"sK1HvYX2d7y0GMDnltT9I/KlcYDHiwcq0UgHX4OSbB70EUt9vUmq/opYeUJFIbfq\r\n" +"QJvGu57PJw+lxdsq3mZvx8n04fIMxqJdQSXu2foh0fSIePthNIV5JNtO9tTmmKn9\r\n" +"b+L9Eb1IfhKnvxNVuq046+eUwRA3Qva4HQOkCplamfU+b2dQGXnpha/NzXfCVuZK\r\n" +"R13xhUXjuXADGAIoRl9BgxgONTVpy209xQ7W1UvVEbSVDf8r9OlPDf3olRoavTAv\r\n" +"+EaYyqrFoEtTzIRZDiLIhqjoqtpbrl5oVggfH/qn8qDyZ+a6puwa81+9Mad8CLwh\r\n" +"Q9sa0uT+AET86gCGgpOBPF31+xYgnznQjd2wRs5a2rrYjy5wqAYyGPNUy9lm2EaU\r\n" +"03jMv+JzgeSdyqly8g3oCxBhRENgtGWlMUzzqZoM+Z6/NUn+pebRr53z4lzQWFFV\r\n" +"M1M81OHIKnleuud5CTnuRNfX7jVX9O+iu/bHjU2YKKrB3L1+ZY0cf6RXUDsBFSxg\r\n" +"dRZXBVvjJ8Ag+PDYOGG4Cbh9NByhvNvoKa7eBDpWXkOcP6VqnlIL33AUNKk9NEZc\r\n" +"KpyN1Dbk3eN/c9pIBQIDAQABo4G7MIG4MB0GA1UdDgQWBBRn2V1KId/KpzEztYbH\r\n" +"PHbCFqIioTAfBgNVHSMEGDAWgBRn2V1KId/KpzEztYbHPHbCFqIioTASBgNVHRMB\r\n" +"Af8ECDAGAQH/AgEDMAsGA1UdDwQEAwIBBjAdBgNVHSUEFjAUBggrBgEFBQcDAQYI\r\n" +"KwYBBQUHAwIwGgYDVR0RBBMwEYEPZmlyc3RAaGVsbG8uY29tMBoGA1UdEgQTMBGB\r\n" +"D2ZpcnN0QGhlbGxvLmNvbTANBgkqhkiG9w0BAQsFAAOCAgEAqbo9c3pEMfk4pmTL\r\n" +"Oays4RGZy9kZtZMOgdNvZ1gLbRow85x3mSOQ7ew8trt4PbjEp48EQzTFy4AxsBj/\r\n" +"Kw7p6Y9RAu/fBQMOMwIKzBUW9gayehpOyRTgnt27jDUBBXcq21HDy+WK9FTreqTG\r\n" +"R2CH/Yt75pfsHLWulq7Ou3s5sWvLyuYxohVDsIJfJHwgUSGPB33bFGqSxzN4qOMJ\r\n" +"4+M1OO0+hHVWzqESmYBaroX7XYoFeVOJsEDdjU9lccIZpfupbZ4ljjdBk3v45WSt\r\n" +"gbTS2NYauczjl3wT/p5EU7iGf1a8rSOjUqZS6cmDP7Tq0PL4+1iMCZlF1ZXLvPb4\r\n" +"dCAebIPMF7Pn1BLjANsQ94iKWHmPWdl8m6QmdCtSGgt7zNx3W0N6kF/7tRdshUQD\r\n" +"mPXFZed3U3vVVCOGPPY/KYnNvU2umJ4EsDSThlRPPafZ8GDuj1cF4OGdxfNx6bSQ\r\n" +"E6Zuj4oYR1k5+vAWbVS6F25KV0C6mXkrmL/pl2JQt+fyWIjGxP3pkBcxBYyP+OgQ\r\n" +"hX9yv+cUIkDPNa9yytVn2Z+9CFJbz3l/AxIxTqR5a3m9Qlls4otQKco0E9ArA3ce\r\n" +"v9YYMHEDo61jQYTd2rz7BvIdvQ+ds4V+GjmgDFa21tMvpNxC6LMy4gS4PmOSAbMu\r\n" +"jI6AaoTlr5I7zPhFbR8/XEs7DzI=\r\n" +"-----END CERTIFICATE-----\r\n"; + +static char g_secondCert[] = +"-----BEGIN CERTIFICATE-----\r\n" +"MIIFwjCCA6qgAwIBAgIUTUs0/9mQvlKZ67Q3nDR+5bwvyoowDQYJKoZIhvcNAQEL\r\n" +"BQAwejELMAkGA1UEBhMCQ04xETAPBgNVBAgMCFNIQU5HSEFJMREwDwYDVQQHDAhT\r\n" +"SEFOR0hBSTELMAkGA1UECgwCQUExCzAJBgNVBAsMAkJCMQswCQYDVQQDDAJDQzEe\r\n" +"MBwGCSqGSIb3DQEJARYPZmlyc3RAaGVsbG8uY29tMB4XDTIyMDgyMzExMzQwMFoX\r\n" +"DTQyMDgyMzExMzQwMFowezELMAkGA1UEBhMCQ04xETAPBgNVBAgMCFNIQU5HSEFJ\r\n" +"MREwDwYDVQQHDAhTSEFOR0hBSTELMAkGA1UECgwCQUExCzAJBgNVBAsMAkJCMQsw\r\n" +"CQYDVQQDDAJDQzEfMB0GCSqGSIb3DQEJARYQc2Vjb25kQGhlbGxvLmNvbTCCAiIw\r\n" +"DQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAJkLbBN8iHBWDHCdoMPpUwIeCSpW\r\n" +"nWdqJJ83Hmp3KQvm2sY9l2VOMFE+D9QJr3rRLuzQLYwcGjCcqcq+a7up7jfyB+wm\r\n" +"FR+H1d9Mnv3G4n1ljwBuGqYr7QQh/6tZ7OsMaSdj6hAQe6b2eFeB1qpTORA2smX+\r\n" +"uQZ6C47kKOVkna/P8ipSgnQZejX5f+O/SsystdCLbtkZCGXOahMhi9mmdbK0jNuy\r\n" +"ZhM2sea8NiQONQjSFQm1pC0wpMyvCsZt0Xucxgv9pBvcX/w2BV8DrJ67yD61Lac2\r\n" +"4x9u7FgBlJRHqBz8pdMo11dwXaBKLL0RHEJR5eZYivX9krRdWH5/8YUwAFnZ09HH\r\n" +"IajVxZMBRSuUcHmFrGFbQcNCEsERx1DnWzb6j2iNo55s6kYWbvuF2vdAdZEJPWWk\r\n" +"NKRn+OJYQR1t0micL+RRS0rvktc49AOa25xqHIDK9wV6kXlJA36mRa2x9/ijB2c8\r\n" +"ZSn5vKhWRZOYQAQpB9kG5H2cK4xx48EOCNDnQ74RSVsP/xq8yJx6NOHDFkXhOq4M\r\n" +"7daCtrY57GjyUgIEhhGi7DIAjfLqrwdihLWvUip1gS32lc9Qy806r+yQYHFzqImI\r\n" +"GACoP9i5MfZDq5TUbwx4Z9yDQ0Djraa9GCU+GHmaZc84hiXwh2PsPCswG3mme87G\r\n" +"OydzdjYF/KKO9P33AgMBAAGjPzA9MAwGA1UdEwQFMAMBAf8wLQYDVR0fBCYwJDAi\r\n" +"oCCgHoYcaHR0cHM6Ly9jYS5zZWNvbmQuY24vY3JsLnBlbTANBgkqhkiG9w0BAQsF\r\n" +"AAOCAgEASJmN9D3Nf5YHOSa28gZLKhGziwNG9ykRXK59vLNIeYYDuoR51m+zkqtm\r\n" +"I5SuYDb+IfjicJCyMnrMlP/d/Lv/YUi/rEF/BS0YF2YlnX+5JmG8RG1Sh2OSfp28\r\n" +"rmh5srMg76EuDXIPN1+qHeQqpbNj11DzKL3Z2Tv+ohj2+/WauJt2KTdRWbRU7AT7\r\n" +"xRlgFOofQUFUo78JG+Op1yfQnbDqJNBB04ASwEi4ru9yliBgS6Ves/zn5xAjwe98\r\n" +"1tGuGFhEYXEKzP3cPGShefdFgyI53YrsVxXy4+x5OdfyRiq9+ao/jAAezZc6fcBe\r\n" +"V6gADyhpt9vSDinTcI3xBRqwLIa+ujTd/HEqSu9Di8xYJ+RbKJ0wFRK1VJqMZXKu\r\n" +"HIo7mgfBUwojxFbIk+FSXWWvWBtaOQxy4BZxv5NjAFlYU2k3p0rJOhQ3CCpTd6Sf\r\n" +"HVd68XS0xK+RLCYxbTK0ejZ8gGN3DHpdtCWRcVXOo47mR3eCgIWAdkWeRO+xs2LV\r\n" +"5afFCeGtpITsNUkqh9YVTvMxLEBwSmNH4SHVzJN5Xj6hgfLg2ZhbI7r1DC8CaTr7\r\n" +"H56qZfZmrvZbBc1q9yIhqJNPwwOZ0N0QJnZObBE1E8PX7if3lPlOoGIlbYcyEyu4\r\n" +"neNdebXmjLY6R8J9/eLy36xX7vRdjDBT1gva9AIthH0dg0tpPJI=\r\n" +"-----END CERTIFICATE-----\r\n"; + +static char g_testInvalidCert[] = +"-----xxxx CERTIFICATE-----\r\n" +"MIIDpzCCAo+gAwIBAgICAQAwDQYJKoZIhvcNAQELBQAwbDELMAkGA1UEBhMCQ04x\r\n" +"CzAJBgNVBAgMAkJKMQswCQYDVQQHDAJCSjELMAkGA1UECgwCSEQxDDAKBgNVBAsM\r\n" +"A2RldjELMAkGA1UEAwwCY2ExGzAZBgkqhkiG9w0BCQEWDGNhQHdvcmxkLmNvbTAe\r\n" +"Fw0yMjA4MTkwNTE2MTVaFw0yMzA4MTkwNTE2MTVaMGwxCzAJBgNVBAYTAkNOMQsw\r\n" +"CQYDVQQIDAJCSjELMAkGA1UEBwwCQkoxCzAJBgNVBAoMAkhEMQwwCgYDVQQLDANk\r\n" +"ZXYxCzAJBgNVBAMMAmNhMRswGQYJKoZIhvcNAQkBFgxjYUB3b3JsZC5jb20wggEi\r\n" +"MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCuvLoVT5em7ApBma8xtgpcFcaU\r\n" +"CbXBJSUl2NpFW2sriucbEOvKRdw9KvLa/tSP6CupPZVKIzHAP2oeW88aFBr23miG\r\n" +"iR49M52c73Iw3H3EG2ckK8M1mxEzXSqynivqiNZDKG+bA5cFzcfmk6Th1bJan9w9\r\n" +"Ci8HPSBvgg7Rc6pqNM4HjTHl3Bb6cf4Xh3/GgpjypTd9jAAEyq+l/+1pnTYVlIJA\r\n" +"WGh0Z26RosXfzwfFKH77ysTjoj9ambvGmFsMXvNXEyYmBCeYND6xGj4pa2lylsra\r\n" +"kfYmGxcFQ45Lj5oWdNQQVdvrQiYWu3SJOC/WqB5UIAq92PPrq1apznxfjqABAgMB\r\n" +"AAGjUzBRMB0GA1UdDgQWBBRI5iWwjBMAOCcgcUjUCYJdsvwEMjAfBgNVHSMEGDAW\r\n" +"gBRI5iWwjBMAOCcgcUjUCYJdsvwEMjAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3\r\n" +"DQEBCwUAA4IBAQABop7EJgS2czHKWVzdEwjbi9m5ZUPy6aOV9paV1e/5IyFNHwun\r\n" +"B64iwcg03+FmIWNuynb1mglHHrUoXygXu9GIR8cWfOI3W+Pnn8fDi8MxQMn/e/Jj\r\n" +"BuGcnRwKynRhyLdkyWYn1YwqenMuFJu9yzkhfAPltGFEuPYCWDatdhm6zhFdu1PE\r\n" +"EMErHpQOT45z5cgC4XqgKlE+n8L4/5RfZnbuUJ3bV+FuI+VApLGXJQlJQAOTqBDg\r\n" +"k7DMSgPUUxYYa6AGMFy6vqQ6hcgCMK08ko8LdjVd1MobKzM9Oh480GFZA/ubR3QW\r\n" +"lv3OuOhmnIxNGcPUiqpSiWKqR5tf1KUImIR9\r\n" +"-----END CERTIFICATE-----\r\n"; + +/* g_testSelfSignedCaCert +Certificate: + Data: + Version: 3 (0x2) + Serial Number: 272 (0x110) + Signature Algorithm: sha256WithRSAEncryption + Issuer: C = CN, ST = BJ, L = BJ, O = HD, OU = dev, CN = ca, emailAddress = ca@cryptoframework.com + Validity + Not Before: Aug 19 12:49:06 2022 GMT + Not After : Aug 16 12:49:06 2032 GMT + Subject: C = CN, ST = BJ, L = BJ, O = HD, OU = dev, CN = ca, emailAddress = ca@cryptoframework.com + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + RSA Public-Key: (2048 bit) + Modulus: + 00:9f:29:d0:85:84:ed:6c:30:6e:d0:13:83:e0:1b: + 61:08:f7:dd:63:41:06:4b:54:fb:f0:15:7f:e4:e5: + d5:a0:1a:e1:33:9e:5b:6f:d9:01:17:38:b1:dc:0b: + 55:3c:5d:5c:28:a9:16:c7:ae:88:63:77:d2:1c:17: + ad:71:54:1e:b7:0c:7f:4c:36:b0:29:33:9c:95:59: + fe:b4:1c:7c:43:b9:29:bd:6f:07:3e:83:10:47:20: + 21:26:04:86:1a:8e:05:f6:01:8a:de:6a:7e:9a:b9: + 47:6f:b6:47:f4:e1:ff:26:d5:fa:40:6b:52:5f:86: + b2:c5:db:0c:07:ba:a1:90:b2:e7:a9:46:a6:10:ef: + 98:73:14:3b:b6:b5:de:3f:92:16:64:e1:31:b2:36: + c9:ec:ae:6b:52:da:81:2a:1a:04:97:d8:d4:9f:a2: + ee:35:8f:9a:61:05:47:47:50:da:9d:04:1a:31:d3: + 81:01:a1:46:8e:55:bb:00:c7:8a:93:52:bf:45:cf: + f0:e5:00:fc:f6:1b:2f:f4:81:8f:51:6a:e0:2d:e0: + b5:fb:e3:7a:cc:14:6f:35:5a:32:8a:bf:c0:2b:b2: + d6:a7:17:23:cd:19:2d:ed:f0:85:1d:b8:73:47:17: + 60:53:b4:b8:68:bd:7a:03:e9:db:87:f0:ef:26:06: + aa:01 + Exponent: 65537 (0x10001) + X509v3 extensions: + X509v3 Subject Key Identifier: + 8C:A3:3B:42:63:01:B3:4D:51:F6:E4:2D:B5:83:7F:18:39:2F:B7:B5 + X509v3 Authority Key Identifier: + keyid:8C:A3:3B:42:63:01:B3:4D:51:F6:E4:2D:B5:83:7F:18:39:2F:B7:B5 + + X509v3 Basic Constraints: critical + CA:TRUE, pathlen:2 + X509v3 Key Usage: + Certificate Sign, CRL Sign + X509v3 Extended Key Usage: + TLS Web Server Authentication, TLS Web Client Authentication + X509v3 Subject Alternative Name: + email:ca@cryptoframework.com + X509v3 Issuer Alternative Name: + email:ca@cryptoframework.com + Signature Algorithm: sha256WithRSAEncryption + 87:ee:11:13:a7:09:eb:6f:e0:2d:8b:2c:2e:47:3b:11:28:3b: + 7b:12:b0:66:59:a2:b0:7c:81:89:cb:b2:ff:e5:da:80:e6:77: + 71:36:e0:40:d5:e5:42:86:4a:6f:0f:e4:b3:f0:7f:70:89:db: + 40:66:1b:a4:09:b8:ed:2b:9d:a3:e2:3f:1b:dc:63:d1:7e:e0: + 40:1f:70:b5:2a:db:4a:d3:ac:e9:28:e7:2e:26:14:d3:11:5c: + 16:c7:34:8f:a9:36:4a:b9:72:8b:04:50:72:34:b8:3c:e2:a2: + 51:2d:02:9b:71:77:0c:71:9d:8f:9e:4f:94:19:17:c6:e7:57: + 0a:ad:95:dc:9d:d5:c0:a7:f6:6d:58:d0:6f:3c:f6:f8:cf:d0: + d6:6f:8f:ec:58:41:f8:99:9e:3b:c7:9e:9a:4a:8c:43:4b:45: + 31:4d:c4:33:8e:35:36:97:a3:0b:98:85:54:01:a0:a3:09:c2: + f1:2d:01:f9:fc:47:f5:d0:49:b8:73:3a:be:9c:44:5b:0d:dc: + 91:91:43:65:0d:64:77:dd:58:46:0a:fb:8d:8f:1f:73:4b:ff: + 4f:4b:73:1d:66:ce:11:5c:e4:94:42:01:58:bd:66:a2:6a:4b: + 04:2c:1e:d3:f1:b0:f8:13:ba:d1:b7:e2:d8:ca:09:c3:cb:76: + 21:c0:75:43 +*/ +static char g_testSelfSignedCaCert[] = +"-----BEGIN CERTIFICATE-----\r\n" +"MIIEMjCCAxqgAwIBAgICARAwDQYJKoZIhvcNAQELBQAwdjELMAkGA1UEBhMCQ04x\r\n" +"CzAJBgNVBAgMAkJKMQswCQYDVQQHDAJCSjELMAkGA1UECgwCSEQxDDAKBgNVBAsM\r\n" +"A2RldjELMAkGA1UEAwwCY2ExJTAjBgkqhkiG9w0BCQEWFmNhQGNyeXB0b2ZyYW1l\r\n" +"d29yay5jb20wHhcNMjIwODE5MTI0OTA2WhcNMzIwODE2MTI0OTA2WjB2MQswCQYD\r\n" +"VQQGEwJDTjELMAkGA1UECAwCQkoxCzAJBgNVBAcMAkJKMQswCQYDVQQKDAJIRDEM\r\n" +"MAoGA1UECwwDZGV2MQswCQYDVQQDDAJjYTElMCMGCSqGSIb3DQEJARYWY2FAY3J5\r\n" +"cHRvZnJhbWV3b3JrLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB\r\n" +"AJ8p0IWE7WwwbtATg+AbYQj33WNBBktU+/AVf+Tl1aAa4TOeW2/ZARc4sdwLVTxd\r\n" +"XCipFseuiGN30hwXrXFUHrcMf0w2sCkznJVZ/rQcfEO5Kb1vBz6DEEcgISYEhhqO\r\n" +"BfYBit5qfpq5R2+2R/Th/ybV+kBrUl+GssXbDAe6oZCy56lGphDvmHMUO7a13j+S\r\n" +"FmThMbI2yeyua1LagSoaBJfY1J+i7jWPmmEFR0dQ2p0EGjHTgQGhRo5VuwDHipNS\r\n" +"v0XP8OUA/PYbL/SBj1Fq4C3gtfvjeswUbzVaMoq/wCuy1qcXI80ZLe3whR24c0cX\r\n" +"YFO0uGi9egPp24fw7yYGqgECAwEAAaOByTCBxjAdBgNVHQ4EFgQUjKM7QmMBs01R\r\n" +"9uQttYN/GDkvt7UwHwYDVR0jBBgwFoAUjKM7QmMBs01R9uQttYN/GDkvt7UwEgYD\r\n" +"VR0TAQH/BAgwBgEB/wIBAjALBgNVHQ8EBAMCAQYwHQYDVR0lBBYwFAYIKwYBBQUH\r\n" +"AwEGCCsGAQUFBwMCMCEGA1UdEQQaMBiBFmNhQGNyeXB0b2ZyYW1ld29yay5jb20w\r\n" +"IQYDVR0SBBowGIEWY2FAY3J5cHRvZnJhbWV3b3JrLmNvbTANBgkqhkiG9w0BAQsF\r\n" +"AAOCAQEAh+4RE6cJ62/gLYssLkc7ESg7exKwZlmisHyBicuy/+XagOZ3cTbgQNXl\r\n" +"QoZKbw/ks/B/cInbQGYbpAm47Sudo+I/G9xj0X7gQB9wtSrbStOs6SjnLiYU0xFc\r\n" +"Fsc0j6k2SrlyiwRQcjS4POKiUS0Cm3F3DHGdj55PlBkXxudXCq2V3J3VwKf2bVjQ\r\n" +"bzz2+M/Q1m+P7FhB+JmeO8eemkqMQ0tFMU3EM441NpejC5iFVAGgownC8S0B+fxH\r\n" +"9dBJuHM6vpxEWw3ckZFDZQ1kd91YRgr7jY8fc0v/T0tzHWbOEVzklEIBWL1mompL\r\n" +"BCwe0/Gw+BO60bfi2MoJw8t2IcB1Qw==\r\n" +"-----END CERTIFICATE-----\r\n"; + +constexpr int TEST_CERT_VERSION = 3; +constexpr int TEST_CERT_CHAIN_LEN = 2; +constexpr int TEST_CERT_SERIAL_NUMBER = 272; + +void X509CertTest::SetUpTestCase() {} +void X509CertTest::TearDownTestCase() {} + +void X509CertTest::SetUp() +{ +} + +void X509CertTest::TearDown() +{ +} + +/* Valid PEM format. */ +HWTEST_F(X509CertTest, GenerateCert001, TestSize.Level0) +{ + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_testSelfSignedCaCert; + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testSelfSignedCaCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + OH_HCF_ObjDestroy(x509Cert); +} + +/* Invalid input. */ +HWTEST_F(X509CertTest, GenerateCert002, TestSize.Level0) +{ + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_NE(ret, HCF_SUCCESS); + EXPECT_EQ(x509Cert, nullptr); + OH_HCF_ObjDestroy(x509Cert); +} + +/* Invalid PEM format. */ +HWTEST_F(X509CertTest, GenerateCert003, TestSize.Level0) +{ + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_testInvalidCert; + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testInvalidCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_NE(ret, HCF_SUCCESS); + EXPECT_EQ(x509Cert, nullptr); + OH_HCF_ObjDestroy(x509Cert); +} + +/* Valid DER format. */ +HWTEST_F(X509CertTest, GenerateCert004, TestSize.Level0) +{ + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_testSelfSignedCaCert; + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testSelfSignedCaCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + HcfEncodingBlob derBlob = { 0 }; + ret = x509Cert->base.getEncoded((HcfCertificate *)x509Cert, &derBlob); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(derBlob.data, nullptr); + EXPECT_EQ(derBlob.encodingFormat, HCF_FORMAT_DER); + HcfX509Certificate *certFromDerData = nullptr; + ret = HcfX509CertificateCreate(&derBlob, &certFromDerData); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(certFromDerData, nullptr); + + free(derBlob.data); + OH_HCF_ObjDestroy(certFromDerData); + OH_HCF_ObjDestroy(x509Cert); +} + +/* verify self signed cert. */ +HWTEST_F(X509CertTest, Verify001, TestSize.Level0) +{ + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_testSelfSignedCaCert; + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testSelfSignedCaCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + HcfPubKey *keyOut = nullptr; + ret = x509Cert->base.getPublicKey((HcfCertificate *)x509Cert, &keyOut); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(keyOut, nullptr); + ret = x509Cert->base.verify((HcfCertificate *)x509Cert, keyOut); + EXPECT_EQ(ret, HCF_SUCCESS); + OH_HCF_ObjDestroy(keyOut); + OH_HCF_ObjDestroy(x509Cert); +} + +/* use root ca cert's public key to verify next cert. */ +HWTEST_F(X509CertTest, Verify002, TestSize.Level0) +{ + HcfX509Certificate *rootCert = nullptr; + HcfEncodingBlob root = { 0 }; + root.data = (uint8_t *)g_rootCert; + root.encodingFormat = HCF_FORMAT_PEM; + root.len = strlen(g_rootCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&root, &rootCert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(rootCert, nullptr); + HcfPubKey *rootkeyOut = nullptr; + ret = rootCert->base.getPublicKey((HcfCertificate *)rootCert, &rootkeyOut); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(rootkeyOut, nullptr); + + HcfX509Certificate *secondCert = nullptr; + HcfEncodingBlob second = { 0 }; + second.data = (uint8_t *)g_secondCert; + second.encodingFormat = HCF_FORMAT_PEM; + second.len = strlen(g_secondCert) + 1; + ret = HcfX509CertificateCreate(&root, &secondCert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(rootCert, nullptr); + ret = secondCert->base.verify((HcfCertificate *)secondCert, rootkeyOut); + EXPECT_EQ(ret, HCF_SUCCESS); + OH_HCF_ObjDestroy(rootkeyOut); + OH_HCF_ObjDestroy(rootCert); + OH_HCF_ObjDestroy(secondCert); +} + +/* verify cert with wrong pub key. */ +HWTEST_F(X509CertTest, Verify003, TestSize.Level0) +{ + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_testSelfSignedCaCert; + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testSelfSignedCaCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + + HcfX509Certificate *rootCert = nullptr; + HcfEncodingBlob root = { 0 }; + root.data = (uint8_t *)g_rootCert; + root.encodingFormat = HCF_FORMAT_PEM; + root.len = strlen(g_rootCert) + 1; + ret = HcfX509CertificateCreate(&root, &rootCert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(rootCert, nullptr); + HcfPubKey *rootkeyOut = nullptr; + ret = rootCert->base.getPublicKey((HcfCertificate *)rootCert, &rootkeyOut); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(rootkeyOut, nullptr); + + ret = x509Cert->base.verify((HcfCertificate *)x509Cert, rootkeyOut); + EXPECT_NE(ret, HCF_SUCCESS); + OH_HCF_ObjDestroy(rootkeyOut); + OH_HCF_ObjDestroy(rootCert); + OH_HCF_ObjDestroy(x509Cert); +} + +/* verify cert with invalid input pub key. */ +HWTEST_F(X509CertTest, Verify004, TestSize.Level0) +{ + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_testSelfSignedCaCert; + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testSelfSignedCaCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + HcfPubKey *keyOut = nullptr; + ret = x509Cert->base.verify((HcfCertificate *)x509Cert, keyOut); + EXPECT_NE(ret, HCF_SUCCESS); + OH_HCF_ObjDestroy(x509Cert); +} + +HWTEST_F(X509CertTest, GetEncoded001, TestSize.Level0) +{ + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + HcfEncodingBlob encodingBlob = { 0 }; + inStream.data = (uint8_t *)g_testSelfSignedCaCert; + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testSelfSignedCaCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + + ret = x509Cert->base.getEncoded((HcfCertificate *)x509Cert, &encodingBlob); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(encodingBlob.data, nullptr); + EXPECT_EQ(encodingBlob.encodingFormat, HCF_FORMAT_DER); + free(encodingBlob.data); + OH_HCF_ObjDestroy(x509Cert); +} + +/* Invalid input. */ +HWTEST_F(X509CertTest, GetEncoded002, TestSize.Level0) +{ + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_testSelfSignedCaCert; + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testSelfSignedCaCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + + ret = x509Cert->base.getEncoded((HcfCertificate *)x509Cert, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); + OH_HCF_ObjDestroy(x509Cert); +} + +HWTEST_F(X509CertTest, GetPublicKey, TestSize.Level0) +{ + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + HcfPubKey *keyOut = nullptr; + inStream.data = (uint8_t *)g_testSelfSignedCaCert; + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testSelfSignedCaCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + + ret = x509Cert->base.getPublicKey((HcfCertificate *)x509Cert, &keyOut); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(keyOut, nullptr); + OH_HCF_ObjDestroy(keyOut); + OH_HCF_ObjDestroy(x509Cert); +} + +/* Input valid date. YYMMDDHHMMSSZ */ +HWTEST_F(X509CertTest, CheckValidityWithDate001, TestSize.Level0) +{ + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_testSelfSignedCaCert; // validatetime :2022/08/19 - 2032/08/16 + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testSelfSignedCaCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + const char *date = "231018162433Z"; + ret = x509Cert->checkValidityWithDate(x509Cert, date); + EXPECT_EQ(ret, HCF_SUCCESS); + OH_HCF_ObjDestroy(x509Cert); +} + +/* Input valid date. time format: YYYYMMDDHHMMSSZ */ +HWTEST_F(X509CertTest, CheckValidityWithDate002, TestSize.Level0) +{ + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_testSelfSignedCaCert; // validatetime :2022/08/19 - 2032/08/16 + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testSelfSignedCaCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + const char *date = "20231018162433Z"; + ret = x509Cert->checkValidityWithDate(x509Cert, date); + EXPECT_EQ(ret, HCF_SUCCESS); + OH_HCF_ObjDestroy(x509Cert); +} + +/* Input invalid date--expiered. */ +HWTEST_F(X509CertTest, CheckValidityWithDate003, TestSize.Level0) +{ + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_testSelfSignedCaCert; // validatetime :2022/08/19 - 2032/08/16 + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testSelfSignedCaCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + const char *date = "20991018162433Z"; + ret = x509Cert->checkValidityWithDate(x509Cert, date); + EXPECT_EQ(ret, HCF_ERR_CERT_HAS_EXPIRED); + OH_HCF_ObjDestroy(x509Cert); +} + +/* Input invalid date. */ +HWTEST_F(X509CertTest, CheckValidityWithDate004, TestSize.Level0) +{ + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_testSelfSignedCaCert; // validatetime :2022/08/19 - 2032/08/16 + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testSelfSignedCaCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + const char *date = "20191018162433Z"; + ret = x509Cert->checkValidityWithDate(x509Cert, date); + EXPECT_EQ(ret, HCF_ERR_CERT_NOT_YET_VALID); + OH_HCF_ObjDestroy(x509Cert); +} + +/* Input invalid date form. */ +HWTEST_F(X509CertTest, CheckValidityWithDate005, TestSize.Level0) +{ + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_testSelfSignedCaCert; // validatetime :2022/08/19 - 2032/08/16 + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testSelfSignedCaCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + const char *date = "20191018"; + ret = x509Cert->checkValidityWithDate(x509Cert, date); + EXPECT_NE(ret, HCF_SUCCESS); + OH_HCF_ObjDestroy(x509Cert); +} + +HWTEST_F(X509CertTest, GetVersion, TestSize.Level0) +{ + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_testSelfSignedCaCert; + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testSelfSignedCaCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + long ver = x509Cert->getVersion(x509Cert); + EXPECT_EQ(ver, TEST_CERT_VERSION); + OH_HCF_ObjDestroy(x509Cert); +} + +HWTEST_F(X509CertTest, GetSerialNumber, TestSize.Level0) +{ + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_testSelfSignedCaCert; + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testSelfSignedCaCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + long serialNumber = x509Cert->getSerialNumber(x509Cert); + EXPECT_EQ(serialNumber, TEST_CERT_SERIAL_NUMBER); + OH_HCF_ObjDestroy(x509Cert); +} + +HWTEST_F(X509CertTest, GetIssuerName001, TestSize.Level0) +{ + HcfBlob out = { 0 }; + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_testSelfSignedCaCert; + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testSelfSignedCaCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + ret = x509Cert->getIssuerName(x509Cert, &out); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(out.data, nullptr); + printf("the IssuerDN = %s.\n", out.data); + HcfBlobDataClearAndFree(&out); + OH_HCF_ObjDestroy(x509Cert); +} + +/* invalid input. */ +HWTEST_F(X509CertTest, GetIssuerName002, TestSize.Level0) +{ + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_testSelfSignedCaCert; + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testSelfSignedCaCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + ret = x509Cert->getIssuerName(x509Cert, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); + OH_HCF_ObjDestroy(x509Cert); +} + +HWTEST_F(X509CertTest, GetSubjectName001, TestSize.Level0) +{ + HcfBlob out = { 0 }; + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_testSelfSignedCaCert; + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testSelfSignedCaCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + ret = x509Cert->getSubjectName(x509Cert, &out); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(out.data, nullptr); + printf("the SubjectDN = %s.\n", out.data); + HcfBlobDataClearAndFree(&out); + OH_HCF_ObjDestroy(x509Cert); +} + +/* invalid input. */ +HWTEST_F(X509CertTest, GetSubjectName002, TestSize.Level0) +{ + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_testSelfSignedCaCert; + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testSelfSignedCaCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + ret = x509Cert->getSubjectName(x509Cert, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); + OH_HCF_ObjDestroy(x509Cert); +} + +HWTEST_F(X509CertTest, GetNotBeforeTime001, TestSize.Level0) +{ + HcfBlob out = { 0 }; + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_testSelfSignedCaCert; // validatetime :2022/08/19 - 2032/08/16 + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testSelfSignedCaCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + ret = x509Cert->getNotBeforeTime(x509Cert, &out); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(out.data, nullptr); + HcfBlobDataClearAndFree(&out); + OH_HCF_ObjDestroy(x509Cert); +} + +/* invalid input. */ +HWTEST_F(X509CertTest, GetNotBeforeTime002, TestSize.Level0) +{ + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_testSelfSignedCaCert; + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testSelfSignedCaCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + ret = x509Cert->getNotBeforeTime(x509Cert, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); + OH_HCF_ObjDestroy(x509Cert); +} + +HWTEST_F(X509CertTest, GetNotAfterTime001, TestSize.Level0) +{ + HcfBlob out = { 0 }; + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_testSelfSignedCaCert; // validatetime :2022/08/19 - 2032/08/16 + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testSelfSignedCaCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + ret = x509Cert->getNotAfterTime(x509Cert, &out); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(out.data, nullptr); + HcfBlobDataClearAndFree(&out); + OH_HCF_ObjDestroy(x509Cert); +} + +/* invalid input. */ +HWTEST_F(X509CertTest, GetNotAfterTime002, TestSize.Level0) +{ + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_testSelfSignedCaCert; + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testSelfSignedCaCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + ret = x509Cert->getNotAfterTime(x509Cert, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); + OH_HCF_ObjDestroy(x509Cert); +} + +HWTEST_F(X509CertTest, GetSignature001, TestSize.Level0) +{ + HcfBlob sigOut = { 0 }; + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_testSelfSignedCaCert; + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testSelfSignedCaCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + ret = x509Cert->getSignature(x509Cert, &sigOut); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(sigOut.data, nullptr); + HcfBlobDataClearAndFree(&sigOut); + OH_HCF_ObjDestroy(x509Cert); +} + +/* invalid input. */ +HWTEST_F(X509CertTest, GetSignature002, TestSize.Level0) +{ + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_testSelfSignedCaCert; + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testSelfSignedCaCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + ret = x509Cert->getSignature(x509Cert, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); + OH_HCF_ObjDestroy(x509Cert); +} + +HWTEST_F(X509CertTest, GetSignatureAlgName001, TestSize.Level0) +{ + HcfBlob sigAlgName = { 0 }; + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_testSelfSignedCaCert; + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testSelfSignedCaCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + ret = x509Cert->getSignatureAlgName(x509Cert, &sigAlgName); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(sigAlgName.data, nullptr); + HcfBlobDataClearAndFree(&sigAlgName); + OH_HCF_ObjDestroy(x509Cert); +} + +/* invalid input. */ +HWTEST_F(X509CertTest, GetSignatureAlgName002, TestSize.Level0) +{ + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_testSelfSignedCaCert; + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testSelfSignedCaCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + ret = x509Cert->getSignatureAlgName(x509Cert, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); + OH_HCF_ObjDestroy(x509Cert); +} + +HWTEST_F(X509CertTest, GetSignatureAlgOid001, TestSize.Level0) +{ + HcfBlob sigAlgOID = { 0 }; + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_testSelfSignedCaCert; + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testSelfSignedCaCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + ret = x509Cert->getSignatureAlgOid(x509Cert, &sigAlgOID); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(sigAlgOID.data, nullptr); + HcfBlobDataClearAndFree(&sigAlgOID); + OH_HCF_ObjDestroy(x509Cert); +} + +/* invalid input. */ +HWTEST_F(X509CertTest, GetSignatureAlgOid002, TestSize.Level0) +{ + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_testSelfSignedCaCert; + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testSelfSignedCaCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + ret = x509Cert->getSignatureAlgOid(x509Cert, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); + OH_HCF_ObjDestroy(x509Cert); +} + +HWTEST_F(X509CertTest, GetSignatureAlgParams001, TestSize.Level0) +{ + HcfBlob sigAlgParamsOut = { 0 }; + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_testSelfSignedCaCert; + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testSelfSignedCaCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + ret = x509Cert->getSignatureAlgParams(x509Cert, &sigAlgParamsOut); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(sigAlgParamsOut.data, nullptr); + HcfBlobDataClearAndFree(&sigAlgParamsOut); + OH_HCF_ObjDestroy(x509Cert); +} + +/* invalid input. */ +HWTEST_F(X509CertTest, GetSignatureAlgParams002, TestSize.Level0) +{ + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_testSelfSignedCaCert; + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testSelfSignedCaCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + ret = x509Cert->getSignatureAlgParams(x509Cert, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); + OH_HCF_ObjDestroy(x509Cert); +} + +HWTEST_F(X509CertTest, GetKeyUsage, TestSize.Level0) +{ + HcfBlob out = { 0 }; + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_testSelfSignedCaCert; + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testSelfSignedCaCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + ret = x509Cert->getKeyUsage(x509Cert, &out); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(out.data, nullptr); + HcfBlobDataClearAndFree(&out); + OH_HCF_ObjDestroy(x509Cert); +} + +HWTEST_F(X509CertTest, GetExtKeyUsage001, TestSize.Level0) +{ + HcfArray keyUsageOut = { 0 }; + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_testSelfSignedCaCert; + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testSelfSignedCaCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + ret = x509Cert->getExtKeyUsage(x509Cert, &keyUsageOut); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(keyUsageOut.data, nullptr); + HcfArrayDataClearAndFree(&keyUsageOut); + OH_HCF_ObjDestroy(x509Cert); +} + +/* Cert which has no extended key usage. */ +HWTEST_F(X509CertTest, GetExtKeyUsage002, TestSize.Level0) +{ + HcfArray keyUsageOut = { 0 }; + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_secondCert; + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_secondCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + ret = x509Cert->getExtKeyUsage(x509Cert, &keyUsageOut); + EXPECT_EQ(ret, HCF_ERR_CRYPTO_OPERATION); + EXPECT_EQ(keyUsageOut.data, nullptr); + OH_HCF_ObjDestroy(x509Cert); +} + +/* not a CA cert */ +HWTEST_F(X509CertTest, GetBasicConstraints001, TestSize.Level0) +{ + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_deviceTestCert; + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_deviceTestCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + int32_t pathLen = x509Cert->getBasicConstraints(x509Cert); + EXPECT_EQ(pathLen, -1); /* cert path len is only valid for CA. */ + OH_HCF_ObjDestroy(x509Cert); +} + +/* CA cert */ +HWTEST_F(X509CertTest, GetBasicConstraints002, TestSize.Level0) +{ + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_testSelfSignedCaCert; + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testSelfSignedCaCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + int32_t pathLen = x509Cert->getBasicConstraints(x509Cert); + EXPECT_EQ(pathLen, TEST_CERT_CHAIN_LEN); /* g_testSelfSignedCaCert is CA and it's path len is 2. */ + OH_HCF_ObjDestroy(x509Cert); +} + +HWTEST_F(X509CertTest, GetSubjectAltNames001, TestSize.Level0) +{ + HcfArray outName = { 0 }; + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_testSelfSignedCaCert; + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testSelfSignedCaCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + ret = x509Cert->getSubjectAltNames(x509Cert, &outName); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(outName.data, nullptr); + HcfArrayDataClearAndFree(&outName); + OH_HCF_ObjDestroy(x509Cert); +} + +/* cert without subject alternative names. */ +HWTEST_F(X509CertTest, GetSubjectAltNames002, TestSize.Level0) +{ + HcfArray outName = { 0 }; + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_secondCert; + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_secondCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + ret = x509Cert->getSubjectAltNames(x509Cert, &outName); + EXPECT_EQ(ret, HCF_ERR_CRYPTO_OPERATION); + EXPECT_EQ(outName.data, nullptr); + OH_HCF_ObjDestroy(x509Cert); +} + +/* invalid input. */ +HWTEST_F(X509CertTest, GetSubjectAltNames003, TestSize.Level0) +{ + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_secondCert; + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_secondCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + ret = x509Cert->getSubjectAltNames(x509Cert, nullptr); + EXPECT_EQ(ret, HCF_INVALID_PARAMS); + OH_HCF_ObjDestroy(x509Cert); +} + +HWTEST_F(X509CertTest, GetIssuerAltNames001, TestSize.Level0) +{ + HcfArray outName = { 0 }; + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_testSelfSignedCaCert; + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_testSelfSignedCaCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + ret = x509Cert->getIssuerAltNames(x509Cert, &outName); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(outName.data, nullptr); + HcfArrayDataClearAndFree(&outName); + OH_HCF_ObjDestroy(x509Cert); +} + +/* cert without issuer alternative names. */ +HWTEST_F(X509CertTest, GetIssuerAltNames002, TestSize.Level0) +{ + HcfArray outName = { 0 }; + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_secondCert; + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_secondCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + ret = x509Cert->getIssuerAltNames(x509Cert, &outName); + EXPECT_EQ(ret, HCF_ERR_CRYPTO_OPERATION); + EXPECT_EQ(outName.data, nullptr); + OH_HCF_ObjDestroy(x509Cert); +} + +/* invalid input. */ +HWTEST_F(X509CertTest, GetIssuerAltNames003, TestSize.Level0) +{ + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStream = { 0 }; + inStream.data = (uint8_t *)g_secondCert; + inStream.encodingFormat = HCF_FORMAT_PEM; + inStream.len = strlen(g_secondCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStream, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + ret = x509Cert->getIssuerAltNames(x509Cert, nullptr); + EXPECT_EQ(ret, HCF_INVALID_PARAMS); + OH_HCF_ObjDestroy(x509Cert); +} \ No newline at end of file diff --git a/test/unittest/src/crypto_x509_crl_test.cpp b/test/unittest/src/crypto_x509_crl_test.cpp new file mode 100644 index 0000000..e56d680 --- /dev/null +++ b/test/unittest/src/crypto_x509_crl_test.cpp @@ -0,0 +1,1374 @@ +/* + * Copyright (C) 2022 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 "securec.h" + +#include +#include + +#include "asy_key_generator.h" +#include "cipher.h" +#include "key_pair.h" +#include "memory.h" +#include "openssl_class.h" +#include "x509_crl.h" +#include "x509_crl_openssl.h" + +using namespace std; +using namespace testing::ext; + +#define TEST_VERSION 3 +#define TEST_EXT_VERSION 4 +#define TEST_OFFSET_TIME 1000 +#define TEST_SN 1000 +#define TEST_TIME 1986598400 +#define TEST_OFFSET 10 +#define TEST_CRL_LEN 256 + +static char g_testErrorCert[] = +"-----BEGIN CERTIFICATE-----\r\n" +"MIIEQDCCAyigAwIBAgIQICAIMRlDU0ytSEUfNeOUJTANBgkqhkiG9w0BAQsFADBcMQswCQYDVQQG\r\n" +"EwJDTjEPMA0GA1UECgwGSHVhd2VpMRMwEQYDVQQLDApIdWF3ZWkgQ0JHMScwJQYDVQQDDB5IdWF3\r\n" +"ZWkgQ0JHIE1vYmlsZSBFcXVpcG1lbnQgQ0EwHhcNMjAwODMxMTE0MzUzWhcNMzAwODI5MTE0MzUz\r\n" +"WjBvMQswCQYDVQQGEwJDTjEPMA0GA1UECgwGSHVhd2VpMRMwEQYDVQQLDApIdWF3ZWkgQ0JHMTow\r\n" +"OAYDVQQDDDFIVUFXRUlfSFdKQURfODE4ZjhjNDUtOGNmNC00ZTM2LTkxOTMtNTQ5OWMwNzM0YzM4\r\n" +"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArZcfL6ot4z6k3T4X3C26EI557Zvrx9Ci\r\n" +"hNx6RMy+vjXa3E4BkxwZ3r0ADbc+msJOq0IyQJNujaLq35oQvJgMIvBn1xFurBXdOzbygc7G9GKt\r\n" +"sb4rmKUP0QEPHM2/TrxAJT2LNPLrOE047ESe2X76FpDY6oZdsoGJ5I9m/mlfGsxR1l1TeUjwA/Rs\r\n" +"UtISR66aastBy2tU7IubP0B0Gceqy9DnjTQtY9OpkOql08H20C30iCVijK6BmP43X4OMz2MS0leV\r\n" +"K0AHmhiv6ufu166Xtc2JOXRk/MJ+53iprvVEUowKY/ZATUz6iDHDZYM3MdQV+VbFrOevUceOSweY\r\n" +"PaXCzwIDAQABo4HqMIHnMB8GA1UdIwQYMBaAFDXT2UhPcFFNI7Ey1dXdJSHOBS7dMB0GA1UdDgQW\r\n" +"BBSndBqCYYcTB1kMNhYMM4r/vDLteTARBglghkgBhvhCAQEEBAMCBsAwCwYDVR0PBAQDAgTwMGYG\r\n" +"A1UdHwRfMF0wW6BZoFeGVWh0dHA6Ly9jcGtpLWNhd2ViLmh1YXdlaS5jb20vY3BraS9zZXJ2bGV0\r\n" +"L2NybEZpbGVEb3duLmNybD9jZXJ0eXBlPTQmeWVhcj0vY3JsMjAyMC5jcmwwHQYDVR0lBBYwFAYI\r\n" +"KwYBBQUHAwEGCCsGAQUFBwMCMA0GCSqGSIb3DQEBCwUAA4IBAQCNTqZHRy7BJ+KFOflqwYkeD1Yd\r\n" +"K5XxcZUykw8AefX3SMYzSBzy7IIIhM5bvhWF6r5NnBJYqmyQfy+3K0Z0LQXfsY95U9JBkKl3nQPn\r\n" +"p1PzV8wLp/XYE7ePsbIbjQ1gQdC47sTDjoA73X4wEchdEVJBNUs2e15HRxbzaVJ6ABSKI9AHkxKv\r\n" +"o9iYKFozQaL4y+3Y+Yei/N1kiZZayJqC1uXq45kelc3SCJrVPE4g/Uspf2jjp7xsS+MkmxvSAT9X\r\n" +"OJeDWEeXyt7tvJeodRQgGZVhdtN78mtoaqWqD9Z6a6wpWdC4sZCWJfMjCu4Wd889Pn4MT5DBKBN3\r\n" +"f3+JpOzUJlM9\r\n" +"-----END CERTIFICATE-----\r\n"; + +static char g_testCert[] = +"-----BEGIN CERTIFICATE-----\r\n" +"MIID/jCCAuagAwIBAgIBATANBgkqhkiG9w0BAQsFADCBjDELMAkGA1UEBhMCQ04x\r\n" +"ETAPBgNVBAgMCHNoYW5naGFpMQ8wDQYDVQQHDAZodWF3ZWkxFTATBgNVBAoMDHd3\r\n" +"dy50ZXN0LmNvbTENMAsGA1UECwwEdGVzdDEVMBMGA1UEAwwMd3d3LnRlc3QuY29t\r\n" +"MRwwGgYJKoZIhvcNAQkBFg10ZXN0QHRlc3QuY29tMB4XDTIyMDgyOTA2NTUwM1oX\r\n" +"DTIzMDgyOTA2NTUwM1owezELMAkGA1UEBhMCQ04xETAPBgNVBAgMCHNoYW5naGFp\r\n" +"MRUwEwYDVQQKDAx3d3cudGVzdC5jb20xDTALBgNVBAsMBHRlc3QxFTATBgNVBAMM\r\n" +"DHd3dy50ZXN0LmNvbTEcMBoGCSqGSIb3DQEJARYNdGVzdEB0ZXN0LmNvbTCCASIw\r\n" +"DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJmY9T4SzXXwKvfMvnvMWY7TqUJK\r\n" +"jnWf2Puv0YUQ2fdvyoKQ2LQXdtzoUL53j587oI+IXelOr7dg020zPyun0cmZHZ4y\r\n" +"l/qAcrWbDjZeEGcbbb5UtQtn1WOEnv8pkXluO355mbZQUKK9L3gFWseXJKGbIXw0\r\n" +"NRpaJZzqvPor4m3a5pmJKPHOlivUdYfLaKSkNj3DlaFzCWKV82k5ee6gzVyETtG+\r\n" +"XN+vq8qLybT+fIFsLNMmAHzRxlqz3NiH7yh+1/p/Knvf8bkkRVR2btH51RyX2RSu\r\n" +"DjPM0/VRL8fxDSDeWBq+Gvn/E6AbOVMmkx63tcyWHhklCSaZtyz7kq39TQMCAwEA\r\n" +"AaN7MHkwCQYDVR0TBAIwADAsBglghkgBhvhCAQ0EHxYdT3BlblNTTCBHZW5lcmF0\r\n" +"ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFFiFDysfADQCzRZCOSPupQxFicwzMB8G\r\n" +"A1UdIwQYMBaAFNYQRQiPsG8HefOTsmsVhaVjY7IPMA0GCSqGSIb3DQEBCwUAA4IB\r\n" +"AQAeppxf6sKQJxJQXKPTT3xHKaskidNwDBbOSIvnVvWXicZXDs+1sF6tUaRgvPxL\r\n" +"OL58+P2Jy0tfSwj2WhqQRGe9MvQ5iFHcdelZc0ciW6EQ0VDHIaDAQc2nQzej/79w\r\n" +"UE7BJJV3b9n1be2iCsuodKO14pOkMb84WcIxng+8SD+MiFqV5BPO1QyKGdO1PE1b\r\n" +"+evjyTpFSTgZf2Mw3fGtu5hfEXyHw1lnsFY2MlSwiRlAym/gm4aXy+4H6LyXKd56\r\n" +"UYQ6fituD0ziaw3RI6liyIe7aENHCkZf6bAvMRhk4QiU4xu6emwX8Qt1bT7RthP0\r\n" +"1Vsro0IOeXT9WAcqEtQUegsi\r\n" +"-----END CERTIFICATE-----\r\n"; + +static char g_testCrl[] = +"-----BEGIN X509 CRL-----\r\n" +"MIIB/DCB5QIBATANBgkqhkiG9w0BAQsFADCBjDELMAkGA1UEBhMCQ04xETAPBgNV\r\n" +"BAgMCHNoYW5naGFpMQ8wDQYDVQQHDAZodWF3ZWkxFTATBgNVBAoMDHd3dy50ZXN0\r\n" +"LmNvbTENMAsGA1UECwwEdGVzdDEVMBMGA1UEAwwMd3d3LnRlc3QuY29tMRwwGgYJ\r\n" +"KoZIhvcNAQkBFg10ZXN0QHRlc3QuY29tFw0yMjA4MjkwNzAwMTRaFw0yMjA5Mjgw\r\n" +"NzAwMTRaMBQwEgIBARcNMjIwODI5MDY1OTUzWqAOMAwwCgYDVR0UBAMCAQAwDQYJ\r\n" +"KoZIhvcNAQELBQADggEBAHpfFhhUR59OAvOSuKDQUC5tKeLEuPbY8bYdmQVI8EFd\r\n" +"xDkZTXmT3CX1aDPYKVsG/jH9KPAmCV/ODKEGiJzclb3Z4am7tT+Wy4mpXypNS1od\r\n" +"wPDcQGsMrjT6iSp6JImiB0dDDSleBTBcYR/hhtFaiGSncyqJ0mhyaXPxIkNOO6nY\r\n" +"v+rcTEPQWavViDRyNDhnTbN868I3fzFVBcidF13CA0sCJ91ZvsE9h/YmPO2+e0YE\r\n" +"IUgzn37UOiLGObCVBY12QjGiuvVvCl7ncncsFEJuGfvONOqyFHjyxDHo5W0fqTn2\r\n" +"eCtiNcgUr9Kz2bwCmvEXhP7PuF4RMLq4vfzi0YjCG98=\r\n" +"-----END X509 CRL-----\r\n"; + +HcfX509Crl *g_x509Crl = nullptr; +HcfKeyPair *g_keyPair = nullptr; +ASN1_TIME *g_lastUpdate = nullptr; +ASN1_TIME *g_nextUpdate = nullptr; +ASN1_TIME *g_rvTime = nullptr; +HcfEncodingBlob *g_crlDerInStream = nullptr; +unsigned char *g_tbs = nullptr; +unsigned char *g_signatureStr = nullptr; +int g_signatureLen = 0; +class X509CrlTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +static unsigned char *GetCrlStream() +{ + int ret, len; + unsigned char *buf, *p; + time_t t; + X509_NAME *issuer; + X509_CRL *crl = nullptr; + X509_REVOKED *revoked; + EVP_PKEY *prikey; + ASN1_INTEGER *serial; + + // Generate keyPair + HcfAsyKeyGenerator *generator = nullptr; + HcfAsyKeyGeneratorCreate("RSA1024|PRIMES_3", &generator); + generator->generateKeyPair(generator, nullptr, &g_keyPair); + RSA *rsaPrikey = ((HcfOpensslRsaPriKey *)g_keyPair->priKey)->sk; + prikey = EVP_PKEY_new(); + EVP_PKEY_assign_RSA(prikey, rsaPrikey); + + // Set version + crl = X509_CRL_new(); + ret = X509_CRL_set_version(crl, TEST_VERSION); + + // Set Issuer + issuer = X509_NAME_new(); + ret = X509_NAME_add_entry_by_NID(issuer, NID_commonName, V_ASN1_PRINTABLESTRING, + (const unsigned char *)"CRL issuer", 10, -1, 0); + ret = X509_CRL_set_issuer_name(crl, issuer); + + // Set last time + g_lastUpdate = ASN1_TIME_new(); + t = time(nullptr); + ASN1_TIME_set(g_lastUpdate, t + TEST_OFFSET_TIME); + ret = X509_CRL_set_lastUpdate(crl, g_lastUpdate); + + // Set next time + g_nextUpdate = ASN1_TIME_new(); + t = TEST_TIME; + ASN1_TIME_set(g_nextUpdate, t); + ret = X509_CRL_set_nextUpdate(crl, g_nextUpdate); + + // Add serial number + revoked = X509_REVOKED_new(); + serial = ASN1_INTEGER_new(); + ret = ASN1_INTEGER_set(serial, TEST_SN); + ret = X509_REVOKED_set_serialNumber(revoked, serial); + + // Set revocationDate + g_rvTime = ASN1_TIME_new(); + t = TEST_TIME; + ASN1_TIME_set(g_rvTime, t); + ret = X509_CRL_set_nextUpdate(crl, g_rvTime); + ret = X509_REVOKED_set_revocationDate(revoked, g_rvTime); + ret = X509_CRL_add0_revoked(crl, revoked); + + // Sort + ret = X509_CRL_sort(crl); + + // Sign + ret = X509_CRL_sign(crl, prikey, EVP_md5()); + + len = i2d_X509_CRL(crl, nullptr); + buf = (unsigned char *)malloc(len + TEST_OFFSET); + p = buf; + len = i2d_X509_CRL(crl, &p); + + // Get sign + const ASN1_BIT_STRING *ASN1Signature = NULL; + X509_CRL_get0_signature(crl, &ASN1Signature, NULL); + g_signatureStr = (unsigned char *)ASN1_STRING_get0_data(ASN1Signature); + g_signatureLen = ASN1_STRING_length(ASN1Signature); + // Get Tbs + i2d_re_X509_CRL_tbs(crl, &g_tbs); + + return buf; +} + +void X509CrlTest::SetUpTestCase() +{ + HcfX509Crl *x509Crl = nullptr; + g_crlDerInStream = (HcfEncodingBlob *)HcfMalloc(sizeof(HcfEncodingBlob), 0); + unsigned char *crlStream = GetCrlStream(); + g_crlDerInStream->data = (uint8_t *)crlStream; + g_crlDerInStream->encodingFormat = HCF_FORMAT_DER; + g_crlDerInStream->len = TEST_CRL_LEN; + HcfX509CrlCreate(g_crlDerInStream, &x509Crl); + g_x509Crl = (HcfX509Crl *)x509Crl; +} +void X509CrlTest::TearDownTestCase() +{ + if (g_x509Crl != nullptr) { + OH_HCF_ObjDestroy(g_x509Crl); + g_x509Crl = nullptr; + } + if (g_keyPair != nullptr) { + OH_HCF_ObjDestroy(g_keyPair); + g_keyPair = nullptr; + } + if (g_lastUpdate != nullptr) { + ASN1_TIME_free(g_lastUpdate); + g_lastUpdate = nullptr; + } + if (g_nextUpdate != nullptr) { + ASN1_TIME_free(g_nextUpdate); + g_nextUpdate = nullptr; + } + if (g_rvTime != nullptr) { + ASN1_TIME_free(g_rvTime); + g_rvTime = nullptr; + } + if (g_crlDerInStream != nullptr) { + HcfFree(g_crlDerInStream->data); + HcfFree(g_crlDerInStream); + g_crlDerInStream = nullptr; + } +} +void X509CrlTest::SetUp() {} +void X509CrlTest::TearDown() {} + +// Begin test crl create, test crl create PEM true +HWTEST_F(X509CrlTest, X509CrlTest001, TestSize.Level0) +{ + HcfX509Crl *x509Crl = nullptr; + HcfEncodingBlob inStreamCrl = { 0 }; + inStreamCrl.data = (uint8_t *)g_testCrl; + inStreamCrl.encodingFormat = HCF_FORMAT_PEM; + inStreamCrl.len = strlen(g_testCrl) + 1; + HcfResult ret = HcfX509CrlCreate(&inStreamCrl, &x509Crl); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Crl, nullptr); + OH_HCF_ObjDestroy(x509Crl); +} + +// Test crl create DER true +HWTEST_F(X509CrlTest, X509CrlTest002, TestSize.Level0) +{ + HcfX509Crl *x509Crl = nullptr; + HcfResult ret = HcfX509CrlCreate(g_crlDerInStream, &x509Crl); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Crl, nullptr); + OH_HCF_ObjDestroy(x509Crl); +} + +// Test crl create error | encodingFormat +HWTEST_F(X509CrlTest, X509CrlTest003, TestSize.Level0) +{ + HcfX509Crl *x509Crl = nullptr; + HcfEncodingBlob inStreamCrl = { 0 }; + inStreamCrl.data = (uint8_t *)g_testCrl; + inStreamCrl.encodingFormat = HCF_FORMAT_DER; + inStreamCrl.len = strlen(g_testCrl) + 1; + HcfResult ret = HcfX509CrlCreate(&inStreamCrl, &x509Crl); + EXPECT_NE(ret, HCF_SUCCESS); + EXPECT_EQ(x509Crl, nullptr); +} + +// Test crl create error | Crl data +HWTEST_F(X509CrlTest, X509CrlTest004, TestSize.Level0) +{ + HcfX509Crl *x509Crl = nullptr; + HcfEncodingBlob inStreamCrl = { 0 }; + inStreamCrl.data = nullptr; + inStreamCrl.encodingFormat = HCF_FORMAT_PEM; + inStreamCrl.len = strlen(g_testCrl) + 1; + HcfResult ret = HcfX509CrlCreate(&inStreamCrl, &x509Crl); + EXPECT_NE(ret, HCF_SUCCESS); + EXPECT_EQ(x509Crl, nullptr); +} + +// Test crl create error | Crl len +HWTEST_F(X509CrlTest, X509CrlTest005, TestSize.Level0) +{ + HcfX509Crl *x509Crl = nullptr; + HcfEncodingBlob inStreamCrl = { 0 }; + inStreamCrl.data = (uint8_t *)g_testCrl; + inStreamCrl.encodingFormat = HCF_FORMAT_PEM; + inStreamCrl.len = 0; + HcfResult ret = HcfX509CrlCreate(&inStreamCrl, &x509Crl); + EXPECT_NE(ret, HCF_SUCCESS); + EXPECT_EQ(x509Crl, nullptr); +} + +// Test crl create error | Crl nullptr +HWTEST_F(X509CrlTest, X509CrlTest006, TestSize.Level0) +{ + HcfX509Crl *x509Crl = nullptr; + HcfEncodingBlob *inStreamCrl = nullptr; + HcfResult ret = HcfX509CrlCreate(inStreamCrl, &x509Crl); + EXPECT_NE(ret, HCF_SUCCESS); + EXPECT_EQ(x509Crl, nullptr); +} + +// Begin test crl isRevoked, test crl isRevoked true +HWTEST_F(X509CrlTest, X509CrlTest011, TestSize.Level0) +{ + // Get cert + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStreamCert = { 0 }; + inStreamCert.data = (uint8_t *)g_testCert; + inStreamCert.encodingFormat = HCF_FORMAT_PEM; + inStreamCert.len = strlen(g_testCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStreamCert, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + + // Get crl + HcfX509Crl *x509Crl = nullptr; + HcfEncodingBlob inStreamCrl = { 0 }; + inStreamCrl.data = (uint8_t *)g_testCrl; + inStreamCrl.encodingFormat = HCF_FORMAT_PEM; + inStreamCrl.len = strlen(g_testCrl) + 1; + ret = HcfX509CrlCreate(&inStreamCrl, &x509Crl); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Crl, nullptr); + + bool resIsRevoked = x509Crl->base.isRevoked((HcfCrl *)x509Crl, (HcfCertificate *)x509Cert); + EXPECT_EQ(resIsRevoked, true); + OH_HCF_ObjDestroy(x509Crl); + OH_HCF_ObjDestroy(x509Cert); +} + +// Test crl isRevoked error | crl null +HWTEST_F(X509CrlTest, X509CrlTest012, TestSize.Level0) +{ + // Get cert + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStreamCert = { 0 }; + inStreamCert.data = (uint8_t *)g_testCert; + inStreamCert.encodingFormat = HCF_FORMAT_PEM; + inStreamCert.len = strlen(g_testCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStreamCert, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + + bool resIsRevoked = g_x509Crl->base.isRevoked(nullptr, (HcfCertificate *)x509Cert); + EXPECT_EQ(resIsRevoked, false); + OH_HCF_ObjDestroy(x509Cert); +} + +// Test crl isRevoked error | x509Cert null +HWTEST_F(X509CrlTest, X509CrlTest013, TestSize.Level0) +{ + // Get crl + HcfX509Crl *x509Crl = nullptr; + HcfEncodingBlob inStreamCrl = { 0 }; + inStreamCrl.data = (uint8_t *)g_testCrl; + inStreamCrl.encodingFormat = HCF_FORMAT_PEM; + inStreamCrl.len = strlen(g_testCrl) + 1; + HcfResult ret = HcfX509CrlCreate(&inStreamCrl, &x509Crl); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Crl, nullptr); + + bool resIsRevoked = x509Crl->base.isRevoked((HcfCrl *)x509Crl, nullptr); + EXPECT_EQ(resIsRevoked, false); + OH_HCF_ObjDestroy(x509Crl); +} + +// Test crl isRevoked error | x509Crl error +HWTEST_F(X509CrlTest, X509CrlTest014, TestSize.Level0) +{ + // Get cert + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStreamCert = { 0 }; + inStreamCert.data = (uint8_t *)g_testCert; + inStreamCert.encodingFormat = HCF_FORMAT_PEM; + inStreamCert.len = strlen(g_testCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStreamCert, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + + // Get crl + HcfX509Crl *x509Crl = nullptr; + ret = HcfX509CrlCreate(g_crlDerInStream, &x509Crl); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Crl, nullptr); + + bool resIsRevoked = x509Crl->base.isRevoked((HcfCrl *)x509Crl, (HcfCertificate *)x509Cert); + EXPECT_EQ(resIsRevoked, false); + OH_HCF_ObjDestroy(x509Cert); + OH_HCF_ObjDestroy(x509Crl); +} + +// Test crl isRevoked error | x509Crl error +HWTEST_F(X509CrlTest, X509CrlTest015, TestSize.Level0) +{ + // Get cert + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStreamCert = { 0 }; + inStreamCert.data = (uint8_t *)g_testErrorCert; + inStreamCert.encodingFormat = HCF_FORMAT_PEM; + inStreamCert.len = strlen(g_testErrorCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStreamCert, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + + // Get crl + HcfX509Crl *x509Crl = nullptr; + HcfEncodingBlob inStreamCrl = { 0 }; + inStreamCrl.data = (uint8_t *)g_testCrl; + inStreamCrl.encodingFormat = HCF_FORMAT_PEM; + inStreamCrl.len = strlen(g_testCrl) + 1; + ret = HcfX509CrlCreate(&inStreamCrl, &x509Crl); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Crl, nullptr); + + bool resIsRevoked = x509Crl->base.isRevoked((HcfCrl *)x509Crl, (HcfCertificate *)x509Cert); + EXPECT_EQ(resIsRevoked, false); + OH_HCF_ObjDestroy(x509Cert); + OH_HCF_ObjDestroy(x509Crl); +} + +// Test crl GetType true +HWTEST_F(X509CrlTest, X509CrlTest021, TestSize.Level0) +{ + // Get crl + HcfX509Crl *x509Crl = nullptr; + HcfEncodingBlob inStreamCrl = { 0 }; + inStreamCrl.data = (uint8_t *)g_testCrl; + inStreamCrl.encodingFormat = HCF_FORMAT_PEM; + inStreamCrl.len = strlen(g_testCrl) + 1; + HcfResult ret = HcfX509CrlCreate(&inStreamCrl, &x509Crl); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Crl, nullptr); + + const char *resStr = x509Crl->base.getType((HcfCrl *)x509Crl); + EXPECT_STREQ(resStr, "X509"); + OH_HCF_ObjDestroy(x509Crl); +} + +// Test crl GetType error +HWTEST_F(X509CrlTest, X509CrlTest022, TestSize.Level0) +{ + // Get crl + HcfX509Crl *x509Crl = nullptr; + HcfEncodingBlob inStreamCrl = { 0 }; + inStreamCrl.data = (uint8_t *)g_testCrl; + inStreamCrl.encodingFormat = HCF_FORMAT_PEM; + inStreamCrl.len = strlen(g_testCrl) + 1; + HcfResult ret = HcfX509CrlCreate(&inStreamCrl, &x509Crl); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Crl, nullptr); + + const char *resStr = x509Crl->base.getType(nullptr); + EXPECT_EQ(resStr, nullptr); + OH_HCF_ObjDestroy(x509Crl); +} + +// Test crl getEncoded DER true +HWTEST_F(X509CrlTest, X509CrlTest031, TestSize.Level0) +{ + HcfEncodingBlob inStreamInput = { 0 }; + HcfResult ret = g_x509Crl->getEncoded(g_x509Crl, &inStreamInput); + EXPECT_EQ(ret, HCF_SUCCESS); + HcfX509Crl *crl2 = nullptr; + ret = HcfX509CrlCreate(&inStreamInput, &crl2); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(crl2, nullptr); + OH_HCF_ObjDestroy(crl2); + HcfFree(inStreamInput.data); +} + +// Test crl getEncoded PEM true +HWTEST_F(X509CrlTest, X509CrlTest032, TestSize.Level0) +{ + // Get crl + HcfX509Crl *x509Crl = nullptr; + HcfEncodingBlob inStreamCrl = { 0 }; + inStreamCrl.data = (uint8_t *)g_testCrl; + inStreamCrl.encodingFormat = HCF_FORMAT_PEM; + inStreamCrl.len = strlen(g_testCrl) + 1; + HcfResult ret = HcfX509CrlCreate(&inStreamCrl, &x509Crl); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Crl, nullptr); + + HcfEncodingBlob inStreamInput = { 0 }; + ret = x509Crl->getEncoded(x509Crl, &inStreamInput); + EXPECT_EQ(ret, HCF_SUCCESS); + HcfX509Crl *crl2 = nullptr; + ret = HcfX509CrlCreate(&inStreamInput, &crl2); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(crl2, nullptr); + HcfFree(inStreamInput.data); + OH_HCF_ObjDestroy(crl2); + OH_HCF_ObjDestroy(x509Crl); +} + +// Test crl getEncoded error +HWTEST_F(X509CrlTest, X509CrlTest033, TestSize.Level0) +{ + HcfResult ret = g_x509Crl->getEncoded(g_x509Crl, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); +} + +// Test crl getEncoded error +HWTEST_F(X509CrlTest, X509CrlTest034, TestSize.Level0) +{ + HcfEncodingBlob inStreamInput = { 0 }; + HcfResult ret = g_x509Crl->getEncoded(nullptr, &inStreamInput); + EXPECT_NE(ret, HCF_SUCCESS); +} + +// Test crl getEncoded error +HWTEST_F(X509CrlTest, X509CrlTest035, TestSize.Level0) +{ + HcfResult ret = g_x509Crl->getEncoded(nullptr, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); +} + +// Test crl verify true +HWTEST_F(X509CrlTest, X509CrlTest041, TestSize.Level0) +{ + HcfResult ret = g_x509Crl->verify(g_x509Crl, g_keyPair->pubKey); + EXPECT_EQ(ret, HCF_SUCCESS); +} + +// Test crl verify false +HWTEST_F(X509CrlTest, X509CrlTest042, TestSize.Level0) +{ + HcfKeyPair *keyPair = nullptr; + HcfAsyKeyGenerator *generator = nullptr; + HcfAsyKeyGeneratorCreate("RSA1024|PRIMES_3", &generator); + generator->generateKeyPair(generator, nullptr, &keyPair); + + HcfResult ret = g_x509Crl->verify(g_x509Crl, keyPair->pubKey); + EXPECT_NE(ret, HCF_SUCCESS); + OH_HCF_ObjDestroy(keyPair); + OH_HCF_ObjDestroy(generator); +} + +// Test crl verify false +HWTEST_F(X509CrlTest, X509CrlTest043, TestSize.Level0) +{ + HcfResult ret = g_x509Crl->verify(nullptr, g_keyPair->pubKey); + EXPECT_NE(ret, HCF_SUCCESS); +} + +// Test crl verify false +HWTEST_F(X509CrlTest, X509CrlTest044, TestSize.Level0) +{ + HcfResult ret = g_x509Crl->verify(g_x509Crl, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); +} + +// Test crl verify false +HWTEST_F(X509CrlTest, X509CrlTest045, TestSize.Level0) +{ + // Get crl + HcfX509Crl *x509Crl = nullptr; + HcfEncodingBlob inStreamCrl = { 0 }; + inStreamCrl.data = (uint8_t *)g_testCrl; + inStreamCrl.encodingFormat = HCF_FORMAT_PEM; + inStreamCrl.len = strlen(g_testCrl) + 1; + HcfResult ret = HcfX509CrlCreate(&inStreamCrl, &x509Crl); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Crl, nullptr); + + ret = x509Crl->verify(x509Crl, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); + OH_HCF_ObjDestroy(x509Crl); +} + +// Test crl getVersion true +HWTEST_F(X509CrlTest, X509CrlTest051, TestSize.Level0) +{ + long version = g_x509Crl->getVersion(g_x509Crl); + EXPECT_EQ(version, TEST_EXT_VERSION); +} + +// Test crl getVersion false +HWTEST_F(X509CrlTest, X509CrlTest052, TestSize.Level0) +{ + long version = g_x509Crl->getVersion(nullptr); + EXPECT_EQ(version, -1); +} + +// Test crl getIssuerName true +HWTEST_F(X509CrlTest, X509CrlTest061, TestSize.Level0) +{ + HcfBlob out = { 0 }; + HcfResult ret = g_x509Crl->getIssuerName(g_x509Crl, &out); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(out.data, nullptr); + EXPECT_STREQ("/CN=CRL issuer", (char *)(out.data)); + HcfFree(out.data); +} + +// Test crl getIssuerName false +HWTEST_F(X509CrlTest, X509CrlTest062, TestSize.Level0) +{ + HcfBlob out = { 0 }; + HcfResult ret = g_x509Crl->getIssuerName(nullptr, &out); + EXPECT_NE(ret, HCF_SUCCESS); + EXPECT_EQ(out.data, nullptr); +} + +// Test crl getIssuerName false +HWTEST_F(X509CrlTest, X509CrlTest063, TestSize.Level0) +{ + HcfResult ret = g_x509Crl->getIssuerName(g_x509Crl, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); +} + +// Test crl getIssuerName false +HWTEST_F(X509CrlTest, X509CrlTest064, TestSize.Level0) +{ + HcfResult ret = g_x509Crl->getIssuerName(nullptr, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); +} + +// Test crl getLastUpdate true +HWTEST_F(X509CrlTest, X509CrlTest071, TestSize.Level0) +{ + HcfBlob out = { 0 }; + HcfResult ret = g_x509Crl->getLastUpdate(g_x509Crl, &out); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(out.data, nullptr); + EXPECT_STREQ((char *)g_lastUpdate->data, (char *)out.data); + HcfFree(out.data); +} + +// Test crl getLastUpdate false +HWTEST_F(X509CrlTest, X509CrlTest072, TestSize.Level0) +{ + HcfBlob out = { 0 }; + HcfResult ret = g_x509Crl->getLastUpdate(nullptr, &out); + EXPECT_NE(ret, HCF_SUCCESS); + EXPECT_EQ(out.data, nullptr); +} + +// Test crl getLastUpdate false +HWTEST_F(X509CrlTest, X509CrlTest073, TestSize.Level0) +{ + HcfResult ret = g_x509Crl->getLastUpdate(g_x509Crl, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); +} + +// Test crl getLastUpdate false +HWTEST_F(X509CrlTest, X509CrlTest074, TestSize.Level0) +{ + HcfResult ret = g_x509Crl->getLastUpdate(nullptr, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); +} + +// Test crl getNextUpdate true +HWTEST_F(X509CrlTest, X509CrlTest081, TestSize.Level0) +{ + HcfBlob out = { 0 }; + HcfResult ret = g_x509Crl->getNextUpdate(g_x509Crl, &out); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(out.data, nullptr); + EXPECT_STREQ((char *)g_nextUpdate->data, (char *)out.data); + HcfFree(out.data); +} + +// Test crl getNextUpdate false +HWTEST_F(X509CrlTest, X509CrlTest082, TestSize.Level0) +{ + HcfBlob out = { 0 }; + HcfResult ret = g_x509Crl->getNextUpdate(nullptr, &out); + EXPECT_NE(ret, HCF_SUCCESS); + EXPECT_EQ(out.data, nullptr); +} + +// Test crl getNextUpdate false +HWTEST_F(X509CrlTest, X509CrlTest083, TestSize.Level0) +{ + HcfResult ret = g_x509Crl->getNextUpdate(g_x509Crl, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); +} + +// Test crl getNextUpdate false +HWTEST_F(X509CrlTest, X509CrlTest084, TestSize.Level0) +{ + HcfResult ret = g_x509Crl->getNextUpdate(nullptr, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); +} + +// Test crl getRevokedCert true +HWTEST_F(X509CrlTest, X509CrlTest091, TestSize.Level0) +{ + HcfX509CrlEntry *crlEntry = nullptr; + HcfResult ret = g_x509Crl->getRevokedCert(g_x509Crl, 1000, &crlEntry); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(crlEntry, nullptr); + OH_HCF_ObjDestroy(crlEntry); +} + +// Test crl getRevokedCert false +HWTEST_F(X509CrlTest, X509CrlTest092, TestSize.Level0) +{ + HcfX509CrlEntry *crlEntry = nullptr; + HcfResult ret = g_x509Crl->getRevokedCert(g_x509Crl, 9999, &crlEntry); + EXPECT_NE(ret, HCF_SUCCESS); +} + +// Test crl getRevokedCert false +HWTEST_F(X509CrlTest, X509CrlTest093, TestSize.Level0) +{ + HcfResult ret = g_x509Crl->getRevokedCert(g_x509Crl, 1000, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); +} + +// Test crl getRevokedCert false +HWTEST_F(X509CrlTest, X509CrlTest094, TestSize.Level0) +{ + HcfX509CrlEntry *crlEntry = nullptr; + HcfResult ret = g_x509Crl->getRevokedCert(nullptr, 1000, &crlEntry); + EXPECT_NE(ret, HCF_SUCCESS); +} + +// Test crl getRevokedCert false +HWTEST_F(X509CrlTest, X509CrlTest095, TestSize.Level0) +{ + HcfResult ret = g_x509Crl->getRevokedCert(nullptr, 1000, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); +} + +// Test crl entry getSerialNumber true +HWTEST_F(X509CrlTest, X509CrlTest101, TestSize.Level0) +{ + HcfX509CrlEntry *crlEntry = nullptr; + HcfResult ret = g_x509Crl->getRevokedCert(g_x509Crl, 1000, &crlEntry); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(crlEntry, nullptr); + long sn = crlEntry->getSerialNumber(crlEntry); + EXPECT_EQ(sn, 1000); + OH_HCF_ObjDestroy(crlEntry); +} + +// Test crl entry getSerialNumber false +HWTEST_F(X509CrlTest, X509CrlTest102, TestSize.Level0) +{ + HcfX509CrlEntry *crlEntry = nullptr; + HcfResult ret = g_x509Crl->getRevokedCert(g_x509Crl, 1000, &crlEntry); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(crlEntry, nullptr); + long sn = crlEntry->getSerialNumber(nullptr); + EXPECT_EQ(sn, -1); + OH_HCF_ObjDestroy(crlEntry); +} + +// Test crl entry getSerialNumber false +HWTEST_F(X509CrlTest, X509CrlTest103, TestSize.Level0) +{ + HcfX509CrlEntry *crlEntry = nullptr; + HcfResult ret = g_x509Crl->getRevokedCert(g_x509Crl, 1000, &crlEntry); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(crlEntry, nullptr); + long sn = crlEntry->getSerialNumber(nullptr); + EXPECT_EQ(sn, -1); + OH_HCF_ObjDestroy(crlEntry); +} + +// Test crl entry getEncoded true +HWTEST_F(X509CrlTest, X509CrlTest111, TestSize.Level0) +{ + HcfX509CrlEntry *crlEntry = nullptr; + HcfResult ret = g_x509Crl->getRevokedCert(g_x509Crl, 1000, &crlEntry); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(crlEntry, nullptr); + + HcfEncodingBlob encodingBlob = { 0 }; + ret = crlEntry->getEncoded(crlEntry, &encodingBlob); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(encodingBlob.data, nullptr); + OH_HCF_ObjDestroy(crlEntry); + HcfFree(encodingBlob.data); +} + +// Test crl entry getEncoded false +HWTEST_F(X509CrlTest, X509CrlTest112, TestSize.Level0) +{ + HcfX509CrlEntry *crlEntry = nullptr; + HcfResult ret = g_x509Crl->getRevokedCert(g_x509Crl, 1000, &crlEntry); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(crlEntry, nullptr); + + HcfEncodingBlob encodingBlob = { 0 }; + ret = crlEntry->getEncoded(nullptr, &encodingBlob); + EXPECT_NE(ret, HCF_SUCCESS); + EXPECT_EQ(encodingBlob.data, nullptr); + OH_HCF_ObjDestroy(crlEntry); +} + +// Test crl entry getEncoded false +HWTEST_F(X509CrlTest, X509CrlTest113, TestSize.Level0) +{ + HcfX509CrlEntry *crlEntry = nullptr; + HcfResult ret = g_x509Crl->getRevokedCert(g_x509Crl, 1000, &crlEntry); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(crlEntry, nullptr); + + ret = crlEntry->getEncoded(crlEntry, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); + OH_HCF_ObjDestroy(crlEntry); +} + +// Test crl entry getEncoded false +HWTEST_F(X509CrlTest, X509CrlTest114, TestSize.Level0) +{ + HcfX509CrlEntry *crlEntry = nullptr; + HcfResult ret = g_x509Crl->getRevokedCert(g_x509Crl, 1000, &crlEntry); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(crlEntry, nullptr); + + ret = crlEntry->getEncoded(nullptr, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); + OH_HCF_ObjDestroy(crlEntry); +} + +// Test crl entry getCertIssuer true +HWTEST_F(X509CrlTest, X509CrlTest121, TestSize.Level0) +{ + HcfX509CrlEntry *crlEntry = nullptr; + HcfResult ret = g_x509Crl->getRevokedCert(g_x509Crl, 1000, &crlEntry); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(crlEntry, nullptr); + + HcfBlob out = { 0 }; + ret = crlEntry->getCertIssuer(crlEntry, &out); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(out.data, nullptr); + EXPECT_STREQ("/CN=CRL issuer", (char *)out.data); + OH_HCF_ObjDestroy(crlEntry); + HcfFree(out.data); +} + +// Test crl entry getCertIssuer false +HWTEST_F(X509CrlTest, X509CrlTest122, TestSize.Level0) +{ + HcfX509CrlEntry *crlEntry = nullptr; + HcfResult ret = g_x509Crl->getRevokedCert(g_x509Crl, 1000, &crlEntry); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(crlEntry, nullptr); + + HcfBlob out = { 0 }; + ret = crlEntry->getCertIssuer(nullptr, &out); + EXPECT_NE(ret, HCF_SUCCESS); + EXPECT_EQ(out.data, nullptr); + OH_HCF_ObjDestroy(crlEntry); +} + +// Test crl entry getCertIssuer false +HWTEST_F(X509CrlTest, X509CrlTest123, TestSize.Level0) +{ + HcfX509CrlEntry *crlEntry = nullptr; + HcfResult ret = g_x509Crl->getRevokedCert(g_x509Crl, 1000, &crlEntry); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(crlEntry, nullptr); + + ret = crlEntry->getCertIssuer(crlEntry, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); + OH_HCF_ObjDestroy(crlEntry); +} + +// Test crl entry getRevocationDate true +HWTEST_F(X509CrlTest, X509CrlTest131, TestSize.Level0) +{ + HcfX509CrlEntry *crlEntry = nullptr; + HcfResult ret = g_x509Crl->getRevokedCert(g_x509Crl, 1000, &crlEntry); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(crlEntry, nullptr); + + HcfBlob out = { 0 }; + ret = crlEntry->getRevocationDate(crlEntry, &out); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(out.data, nullptr); + EXPECT_STREQ((char *)g_rvTime->data, (char *)out.data); + OH_HCF_ObjDestroy(crlEntry); + HcfFree(out.data); +} + +// Test crl entry getRevocationDate false +HWTEST_F(X509CrlTest, X509CrlTest132, TestSize.Level0) +{ + HcfX509CrlEntry *crlEntry = nullptr; + HcfResult ret = g_x509Crl->getRevokedCert(g_x509Crl, 1000, &crlEntry); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(crlEntry, nullptr); + + HcfBlob out = { 0 }; + ret = crlEntry->getRevocationDate(nullptr, &out); + EXPECT_NE(ret, HCF_SUCCESS); + EXPECT_EQ(out.data, nullptr); + OH_HCF_ObjDestroy(crlEntry); +} + +// Test crl entry getRevocationDate false +HWTEST_F(X509CrlTest, X509CrlTest133, TestSize.Level0) +{ + HcfX509CrlEntry *crlEntry = nullptr; + HcfResult ret = g_x509Crl->getRevokedCert(g_x509Crl, 1000, &crlEntry); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(crlEntry, nullptr); + + ret = crlEntry->getRevocationDate(crlEntry, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); + OH_HCF_ObjDestroy(crlEntry); +} + +// Test crl getRevokedCertWithCert true +HWTEST_F(X509CrlTest, X509CrlTest141, TestSize.Level0) +{ + // Get cert + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStreamCert = { 0 }; + inStreamCert.data = (uint8_t *)g_testCert; + inStreamCert.encodingFormat = HCF_FORMAT_PEM; + inStreamCert.len = strlen(g_testCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStreamCert, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + + // Get crl + HcfX509Crl *x509Crl = nullptr; + HcfEncodingBlob inStreamCrl = { 0 }; + inStreamCrl.data = (uint8_t *)g_testCrl; + inStreamCrl.encodingFormat = HCF_FORMAT_PEM; + inStreamCrl.len = strlen(g_testCrl) + 1; + ret = HcfX509CrlCreate(&inStreamCrl, &x509Crl); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Crl, nullptr); + + HcfX509CrlEntry *crlEntry = nullptr; + ret = x509Crl->getRevokedCertWithCert(x509Crl, x509Cert, &crlEntry); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(crlEntry, nullptr); + + HcfBlob out = { 0 }; + ret = crlEntry->getRevocationDate(crlEntry, &out); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(out.data, nullptr); + EXPECT_STREQ("220829065953Z", (char *)out.data); + + OH_HCF_ObjDestroy(x509Cert); + OH_HCF_ObjDestroy(x509Crl); + OH_HCF_ObjDestroy(crlEntry); + HcfFree(out.data); +} + +// Test crl getRevokedCertWithCert true +HWTEST_F(X509CrlTest, X509CrlTest142, TestSize.Level0) +{ + // Get cert + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStreamCert = { 0 }; + inStreamCert.data = (uint8_t *)g_testCert; + inStreamCert.encodingFormat = HCF_FORMAT_PEM; + inStreamCert.len = strlen(g_testCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStreamCert, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + + // Get crl + HcfX509Crl *x509Crl = nullptr; + HcfEncodingBlob inStreamCrl = { 0 }; + inStreamCrl.data = (uint8_t *)g_testCrl; + inStreamCrl.encodingFormat = HCF_FORMAT_PEM; + inStreamCrl.len = strlen(g_testCrl) + 1; + ret = HcfX509CrlCreate(&inStreamCrl, &x509Crl); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Crl, nullptr); + + HcfX509CrlEntry *crlEntry = nullptr; + ret = x509Crl->getRevokedCertWithCert(x509Crl, x509Cert, &crlEntry); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(crlEntry, nullptr); + + HcfBlob out = { 0 }; + ret = crlEntry->getCertIssuer(crlEntry, &out); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(out.data, nullptr); + EXPECT_STREQ("/C=CN/ST=shanghai/L=huawei/O=www.test.com/OU=test/CN=www.test.com/emailAddress=test@test.com", + (char *)out.data); + + OH_HCF_ObjDestroy(x509Cert); + OH_HCF_ObjDestroy(x509Crl); + OH_HCF_ObjDestroy(crlEntry); + HcfFree(out.data); +} + +// Test crl getRevokedCertWithCert true +HWTEST_F(X509CrlTest, X509CrlTest143, TestSize.Level0) +{ + // Get cert + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStreamCert = { 0 }; + inStreamCert.data = (uint8_t *)g_testCert; + inStreamCert.encodingFormat = HCF_FORMAT_PEM; + inStreamCert.len = strlen(g_testCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStreamCert, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + + // Get crl + HcfX509Crl *x509Crl = nullptr; + HcfEncodingBlob inStreamCrl = { 0 }; + inStreamCrl.data = (uint8_t *)g_testCrl; + inStreamCrl.encodingFormat = HCF_FORMAT_PEM; + inStreamCrl.len = strlen(g_testCrl) + 1; + ret = HcfX509CrlCreate(&inStreamCrl, &x509Crl); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Crl, nullptr); + + HcfX509CrlEntry *crlEntry = nullptr; + ret = x509Crl->getRevokedCertWithCert(x509Crl, x509Cert, &crlEntry); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(crlEntry, nullptr); + + HcfEncodingBlob encodingBlob = { 0 }; + ret = crlEntry->getEncoded(crlEntry, &encodingBlob); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(encodingBlob.data, nullptr); + + HcfFree(encodingBlob.data); + OH_HCF_ObjDestroy(x509Cert); + OH_HCF_ObjDestroy(x509Crl); + OH_HCF_ObjDestroy(crlEntry); +} + +// Test crl getRevokedCertWithCert false +HWTEST_F(X509CrlTest, X509CrlTest144, TestSize.Level0) +{ + // Get crl + HcfX509Crl *x509Crl = nullptr; + HcfEncodingBlob inStreamCrl = { 0 }; + inStreamCrl.data = (uint8_t *)g_testCrl; + inStreamCrl.encodingFormat = HCF_FORMAT_PEM; + inStreamCrl.len = strlen(g_testCrl) + 1; + HcfResult ret = HcfX509CrlCreate(&inStreamCrl, &x509Crl); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Crl, nullptr); + + HcfX509CrlEntry *crlEntry = nullptr; + ret = x509Crl->getRevokedCertWithCert(x509Crl, nullptr, &crlEntry); + EXPECT_NE(ret, HCF_SUCCESS); + EXPECT_EQ(crlEntry, nullptr); + + OH_HCF_ObjDestroy(x509Crl); +} + +// Test crl getRevokedCertWithCert false +HWTEST_F(X509CrlTest, X509CrlTest145, TestSize.Level0) +{ + // Get cert + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStreamCert = { 0 }; + inStreamCert.data = (uint8_t *)g_testCert; + inStreamCert.encodingFormat = HCF_FORMAT_PEM; + inStreamCert.len = strlen(g_testCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStreamCert, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + + // Get crl + HcfX509Crl *x509Crl = nullptr; + HcfEncodingBlob inStreamCrl = { 0 }; + inStreamCrl.data = (uint8_t *)g_testCrl; + inStreamCrl.encodingFormat = HCF_FORMAT_PEM; + inStreamCrl.len = strlen(g_testCrl) + 1; + ret = HcfX509CrlCreate(&inStreamCrl, &x509Crl); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Crl, nullptr); + + HcfX509CrlEntry *crlEntry = nullptr; + ret = x509Crl->getRevokedCertWithCert(nullptr, x509Cert, &crlEntry); + EXPECT_NE(ret, HCF_SUCCESS); + EXPECT_EQ(crlEntry, nullptr); + + OH_HCF_ObjDestroy(x509Cert); + OH_HCF_ObjDestroy(x509Crl); +} + +// Test crl getRevokedCertWithCert false +HWTEST_F(X509CrlTest, X509CrlTest146, TestSize.Level0) +{ + // Get cert + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStreamCert = { 0 }; + inStreamCert.data = (uint8_t *)g_testCert; + inStreamCert.encodingFormat = HCF_FORMAT_PEM; + inStreamCert.len = strlen(g_testCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStreamCert, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + + // Get crl + HcfX509Crl *x509Crl = nullptr; + HcfEncodingBlob inStreamCrl = { 0 }; + inStreamCrl.data = (uint8_t *)g_testCrl; + inStreamCrl.encodingFormat = HCF_FORMAT_PEM; + inStreamCrl.len = strlen(g_testCrl) + 1; + ret = HcfX509CrlCreate(&inStreamCrl, &x509Crl); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Crl, nullptr); + + ret = x509Crl->getRevokedCertWithCert(x509Crl, x509Cert, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); + + OH_HCF_ObjDestroy(x509Cert); + OH_HCF_ObjDestroy(x509Crl); +} + +// Test crl getRevokedCertWithCert false +HWTEST_F(X509CrlTest, X509CrlTest147, TestSize.Level0) +{ + // Get cert + HcfX509Certificate *x509Cert = nullptr; + HcfEncodingBlob inStreamCert = { 0 }; + inStreamCert.data = (uint8_t *)g_testCert; + inStreamCert.encodingFormat = HCF_FORMAT_PEM; + inStreamCert.len = strlen(g_testCert) + 1; + HcfResult ret = HcfX509CertificateCreate(&inStreamCert, &x509Cert); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Cert, nullptr); + + // Get crl + HcfX509Crl *x509Crl = nullptr; + HcfEncodingBlob inStreamCrl = { 0 }; + inStreamCrl.data = (uint8_t *)g_testCrl; + inStreamCrl.encodingFormat = HCF_FORMAT_PEM; + inStreamCrl.len = strlen(g_testCrl) + 1; + ret = HcfX509CrlCreate(&inStreamCrl, &x509Crl); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(x509Crl, nullptr); + + HcfX509CrlEntry *crlEntry = nullptr; + ret = x509Crl->getRevokedCertWithCert(x509Crl, x509Cert, &crlEntry); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(crlEntry, nullptr); + + HcfBlob out = { 0 }; + ret = crlEntry->getRevocationDate(nullptr, &out); + EXPECT_NE(ret, HCF_SUCCESS); + EXPECT_EQ(out.data, nullptr); + + OH_HCF_ObjDestroy(x509Cert); + OH_HCF_ObjDestroy(x509Crl); + OH_HCF_ObjDestroy(crlEntry); +} + +// Test crl entry getRevokedCerts true +HWTEST_F(X509CrlTest, X509CrlTest151, TestSize.Level0) +{ + HcfArray entrysOut = { 0 }; + HcfResult ret = g_x509Crl->getRevokedCerts(g_x509Crl, &entrysOut); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(entrysOut.data, nullptr); + + HcfX509CrlEntry *crlEntry = (HcfX509CrlEntry *)(entrysOut.data[0].data); + HcfBlob out = { 0 }; + ret = crlEntry->getRevocationDate(crlEntry, &out); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(out.data, nullptr); + EXPECT_STREQ((char *)g_rvTime->data, (char *)out.data); + + HcfFree(out.data); + OH_HCF_ObjDestroy(crlEntry); +} + +// Test crl entry getRevokedCerts false +HWTEST_F(X509CrlTest, X509CrlTest152, TestSize.Level0) +{ + HcfResult ret = g_x509Crl->getRevokedCerts(g_x509Crl, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); +} + +// Test crl entry getRevokedCerts false +HWTEST_F(X509CrlTest, X509CrlTest153, TestSize.Level0) +{ + HcfArray entrysOut = { 0 }; + HcfResult ret = g_x509Crl->getRevokedCerts(nullptr, &entrysOut); + EXPECT_NE(ret, HCF_SUCCESS); + EXPECT_EQ(entrysOut.data, nullptr); +} + +// Test crl entry getRevokedCerts false +HWTEST_F(X509CrlTest, X509CrlTest154, TestSize.Level0) +{ + HcfResult ret = g_x509Crl->getRevokedCerts(nullptr, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); +} + +// Test crl getTbsInfo true +HWTEST_F(X509CrlTest, X509CrlTest161, TestSize.Level0) +{ + HcfBlob tbsCertListOut = { 0 }; + HcfResult ret = g_x509Crl->getTbsInfo(g_x509Crl, &tbsCertListOut); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(tbsCertListOut.data, nullptr); + + EXPECT_STREQ((char *)g_tbs, (char *)tbsCertListOut.data); + HcfFree(tbsCertListOut.data); +} + +// Test crl getTbsInfo false +HWTEST_F(X509CrlTest, X509CrlTest162, TestSize.Level0) +{ + HcfBlob tbsCertListOut = { 0 }; + HcfResult ret = g_x509Crl->getTbsInfo(nullptr, &tbsCertListOut); + EXPECT_NE(ret, HCF_SUCCESS); + EXPECT_EQ(tbsCertListOut.data, nullptr); +} + +// Test crl getTbsInfo false +HWTEST_F(X509CrlTest, X509CrlTest163, TestSize.Level0) +{ + HcfResult ret = g_x509Crl->getTbsInfo(g_x509Crl, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); +} + +// Test crl getTbsInfo false +HWTEST_F(X509CrlTest, X509CrlTest164, TestSize.Level0) +{ + HcfResult ret = g_x509Crl->getTbsInfo(nullptr, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); +} + +// Test crl getSignature true +HWTEST_F(X509CrlTest, X509CrlTest171, TestSize.Level0) +{ + HcfBlob signature = { 0 }; + HcfResult ret = g_x509Crl->getSignature(g_x509Crl, &signature); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(signature.data, nullptr); + bool isEqual = (memcmp(g_signatureStr, signature.data, g_signatureLen) == 0); + EXPECT_EQ(isEqual, true); + HcfFree(signature.data); +} + +// Test crl getSignature false +HWTEST_F(X509CrlTest, X509CrlTest172, TestSize.Level0) +{ + HcfBlob signature = { 0 }; + HcfResult ret = g_x509Crl->getSignature(nullptr, &signature); + EXPECT_NE(ret, HCF_SUCCESS); + EXPECT_EQ(signature.data, nullptr); +} + +// Test crl getSignature false +HWTEST_F(X509CrlTest, X509CrlTest173, TestSize.Level0) +{ + HcfResult ret = g_x509Crl->getSignature(g_x509Crl, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); +} + +// Test crl getSignature false +HWTEST_F(X509CrlTest, X509CrlTest174, TestSize.Level0) +{ + HcfResult ret = g_x509Crl->getSignature(nullptr, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); +} + +// Test crl getSignatureAlgName true +HWTEST_F(X509CrlTest, X509CrlTest181, TestSize.Level0) +{ + HcfBlob out = { 0 }; + HcfResult ret = g_x509Crl->getSignatureAlgName(g_x509Crl, &out); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(out.data, nullptr); + EXPECT_STREQ("MD5withRSA", (char *)out.data); + HcfFree(out.data); +} + +// Test crl getSignatureAlgName false +HWTEST_F(X509CrlTest, X509CrlTest182, TestSize.Level0) +{ + HcfBlob out = { 0 }; + HcfResult ret = g_x509Crl->getSignatureAlgName(nullptr, &out); + EXPECT_NE(ret, HCF_SUCCESS); + EXPECT_EQ(out.data, nullptr); +} + +// Test crl getSignatureAlgName false +HWTEST_F(X509CrlTest, X509CrlTest183, TestSize.Level0) +{ + HcfResult ret = g_x509Crl->getSignatureAlgName(g_x509Crl, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); +} + +// Test crl getSignatureAlgName false +HWTEST_F(X509CrlTest, X509CrlTest184, TestSize.Level0) +{ + HcfResult ret = g_x509Crl->getSignatureAlgName(nullptr, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); +} + +// Test crl getSignatureAlgOid true +HWTEST_F(X509CrlTest, X509CrlTest191, TestSize.Level0) +{ + HcfBlob out = { 0 }; + HcfResult ret = g_x509Crl->getSignatureAlgOid(g_x509Crl, &out); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(out.data, nullptr); + EXPECT_STREQ("1.2.840.113549.1.1.4", (char *)out.data); + HcfFree(out.data); +} + +// Test crl getSignatureAlgOid false +HWTEST_F(X509CrlTest, X509CrlTest192, TestSize.Level0) +{ + HcfBlob out = { 0 }; + HcfResult ret = g_x509Crl->getSignatureAlgOid(nullptr, &out); + EXPECT_NE(ret, HCF_SUCCESS); + EXPECT_EQ(out.data, nullptr); +} + +// Test crl getSignatureAlgOid false +HWTEST_F(X509CrlTest, X509CrlTest193, TestSize.Level0) +{ + HcfResult ret = g_x509Crl->getSignatureAlgOid(g_x509Crl, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); +} + +// Test crl getSignatureAlgOid false +HWTEST_F(X509CrlTest, X509CrlTest194, TestSize.Level0) +{ + HcfResult ret = g_x509Crl->getSignatureAlgOid(nullptr, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); +} + +// Test crl getSignatureAlgParams true +HWTEST_F(X509CrlTest, X509CrlTest201, TestSize.Level0) +{ + HcfBlob sigAlgParamOut = { 0 }; + HcfResult ret = g_x509Crl->getSignatureAlgParams(g_x509Crl, &sigAlgParamOut); + EXPECT_EQ(ret, HCF_SUCCESS); + EXPECT_NE(sigAlgParamOut.data, nullptr); + HcfFree(sigAlgParamOut.data); +} + +// Test crl getSignatureAlgParams false +HWTEST_F(X509CrlTest, X509CrlTest202, TestSize.Level0) +{ + HcfBlob sigAlgParamOut = { 0 }; + HcfResult ret = g_x509Crl->getSignatureAlgParams(nullptr, &sigAlgParamOut); + EXPECT_NE(ret, HCF_SUCCESS); + EXPECT_EQ(sigAlgParamOut.data, nullptr); +} + +// Test crl getSignatureAlgParams false +HWTEST_F(X509CrlTest, X509CrlTest203, TestSize.Level0) +{ + HcfResult ret = g_x509Crl->getSignatureAlgParams(g_x509Crl, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); +} + +// Test crl getSignatureAlgParams false +HWTEST_F(X509CrlTest, X509CrlTest204, TestSize.Level0) +{ + HcfResult ret = g_x509Crl->getSignatureAlgParams(nullptr, nullptr); + EXPECT_NE(ret, HCF_SUCCESS); +} \ No newline at end of file diff --git a/test/unittest/src/x509_cert_chain_validator_test.cpp b/test/unittest/src/x509_cert_chain_validator_test.cpp new file mode 100644 index 0000000..f706bf2 --- /dev/null +++ b/test/unittest/src/x509_cert_chain_validator_test.cpp @@ -0,0 +1,272 @@ +/* + * Copyright (C) 2022 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 "string" + +#include "cert_chain_validator.h" +#include "blob.h" +#include "object_base.h" +#include "result.h" + +using namespace std; +using namespace testing::ext; + +class CertChainValidatorTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +constexpr int32_t CERT_HEADER_LEN = 2; + +static char g_caCert[] = +"-----BEGIN CERTIFICATE-----\r\n" +"MIIFwTCCA6mgAwIBAgIUBfKGru//yxvdRovc8iW9U9dzgqMwDQYJKoZIhvcNAQEL\r\n" +"BQAwbzELMAkGA1UEBhMCQ0kxCzAJBgNVBAgMAmhuMQswCQYDVQQHDAJzaDELMAkG\r\n" +"A1UECgwCaGgxCzAJBgNVBAsMAmlpMQswCQYDVQQDDAJhYjEfMB0GCSqGSIb3DQEJ\r\n" +"ARYQY3J5cHRvQGhlbGxvLmNvbTAgFw0yMjA4MjAxMjIyMzZaGA8yMDYyMDgyMDEy\r\n" +"MjIzNlowbzELMAkGA1UEBhMCQ0kxCzAJBgNVBAgMAmhuMQswCQYDVQQHDAJzaDEL\r\n" +"MAkGA1UECgwCaGgxCzAJBgNVBAsMAmlpMQswCQYDVQQDDAJhYjEfMB0GCSqGSIb3\r\n" +"DQEJARYQY3J5cHRvQGhlbGxvLmNvbTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCC\r\n" +"AgoCggIBAOXkcX7cHglTySl4XmjwMhiyxhMQUSTnZtAyjIiudyJmr9q6Ci8OXGTz\r\n" +"yPKmvDejwKcWqwYNpSJstwLUl7o8nFgIJmC9zkQ2ZwdEr5gDNehuR9nNjD55tVKD\r\n" +"68svuLGEWbyFI9AL8p578VPTex18KnLYTnJzYu2rVslFNBzQFVNyFPGhbN/ZEcnE\r\n" +"ICW4qFovuqNdWH/R9wuyilF08CJjBdXAfFvukooleM3Ip/FNSNb0ygs9N+GnxKuw\r\n" +"xybcgC/qZlPHtnl03ebI7/gRgL863E7SZR1lDIMFQ35+Z+TcM4SPqbokNr+nCiUV\r\n" +"hmTW56rZJSLDDKvzHzSbon1atd7bjjWWDA/FkUZtvjrP+IVHe+McOS1pDxUOyUv6\r\n" +"2YiRD6UkHADAqK0shEo/ejbd92CRbobVLapY9GJ0VOolE061PeNDiy/cMI1ihhbB\r\n" +"bq6S5YN/mnjgn0ylDD/6SA4rcc8Pep7ubXSVzhp/mugkJltDvYWoTO8rtZJryqP7\r\n" +"hehpJ8lZ1sGjlBE+1H4673wqx+HeGToGpBwrXM+3mKa27KDMtSRt0CvLuycR1SIW\r\n" +"FmZXy8n8eVemeA4d9flSYak2Mv5PPXttpSM58rylI2BoSTJgxN/j1tE1Lo8hadwp\r\n" +"i5g68H0Fd19HONd+LFxAhpgJ2ZUJb3qoGypEy1J322FCq6djIrIXAgMBAAGjUzBR\r\n" +"MB0GA1UdDgQWBBRH2csGuD+kwo6tU03rVbR5dtBhfjAfBgNVHSMEGDAWgBRH2csG\r\n" +"uD+kwo6tU03rVbR5dtBhfjAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUA\r\n" +"A4ICAQCovX+y4fN27gjPZuT1x8Lbm1c6UPcraWOUx5fQq7gpbxGhkWvcNWDEM6FD\r\n" +"9bNIT3oA0YiiUqPVOG+2pYiDEwsQJbwgrHZmQIYaufMZevO+a5I4u6FHttj05/ju\r\n" +"Z/j5xVECUWIpGFIl+q9U8B5dZ7GbI5zMNZ+k1/KWt+6x5zqRYU1ysxlxITokVfzq\r\n" +"Bu/DtMGqsrw36FqGEVUc0kYHGW9gwsNLXmw+YMpQMinAOE8uU0Pw8wtQeX9UcA+b\r\n" +"UdP4v9R7YkEtE3rfUCZ1pilEEB5XoklOPn6HYwAhrSB8gb1Ar8gmLUcbO0BT85yS\r\n" +"oPLJcw/m8XFC8Dj9ZFU25ux4lhvwmRs9HFFcBUJtYxB13UdfqlFTAlZdtPWi00IQ\r\n" +"C7MujV0ijoR6PnntwpBhLHIry1XZxzkrHmuJGQuZO7Taf9FyblrydIprkRyLZRSj\r\n" +"r3j1va/amhZZZeKZu1A8KLmTK/VF1IU8f9vMBbmrI6Rx0hgmwOr4kVexDdKyhuZw\r\n" +"U0u0HqJMJR1Vin93IFMRE63hjNno3NPL7d0mlhmwjEywrY0MmXYiQ6ag8o0PYAXg\r\n" +"Nr8NxOEvBY7ZOkWd2deJIyARDEc9nPcY46MiwowJ6bPMVPCXYGOxSfRpvY5SEjgj\r\n" +"llVnK3ULIM3AfVqDe7n3GnD4pHbHZQPLGpq0bQH9JUnCraB60g==\r\n" +"-----END CERTIFICATE-----\r\n"; + +static char g_secondCaCert[] = +"-----BEGIN CERTIFICATE-----\r\n" +"MIIFvDCCA6SgAwIBAgIUZDZSgan7tFvmeMmUD80kk+opOZwwDQYJKoZIhvcNAQEL\r\n" +"BQAwbzELMAkGA1UEBhMCQ0kxCzAJBgNVBAgMAmhuMQswCQYDVQQHDAJzaDELMAkG\r\n" +"A1UECgwCaGgxCzAJBgNVBAsMAmlpMQswCQYDVQQDDAJhYjEfMB0GCSqGSIb3DQEJ\r\n" +"ARYQY3J5cHRvQGhlbGxvLmNvbTAeFw0yMjA4MjAxMjI4MDhaFw00MjA4MjAxMjI4\r\n" +"MDhaMHwxCzAJBgNVBAYTAkNOMQ4wDAYDVQQIDAVIVU5BTjERMA8GA1UEBwwIU0hB\r\n" +"R05IQUkxCzAJBgNVBAoMAmhoMQswCQYDVQQLDAJpaTEPMA0GA1UEAwwGYXV0aG9y\r\n" +"MR8wHQYJKoZIhvcNAQkBFhBjcnlwdG9AaGVsbG8uY29tMIICIjANBgkqhkiG9w0B\r\n" +"AQEFAAOCAg8AMIICCgKCAgEAuSVyrlsC5nO+64mTYGAVJb1bdRJhz7ATMy2CE2AC\r\n" +"yo/RAl2p4Yoz8uJ6U23Ip4F+HmAGqXnIRGezwb+U1XaMkxX6WJQybngbYhdJX0As\r\n" +"rElz2CZsh0ZE9bsfAakpMtSrCm7RCucHxDD9R6WDWO2p3ARq8QbmLPk6M0tl9Ibo\r\n" +"4y/nJ84rvNfEkjgVNnWh3JLJ8a9OnaPBm+3j/1fPhzcTAo5VAXzEcUomxoV/JZdU\r\n" +"Dc0uFjqVeG9svMEx0dbn/xYrPm3OygmNjmbwuWkU9wx1aBDB0k5EwZ2pEagus7Wb\r\n" +"Qx37MryvLIMZIlOfqCnygwi478FLD2Ml0+1S/3VQR8S4MptlPrlpfNtkFuh5In/l\r\n" +"EgN340I8cdQfv4ZFlZ1BcFhz09MYJFo+toQm62umoZFBdH76wy634FGb1JlhJv6v\r\n" +"MguyM8QUTYsF9NBLXKqT5GtuiK4paqwwiNz/mu7ulfxAwKh2u5Jiw0xd+QCNNk3d\r\n" +"i3Kchx0ZtomjvmHQh57OZRRfO3lNplnujd9/4oloP+N4xGZ9Uknw9KH+Xx0VZy68\r\n" +"1luyaW2BtEKc3K5vcFBAt8FSSAYp9/bJbqfXNIDLPJogQ8EKsccOfs/IiMDP3Wgt\r\n" +"T3v1Cr76z+dbBo05fHew3n2Y5STCnxnxxth/jo59bO6IeUhN+kfnnKGA7uxwPppk\r\n" +"/CECAwEAAaNDMEEwDAYDVR0TBAUwAwEB/zAxBgNVHR8EKjAoMCagJKAihiBodHRw\r\n" +"czovL2NhLnhpZXhpYW5iaW4uY24vY3JsLnBlbTANBgkqhkiG9w0BAQsFAAOCAgEA\r\n" +"KVB7IIZ2WHSvRLnkMkaDdIu37l60VMhj79MfOTTI/0CcZ0p8G+fqOKGTCtOTFLfz\r\n" +"nXCgDOYH9F5tugLLd9B7FiLys5eBdXRym22BHs/jtzUXFrxSFWBhxvW0cwCwy59g\r\n" +"5c/vX3QcvliJfjaLq67CwHIdKlKocogJp1qeROy7HfLQMQJHE/Fc30QZXp5bJcmg\r\n" +"KDYGdvrgKGpzgf4zjOYH+OMhwB2G9Nd6en7TCihq3A8HiGj+M3OzrKgWR4qiHmPg\r\n" +"3SX7njPLPVerly+o8oh2pSwxSLQMKgPHpbvMHIr5vRIAklGg2TP7WV5+Wc+MC+Ls\r\n" +"fZ5M7WSZWD6BV2XIHA2iM3N7wYzvH0lNlgR1Pu8vhflPfSjFouILbEHnsokHPsUd\r\n" +"bxnNmOyMpCDCg3cjuZYIyjAIB/OoADAekAHX3cAitBBzzD9MBK/UXRkMded6JVwf\r\n" +"bZGq+2LLNzXzqMWQeCcGocRHiV+7uw3klLANfF9NyXvW6FYN50LhnoroGwsuGetY\r\n" +"22F/8s1N0oC7Ucn/JmZUA9xjaCDEeoTDoefv8/3zSr2sR6wR7hIHgvC9NNOTzdSS\r\n" +"Rqc3AfUz90kdsAoZowql7CrZy7LiqzaJMy1F+2H8jmzfCV6DBaCYgzlBGS/dq/Q7\r\n" +"A9kbZrfCeb/yEgz0h0LrWnBWww7r2T+Hk4LQ/jLtC1Q=\r\n" +"-----END CERTIFICATE-----\r\n"; + +static char g_invalidCaCert[] = +"-----BEGIN CERTIFICATE-----\r\n" +"MIIFwTCCA6mgAwIBAgIUBQorsmfkw1hrf85bkGSOiJLFCfYwDQYJKoZIhvcNAQEL\r\n" +"BQAwezELMAkGA1UEBhMCQ04xETAPBgNVBAgMCFNIQU5HSEFJMREwDwYDVQQHDAhT\r\n" +"SEFOR0hBSTELMAkGA1UECgwCQUExCzAJBgNVBAsMAkJCMQswCQYDVQQDDAJDQzEf\r\n" +"MB0GCSqGSIb3DQEJARYQc2Vjb25kQGhlbGxvLmNvbTAeFw0yMjA4MjMxMTM4NDNa\r\n" +"Fw00MjA4MjMxMTM4NDNaMHoxCzAJBgNVBAYTAkNBMREwDwYDVQQIDAhTSEFOR0hB\r\n" +"STERMA8GA1UEBwwIU0hBTkdIQUkxCzAJBgNVBAoMAkFBMQswCQYDVQQLDAJCQjEL\r\n" +"MAkGA1UEAwwCQ0MxHjAcBgkqhkiG9w0BCQEWD3RoaXJkQGhlbGxvLmNvbTCCAiIw\r\n" +"DQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMoRJDPA4mVDVgO7TGQqFZh4OxbV\r\n" +"uGaYmlEIVMwadsjA16l7xKB25bX7WmzHVDgZaJ0zJIyxbXXKvlmELS4mqDVmHUhh\r\n" +"sDHM+N00LVjV70F0xjaMRb1s6hOWlQ8Y314iDjW+c1lcHhWFliXqIp2Y7/c2QNKH\r\n" +"cRd+cqBzR45a9axHQTxS5ajTmLBSSAuSi3u1uVnA7BE7e0i0WSiISOtWiKoqG/R4\r\n" +"o+6llKg68LY0zHdWPyHn6F3aTvP+OJN+NHM+2onovpujDI28sTMRKeT92h/Ubf+s\r\n" +"q+kD25ADBZbq5kOXKq2m2jyh3RHSrxoPRyVUCFfWeqJk2ZUyOleHqV+orOCvTM37\r\n" +"LfbgIG6vchwMRnZHNBYWIm0BYkyo+O9wFV2+wC9iQwk/k+st9sQYNNwH6C2gzNnQ\r\n" +"WHgEYbGRSiUYsyXvkoUjw2gsBZJHjtKBNEqVwUA+yapbVRPsIPnzMr2IcLj9K2LM\r\n" +"FxOtpuliUjg/pqb4r5m83ZJQDBT3mvJr3NWbzbFKhqIaZyjjacCWr0vaumRsryEz\r\n" +"FwOVUZoPvLz/CgTAOAoouxGPs7qJhXb5CtXLdC15U9IEtsP88SExFa4gvO9nZPHE\r\n" +"HW9rc8/kppulsPGEDeZxYonGnk8l55ORqjmxcUQnWxWG1sqz4oTwUifWf9cybwMS\r\n" +"PpDQ4piAyncWY2jbAgMBAAGjPjA8MAwGA1UdEwQFMAMBAf8wLAYDVR0fBCUwIzAh\r\n" +"oB+gHYYbaHR0cHM6Ly9jYS50aGlyZC5jbi9jcmwucGVtMA0GCSqGSIb3DQEBCwUA\r\n" +"A4ICAQA0CP5FEccMxxd83S0IL5uwNCPPBzN3qHGZWm1PJD4dvbzsB5AtWbhDvfvD\r\n" +"GQRvfH83t3701U2J7wAUuFgG8UCNVKLSLfSv3Gqo5wKhEnZcoE0KZot56IA+lwVe\r\n" +"LfwAYgrzPMOWl1pyQ/BE5BcKthS/7OTH7qdNHc0J59xsanKFU9jnGEjfZv14XSRo\r\n" +"/iCM9ZIb4tVETnGFVfjp3Rjgnw2OZjdJcfVLIF/zTlkkGOQLqfyJqoafy0MIuM/k\r\n" +"nosPXJHX7tqQs5+ckKhPRkBltGsoLv2HzoIGiiGLvFmulvkyUd9FDq8UwfetAKU6\r\n" +"BTO6ZkjeS0S+2SBZ29Hm5F2xMoQjTtzYkmxCxbhFkAF2SWvR+hVXoOsAgG2csU15\r\n" +"ef+IgUw1aX7RK2OxYEYvX9BFLaoc8zima+ZzUbScZznVsyPGLZl+7tiOkQVFUSOY\r\n" +"F2TJqRXT8Obb0gQ1rHfU+ilDuP3+eUuUFfmzInqXTkGDArDEkwKoHezXgHhsvLTu\r\n" +"vBYSV/GOZHduz4WmiPQri3CkntSe4/JWeYoJHD+IWBO/Czvh6nNOciRxZSif917h\r\n" +"FQ6og3z/5CyHLd7EWKX/CwUqZ0jmGUdGoaO5i7xTeVzYGpkPzoTTRUv2T/go3roE\r\n" +"3hd5yG48AaYNKhJ26auBrOARpJe/ktKZTMuU3zHuPRtv3Wtdiw==\r\n" +"-----END CERTIFICATE-----\r\n"; + +void CertChainValidatorTest::SetUpTestCase() {} +void CertChainValidatorTest::TearDownTestCase() {} + +void CertChainValidatorTest::SetUp() +{ +} + +void CertChainValidatorTest::TearDown() +{ +} + +HWTEST_F(CertChainValidatorTest, GetAlgorithm001, TestSize.Level0) +{ + HcfCertChainValidator *pathValidator = nullptr; + HcfResult res = HcfCertChainValidatorCreate("PKIX", &pathValidator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(pathValidator, nullptr); + const char *algo = pathValidator->getAlgorithm(pathValidator); + EXPECT_NE(algo, nullptr); + if (algo == nullptr) { + OH_HCF_ObjDestroy(pathValidator); + return; + } + string st("PKIX"); + ASSERT_STREQ(algo, st.c_str()); + OH_HCF_ObjDestroy(pathValidator); +} + +HWTEST_F(CertChainValidatorTest, GetAlgorithm002, TestSize.Level0) +{ + HcfCertChainValidator *pathValidator = nullptr; + HcfResult res = HcfCertChainValidatorCreate("invalidPKIX", &pathValidator); + EXPECT_EQ(res, HCF_NOT_SUPPORT); + EXPECT_EQ(pathValidator, nullptr); +} + +/* valid cert chain. */ +HWTEST_F(CertChainValidatorTest, VerifyTest001, TestSize.Level0) +{ + HcfCertChainValidator *pathValidator = nullptr; + HcfResult res = HcfCertChainValidatorCreate("PKIX", &pathValidator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(pathValidator, nullptr); + HcfCertChainData certsData = { 0 }; + certsData.format = HCF_FORMAT_PEM; + certsData.count = 2; /* level-2 cert chain. */ + uint32_t caCertLen = strlen(g_caCert) + 1; + uint32_t secondCaCertLen = strlen(g_secondCaCert) + 1; + certsData.dataLen = CERT_HEADER_LEN + secondCaCertLen + CERT_HEADER_LEN + caCertLen; + certsData.data = (uint8_t *)malloc(certsData.dataLen); + if (certsData.data == nullptr) { + return; + } + if (memcpy_s(certsData.data, CERT_HEADER_LEN + secondCaCertLen + CERT_HEADER_LEN + caCertLen, + &secondCaCertLen, CERT_HEADER_LEN) != EOK) { + goto OUT; + } + if (memcpy_s(certsData.data + CERT_HEADER_LEN, secondCaCertLen + CERT_HEADER_LEN + caCertLen, + g_secondCaCert, secondCaCertLen) != EOK) { + goto OUT; + } + if (memcpy_s(certsData.data + CERT_HEADER_LEN + secondCaCertLen, CERT_HEADER_LEN + caCertLen, + &caCertLen, CERT_HEADER_LEN) != EOK) { + goto OUT; + } + if (memcpy_s(certsData.data + CERT_HEADER_LEN + secondCaCertLen + CERT_HEADER_LEN, caCertLen, + g_caCert, caCertLen) != EOK) { + goto OUT; + } + + res = pathValidator->validate(pathValidator, &certsData); + EXPECT_EQ(res, HCF_SUCCESS); +OUT: + free(certsData.data); + OH_HCF_ObjDestroy(pathValidator); +} + +/* invalid cert chain. */ +HWTEST_F(CertChainValidatorTest, VerifyTest002, TestSize.Level0) +{ + HcfCertChainValidator *pathValidator = nullptr; + HcfResult res = HcfCertChainValidatorCreate("PKIX", &pathValidator); + EXPECT_EQ(res, HCF_SUCCESS); + EXPECT_NE(pathValidator, nullptr); + HcfCertChainData certsData = { 0 }; + certsData.format = HCF_FORMAT_PEM; + certsData.count = 3; /* level-3 cert chain. */ + uint32_t caCertLen = strlen(g_caCert) + 1; + uint32_t secondCaCertLen = strlen(g_secondCaCert) + 1; + uint32_t thirdCertLen = strlen(g_invalidCaCert) + 1; + certsData.dataLen = CERT_HEADER_LEN + thirdCertLen + CERT_HEADER_LEN + + secondCaCertLen + CERT_HEADER_LEN + caCertLen; + certsData.data = (uint8_t *)malloc(certsData.dataLen); + EXPECT_NE(certsData.data, nullptr); + if (certsData.data == nullptr) { + return; + } + if (memcpy_s(certsData.data, + CERT_HEADER_LEN + thirdCertLen + CERT_HEADER_LEN + secondCaCertLen + CERT_HEADER_LEN + caCertLen, + &thirdCertLen, CERT_HEADER_LEN) != EOK) { + goto OUT; + } + if (memcpy_s(certsData.data + CERT_HEADER_LEN, + thirdCertLen + CERT_HEADER_LEN + secondCaCertLen + CERT_HEADER_LEN + caCertLen, + g_invalidCaCert, thirdCertLen) != EOK) { + return; + } + if (memcpy_s(certsData.data + CERT_HEADER_LEN + thirdCertLen, + CERT_HEADER_LEN + secondCaCertLen + CERT_HEADER_LEN + caCertLen, &secondCaCertLen, CERT_HEADER_LEN) != EOK) { + goto OUT; + } + if (memcpy_s(certsData.data + CERT_HEADER_LEN + thirdCertLen + CERT_HEADER_LEN, + secondCaCertLen + CERT_HEADER_LEN + caCertLen, g_secondCaCert, secondCaCertLen) != EOK) { + goto OUT; + } + if (memcpy_s(certsData.data + CERT_HEADER_LEN + thirdCertLen + CERT_HEADER_LEN + secondCaCertLen, + CERT_HEADER_LEN + caCertLen, &caCertLen, CERT_HEADER_LEN) != EOK) { + goto OUT; + } + if (memcpy_s(certsData.data + CERT_HEADER_LEN + thirdCertLen + CERT_HEADER_LEN + secondCaCertLen + CERT_HEADER_LEN, + caCertLen, g_caCert, caCertLen) != EOK) { + goto OUT; + } + + res = pathValidator->validate(pathValidator, &certsData); + EXPECT_NE(res, HCF_SUCCESS); +OUT: + free(certsData.data); + OH_HCF_ObjDestroy(pathValidator); +} \ No newline at end of file