From 7c2ec644e84eb9dd2d5d045881368f339fa1af5c Mon Sep 17 00:00:00 2001 From: xwb Date: Tue, 16 May 2023 15:45:52 +0800 Subject: [PATCH] review rand &NAPI Signed-off-by: xwb --- common/inc/config.h | 2 +- frameworks/crypto_operation/mac.c | 4 +- frameworks/crypto_operation/md.c | 4 +- frameworks/{rand => crypto_operation}/rand.c | 26 +- .../inc/napi_cert_chain_validator.h | 2 +- .../napi/certificate/inc/napi_cert_defines.h | 2 +- .../certificate/inc/napi_x509_certificate.h | 2 +- .../js/napi/certificate/inc/napi_x509_crl.h | 2 +- .../certificate/inc/napi_x509_crl_entry.h | 2 +- .../src/napi_cert_chain_validator.cpp | 2 +- .../certificate/src/napi_x509_certificate.cpp | 2 +- .../js/napi/certificate/src/napi_x509_crl.cpp | 2 +- .../certificate/src/napi_x509_crl_entry.cpp | 2 +- frameworks/js/napi/crypto/inc/napi_mac.h | 17 +- frameworks/js/napi/crypto/inc/napi_md.h | 15 +- frameworks/js/napi/crypto/inc/napi_rand.h | 13 +- frameworks/js/napi/crypto/src/napi_init.cpp | 131 +++++- frameworks/js/napi/crypto/src/napi_mac.cpp | 415 ++++++++++-------- frameworks/js/napi/crypto/src/napi_md.cpp | 345 +++++++++------ frameworks/js/napi/crypto/src/napi_rand.cpp | 255 +++++++---- .../js/napi/crypto/src/napi_sym_key.cpp | 2 +- .../crypto/src/napi_sym_key_generator.cpp | 62 +-- frameworks/key/sym_key_generator.c | 6 +- frameworks/spi/rand_spi.h | 6 +- .../{rand => crypto_operation}/rand.h | 2 + .../certificate/src/x509_crl_openssl.c | 2 +- .../{aes => cipher}/inc/aes_openssl.h | 0 .../{rsa => cipher}/inc/cipher_rsa_openssl.h | 0 .../{aes => cipher}/src/cipher_3des_openssl.c | 68 +-- .../{aes => cipher}/src/cipher_aes_common.c | 3 +- .../{aes => cipher}/src/cipher_aes_openssl.c | 264 ++++++----- .../crypto_operation/hmac/src/mac_openssl.c | 25 +- .../crypto_operation/md/src/md_openssl.c | 27 +- .../rand/inc/rand_openssl.h | 0 .../rand/src/rand_openssl.c | 24 +- .../rsa/src/cipher_rsa_openssl.c | 338 -------------- .../sym_key_generator/src/sym_key_openssl.c | 10 +- 37 files changed, 1043 insertions(+), 1041 deletions(-) rename frameworks/{rand => crypto_operation}/rand.c (83%) rename interfaces/innerkits/{rand => crypto_operation}/rand.h (95%) rename plugin/openssl_plugin/crypto_operation/{aes => cipher}/inc/aes_openssl.h (100%) rename plugin/openssl_plugin/crypto_operation/{rsa => cipher}/inc/cipher_rsa_openssl.h (100%) rename plugin/openssl_plugin/crypto_operation/{aes => cipher}/src/cipher_3des_openssl.c (81%) rename plugin/openssl_plugin/crypto_operation/{aes => cipher}/src/cipher_aes_common.c (96%) rename plugin/openssl_plugin/crypto_operation/{aes => cipher}/src/cipher_aes_openssl.c (75%) rename plugin/openssl_plugin/{ => crypto_operation}/rand/inc/rand_openssl.h (100%) rename plugin/openssl_plugin/{ => crypto_operation}/rand/src/rand_openssl.c (81%) delete mode 100644 plugin/openssl_plugin/crypto_operation/rsa/src/cipher_rsa_openssl.c diff --git a/common/inc/config.h b/common/inc/config.h index cefcd5f..7dbe5f6 100644 --- a/common/inc/config.h +++ b/common/inc/config.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022 Huawei Device Co., Ltd. + * Copyright (C) 2022-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/frameworks/crypto_operation/mac.c b/frameworks/crypto_operation/mac.c index 819cec0..22e1bb9 100644 --- a/frameworks/crypto_operation/mac.c +++ b/frameworks/crypto_operation/mac.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022 Huawei Device Co., Ltd. + * Copyright (C) 2022-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -168,7 +168,7 @@ HcfResult HcfMacCreate(const char *algoName, HcfMac **mac) if (strcpy_s(returnMacApi->algoName, HCF_MAX_ALGO_NAME_LEN, algoName) != EOK) { LOGE("Failed to copy algoName!"); HcfFree(returnMacApi); - return HCF_ERR_COPY; + return HCF_INVALID_PARAMS; } HcfMacSpi *spiObj = NULL; HcfResult res = createSpiFunc(algoName, &spiObj); diff --git a/frameworks/crypto_operation/md.c b/frameworks/crypto_operation/md.c index fdc1d45..ed231ce 100644 --- a/frameworks/crypto_operation/md.c +++ b/frameworks/crypto_operation/md.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022 Huawei Device Co., Ltd. + * Copyright (C) 2022-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -156,7 +156,7 @@ HcfResult HcfMdCreate(const char *algoName, HcfMd **md) if (strcpy_s(returnMdApi->algoName, HCF_MAX_ALGO_NAME_LEN, algoName) != EOK) { LOGE("Failed to copy algoName!"); HcfFree(returnMdApi); - return HCF_ERR_COPY; + return HCF_INVALID_PARAMS; } HcfMdSpi *spiObj = NULL; HcfResult res = createSpiFunc(algoName, &spiObj); diff --git a/frameworks/rand/rand.c b/frameworks/crypto_operation/rand.c similarity index 83% rename from frameworks/rand/rand.c rename to frameworks/crypto_operation/rand.c index 5bbd0cd..0cb464d 100644 --- a/frameworks/rand/rand.c +++ b/frameworks/crypto_operation/rand.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022 Huawei Device Co., Ltd. + * Copyright (C) 2022-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -14,6 +14,8 @@ */ #include "rand.h" + +#include #include #include "rand_spi.h" #include "rand_openssl.h" @@ -60,10 +62,14 @@ static HcfRandSpiCreateFunc FindAbility(const char *algoName) static HcfResult GenerateRandom(HcfRand *self, int32_t numBytes, HcfBlob *random) { - if ((self == NULL) || (numBytes <= 0) || (numBytes > HCF_MAX_BUFFER_LEN) || (random == NULL)) { + if ((self == NULL) || (random == NULL)) { LOGE("Invalid params!"); return HCF_INVALID_PARAMS; } + if ((numBytes <= 0) || (numBytes > INT_MAX)) { + LOGE("Invalid numBytes!"); + return HCF_INVALID_PARAMS; + } if (!IsClassMatch((HcfObjectBase *)self, GetRandClass())) { LOGE("Class is not match."); return HCF_INVALID_PARAMS; @@ -72,9 +78,22 @@ static HcfResult GenerateRandom(HcfRand *self, int32_t numBytes, HcfBlob *random ((HcfRandImpl *)self)->spiObj, numBytes, random); } +static const char *GetAlgoName(HcfRand *self) +{ + if (self == NULL) { + LOGE("The input self ptr is NULL!"); + return NULL; + } + if (!IsClassMatch((HcfObjectBase *)self, GetRandClass())) { + LOGE("Class is not match!"); + return NULL; + } + return ((HcfRandImpl *)self)->spiObj->engineGetAlgoName(((HcfRandImpl *)self)->spiObj); +} + static HcfResult SetSeed(HcfRand *self, HcfBlob *seed) { - if ((self == NULL) || (!IsBlobValid(seed)) || (seed->len > HCF_MAX_BUFFER_LEN)) { + if ((self == NULL) || (!IsBlobValid(seed)) || (seed->len > INT_MAX)) { LOGE("The input self ptr is NULL!"); return HCF_INVALID_PARAMS; } @@ -128,6 +147,7 @@ HcfResult HcfRandCreate(HcfRand **random) returnRandApi->base.base.getClass = GetRandClass; returnRandApi->base.base.destroy = HcfRandDestroy; returnRandApi->base.generateRandom = GenerateRandom; + returnRandApi->base.getAlgoName = GetAlgoName; returnRandApi->base.setSeed = SetSeed; returnRandApi->spiObj = spiObj; *random = (HcfRand *)returnRandApi; diff --git a/frameworks/js/napi/certificate/inc/napi_cert_chain_validator.h b/frameworks/js/napi/certificate/inc/napi_cert_chain_validator.h index a58c2af..7208820 100644 --- a/frameworks/js/napi/certificate/inc/napi_cert_chain_validator.h +++ b/frameworks/js/napi/certificate/inc/napi_cert_chain_validator.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * 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 diff --git a/frameworks/js/napi/certificate/inc/napi_cert_defines.h b/frameworks/js/napi/certificate/inc/napi_cert_defines.h index dbf22e4..2c83466 100644 --- a/frameworks/js/napi/certificate/inc/napi_cert_defines.h +++ b/frameworks/js/napi/certificate/inc/napi_cert_defines.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023 Huawei Device Co., Ltd. + * Copyright (C) 2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/frameworks/js/napi/certificate/inc/napi_x509_certificate.h b/frameworks/js/napi/certificate/inc/napi_x509_certificate.h index 7b69c46..c68fb06 100644 --- a/frameworks/js/napi/certificate/inc/napi_x509_certificate.h +++ b/frameworks/js/napi/certificate/inc/napi_x509_certificate.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * 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 diff --git a/frameworks/js/napi/certificate/inc/napi_x509_crl.h b/frameworks/js/napi/certificate/inc/napi_x509_crl.h index cce8bcd..c46bc07 100644 --- a/frameworks/js/napi/certificate/inc/napi_x509_crl.h +++ b/frameworks/js/napi/certificate/inc/napi_x509_crl.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * 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 diff --git a/frameworks/js/napi/certificate/inc/napi_x509_crl_entry.h b/frameworks/js/napi/certificate/inc/napi_x509_crl_entry.h index 2d8f97e..190aae7 100644 --- a/frameworks/js/napi/certificate/inc/napi_x509_crl_entry.h +++ b/frameworks/js/napi/certificate/inc/napi_x509_crl_entry.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * 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 diff --git a/frameworks/js/napi/certificate/src/napi_cert_chain_validator.cpp b/frameworks/js/napi/certificate/src/napi_cert_chain_validator.cpp index b5c747d..2367237 100644 --- a/frameworks/js/napi/certificate/src/napi_cert_chain_validator.cpp +++ b/frameworks/js/napi/certificate/src/napi_cert_chain_validator.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (C) 2022-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/frameworks/js/napi/certificate/src/napi_x509_certificate.cpp b/frameworks/js/napi/certificate/src/napi_x509_certificate.cpp index bbe1da3..94c9688 100644 --- a/frameworks/js/napi/certificate/src/napi_x509_certificate.cpp +++ b/frameworks/js/napi/certificate/src/napi_x509_certificate.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (C) 2022-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/frameworks/js/napi/certificate/src/napi_x509_crl.cpp b/frameworks/js/napi/certificate/src/napi_x509_crl.cpp index 7c788f9..c62024f 100644 --- a/frameworks/js/napi/certificate/src/napi_x509_crl.cpp +++ b/frameworks/js/napi/certificate/src/napi_x509_crl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (C) 2022-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/frameworks/js/napi/certificate/src/napi_x509_crl_entry.cpp b/frameworks/js/napi/certificate/src/napi_x509_crl_entry.cpp index f43ef9c..11bd3a8 100644 --- a/frameworks/js/napi/certificate/src/napi_x509_crl_entry.cpp +++ b/frameworks/js/napi/certificate/src/napi_x509_crl_entry.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * 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 diff --git a/frameworks/js/napi/crypto/inc/napi_mac.h b/frameworks/js/napi/crypto/inc/napi_mac.h index 3e979f9..133de48 100644 --- a/frameworks/js/napi/crypto/inc/napi_mac.h +++ b/frameworks/js/napi/crypto/inc/napi_mac.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * 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 @@ -30,21 +30,18 @@ class NapiMac { public: explicit NapiMac(HcfMac *macObj); ~NapiMac(); + HcfMac *GetMac(); + static thread_local 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_; - } + static napi_value JsMacInit(napi_env env, napi_callback_info info); + static napi_value JsMacUpdate(napi_env env, napi_callback_info info); + static napi_value JsMacDoFinal(napi_env env, napi_callback_info info); + static napi_value JsGetMacLength(napi_env env, napi_callback_info info); private: HcfMac *macObj_ = nullptr; diff --git a/frameworks/js/napi/crypto/inc/napi_md.h b/frameworks/js/napi/crypto/inc/napi_md.h index 50f5d49..0e97c09 100644 --- a/frameworks/js/napi/crypto/inc/napi_md.h +++ b/frameworks/js/napi/crypto/inc/napi_md.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * 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 @@ -30,20 +30,17 @@ class NapiMd { public: explicit NapiMd(HcfMd *mdObj); ~NapiMd(); + HcfMd *GetMd(); + static thread_local 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_; - } + static napi_value JsMdUpdate(napi_env env, napi_callback_info info); + static napi_value JsMdDoFinal(napi_env env, napi_callback_info info); + static napi_value JsGetMdLength(napi_env env, napi_callback_info info); private: HcfMd *mdObj_ = nullptr; diff --git a/frameworks/js/napi/crypto/inc/napi_rand.h b/frameworks/js/napi/crypto/inc/napi_rand.h index 927ada8..5858ab0 100644 --- a/frameworks/js/napi/crypto/inc/napi_rand.h +++ b/frameworks/js/napi/crypto/inc/napi_rand.h @@ -30,19 +30,18 @@ class NapiRand { public: explicit NapiRand(HcfRand *randObj); ~NapiRand(); + HcfRand *GetRand(); + static thread_local 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_; - } + static napi_value JsGetAlgorithm(napi_env env, napi_callback_info info); + static napi_value JsGenerateRandom(napi_env env, napi_callback_info info); + static napi_value JsGenerateRandomSync(napi_env env, napi_callback_info info); + static napi_value JsSetSeed(napi_env env, napi_callback_info info); private: HcfRand *randObj_ = nullptr; diff --git a/frameworks/js/napi/crypto/src/napi_init.cpp b/frameworks/js/napi/crypto/src/napi_init.cpp index b5932dc..7d9da1c 100644 --- a/frameworks/js/napi/crypto/src/napi_init.cpp +++ b/frameworks/js/napi/crypto/src/napi_init.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022 Huawei Device Co., Ltd. + * Copyright (C) 2022-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -17,6 +17,7 @@ #include "log.h" #include "napi_asy_key_generator.h" +#include "napi_asy_key_spec_generator.h" #include "napi_sym_key_generator.h" #include "napi_cipher.h" #include "napi_key_pair.h" @@ -32,13 +33,15 @@ #include "napi_key.h" #include "napi_utils.h" #include "napi_crypto_framework_defines.h" +#include "key.h" +#include "asy_key_params.h" namespace OHOS { namespace CryptoFramework { static napi_value CreateCryptoMode(napi_env env) { napi_value cryptoMode = nullptr; - napi_create_object(env, &cryptoMode); + NAPI_CALL(env, napi_create_object(env, &cryptoMode)); AddUint32Property(env, cryptoMode, "ENCRYPT_MODE", ENCRYPT_MODE); AddUint32Property(env, cryptoMode, "DECRYPT_MODE", DECRYPT_MODE); @@ -53,10 +56,11 @@ static void DefineCryptoModeProperties(napi_env env, napi_value exports) napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); } +// enum Result in JS static napi_value CreateResultCode(napi_env env) { napi_value resultCode = nullptr; - napi_create_object(env, &resultCode); + NAPI_CALL(env, napi_create_object(env, &resultCode)); AddUint32Property(env, resultCode, "INVALID_PARAMS", JS_ERR_INVALID_PARAMS); AddUint32Property(env, resultCode, "NOT_SUPPORT", JS_ERR_NOT_SUPPORT); @@ -75,6 +79,110 @@ static void DefineResultCodeProperties(napi_env env, napi_value exports) napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); } +// enum AsyKeySpecItem in JS +static napi_value CreateAsyKeySpecItemCode(napi_env env) +{ + napi_value code = nullptr; + NAPI_CALL(env, napi_create_object(env, &code)); + + AddUint32Property(env, code, "DSA_P_BN", DSA_P_BN); + AddUint32Property(env, code, "DSA_Q_BN", DSA_Q_BN); + AddUint32Property(env, code, "DSA_G_BN", DSA_G_BN); + AddUint32Property(env, code, "DSA_SK_BN", DSA_SK_BN); + AddUint32Property(env, code, "DSA_PK_BN", DSA_PK_BN); + + AddUint32Property(env, code, "ECC_FP_P_BN", ECC_FP_P_BN); + AddUint32Property(env, code, "ECC_A_BN", ECC_A_BN); + AddUint32Property(env, code, "ECC_B_BN", ECC_B_BN); + AddUint32Property(env, code, "ECC_G_X_BN", ECC_G_X_BN); + AddUint32Property(env, code, "ECC_G_Y_BN", ECC_G_Y_BN); + AddUint32Property(env, code, "ECC_N_BN", ECC_N_BN); + AddUint32Property(env, code, "ECC_H_NUM", ECC_H_INT); + AddUint32Property(env, code, "ECC_SK_BN", ECC_SK_BN); + AddUint32Property(env, code, "ECC_PK_X_BN", ECC_PK_X_BN); + AddUint32Property(env, code, "ECC_PK_Y_BN", ECC_PK_Y_BN); + AddUint32Property(env, code, "ECC_FIELD_TYPE_STR", ECC_FIELD_TYPE_STR); + AddUint32Property(env, code, "ECC_FIELD_SIZE_NUM", ECC_FIELD_SIZE_INT); + AddUint32Property(env, code, "ECC_CURVE_NAME_STR", ECC_CURVE_NAME_STR); + + AddUint32Property(env, code, "RSA_N_BN", RSA_N_BN); + AddUint32Property(env, code, "RSA_SK_BN", RSA_SK_BN); + AddUint32Property(env, code, "RSA_PK_BN", RSA_PK_BN); + return code; +} + +static void DefineAsyKeySpecItemProperties(napi_env env, napi_value exports) +{ + napi_property_descriptor desc[] = { + DECLARE_NAPI_PROPERTY("AsyKeySpecItem", CreateAsyKeySpecItemCode(env)), + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); +} + +// enum AsyKeySpecType in JS +static napi_value CreateAsyKeySpecTypeCode(napi_env env) +{ + napi_value code = nullptr; + NAPI_CALL(env, napi_create_object(env, &code)); + + AddUint32Property(env, code, "COMMON_PARAMS_SPEC", HCF_COMMON_PARAMS_SPEC); + AddUint32Property(env, code, "PRIVATE_KEY_SPEC", HCF_PRIVATE_KEY_SPEC); + AddUint32Property(env, code, "PUBLIC_KEY_SPEC", HCF_PUBLIC_KEY_SPEC); + AddUint32Property(env, code, "KEY_PAIR_SPEC", HCF_KEY_PAIR_SPEC); + return code; +} + +static void DefineAsyKeySpecTypeProperties(napi_env env, napi_value exports) +{ + napi_property_descriptor desc[] = { + DECLARE_NAPI_PROPERTY("AsyKeySpecType", CreateAsyKeySpecTypeCode(env)), + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); +} + +// enum CipherSpecItem in JS +static napi_value CreateCipherSpecItemCode(napi_env env) +{ + napi_value code = nullptr; + NAPI_CALL(env, napi_create_object(env, &code)); + + AddUint32Property(env, code, "OAEP_MD_NAME_STR", OAEP_MD_NAME_STR); + AddUint32Property(env, code, "OAEP_MGF_NAME_STR", OAEP_MGF_NAME_STR); + AddUint32Property(env, code, "OAEP_MGF1_MD_STR", OAEP_MGF1_MD_STR); + AddUint32Property(env, code, "OAEP_MGF1_PSRC_UINT8ARR", OAEP_MGF1_PSRC_UINT8ARR); + return code; +} + +static void DefineCipherSpecItemProperties(napi_env env, napi_value exports) +{ + napi_property_descriptor desc[] = { + DECLARE_NAPI_PROPERTY("CipherSpecItem", CreateCipherSpecItemCode(env)), + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); +} + +// enum SignSpecItem in JS +static napi_value CreateSignSpecItemCode(napi_env env) +{ + napi_value code = nullptr; + NAPI_CALL(env, napi_create_object(env, &code)); + + AddUint32Property(env, code, "PSS_MD_NAME_STR", PSS_MD_NAME_STR); + AddUint32Property(env, code, "PSS_MGF_NAME_STR", PSS_MGF_NAME_STR); + AddUint32Property(env, code, "PSS_MGF1_MD_STR", PSS_MGF1_MD_STR); + AddUint32Property(env, code, "PSS_SALT_LEN_NUM", PSS_SALT_LEN_INT); + AddUint32Property(env, code, "PSS_TRAILER_FIELD_NUM", PSS_TRAILER_FIELD_INT); + return code; +} + +static void DefineSignSpecItemProperties(napi_env env, napi_value exports) +{ + napi_property_descriptor desc[] = { + DECLARE_NAPI_PROPERTY("SignSpecItem", CreateSignSpecItemCode(env)), + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); +} + /*********************************************** * Module export and register ***********************************************/ @@ -84,10 +192,20 @@ static napi_value ModuleExport(napi_env env, napi_value exports) DefineCryptoModeProperties(env, exports); DefineResultCodeProperties(env, exports); - NapiAsyKeyGenerator::DefineAsyKeyGeneratorJSClass(env, exports); - NapiKeyPair::DefineKeyPairJSClass(env); + DefineAsyKeySpecItemProperties(env, exports); + DefineAsyKeySpecTypeProperties(env, exports); + DefineCipherSpecItemProperties(env, exports); + DefineSignSpecItemProperties(env, exports); + + NapiKey::DefineHcfKeyJSClass(env); NapiPubKey::DefinePubKeyJSClass(env); NapiPriKey::DefinePriKeyJSClass(env); + NapiKeyPair::DefineKeyPairJSClass(env); + NapiSymKey::DefineSymKeyJSClass(env); + + NapiAsyKeyGenerator::DefineAsyKeyGeneratorJSClass(env, exports); + NapiAsyKeyGeneratorBySpec::DefineAsyKeyGeneratorBySpecJSClass(env, exports); + NapiSymKeyGenerator::DefineSymKeyGeneratorJSClass(env, exports); NapiSign::DefineSignJSClass(env, exports); NapiVerify::DefineVerifyJSClass(env, exports); @@ -95,10 +213,7 @@ static napi_value ModuleExport(napi_env env, napi_value exports) NapiMac::DefineMacJSClass(env, exports); NapiMd::DefineMdJSClass(env, exports); NapiRand::DefineRandJSClass(env, exports); - NapiSymKeyGenerator::DefineSymKeyGeneratorJSClass(env, exports); NapiCipher::DefineCipherJSClass(env, exports); - NapiSymKey::DefineSymKeyJSClass(env); - NapiKey::DefineHcfKeyJSClass(env); LOGI("module init end."); return exports; } diff --git a/frameworks/js/napi/crypto/src/napi_mac.cpp b/frameworks/js/napi/crypto/src/napi_mac.cpp index 9fcbca6..ae3436e 100644 --- a/frameworks/js/napi/crypto/src/napi_mac.cpp +++ b/frameworks/js/napi/crypto/src/napi_mac.cpp @@ -30,13 +30,12 @@ thread_local napi_ref NapiMac::classRef_ = nullptr; struct MacCtx { napi_env env = nullptr; - CfAsyncType asyncType = ASYNC_TYPE_CALLBACK; + AsyncType asyncType = ASYNC_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; @@ -44,6 +43,7 @@ struct MacCtx { HcfResult errCode = HCF_SUCCESS; const char *errMsg = nullptr; HcfBlob *outBlob = nullptr; + HcfMac *mac = nullptr; }; static void FreeCryptoFwkCtx(napi_env env, MacCtx *context) @@ -75,6 +75,7 @@ static void FreeCryptoFwkCtx(napi_env env, MacCtx *context) context->outBlob = nullptr; } context->errMsg = nullptr; + context->mac = nullptr; HcfFree(context); context = nullptr; } @@ -106,39 +107,14 @@ static void ReturnPromiseResult(napi_env env, MacCtx *context, napi_value result } } -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() -{ - HcfObjDestroy(this->macObj_); -} - static void MacInitExecute(napi_env env, void *data) { MacCtx *context = static_cast(data); - NapiMac *macClass = context->macClass; - HcfMac *macObj = macClass->GetMac(); + HcfMac *macObj = context->mac; HcfSymKey *symKey = context->symKey; context->errCode = macObj->init(macObj, symKey); if (context->errCode != HCF_SUCCESS) { + napi_throw(env, GenerateBusinessError(env, context->errCode, "init failed!")); LOGE("init failed!"); context->errMsg = "init failed"; } @@ -149,7 +125,7 @@ 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) { + if (context->asyncType == ASYNC_CALLBACK) { ReturnCallbackResult(env, context, nullInstance); } else { ReturnPromiseResult(env, context, nullInstance); @@ -160,11 +136,11 @@ static void MacInitComplete(napi_env env, napi_status status, void *data) static void MacUpdateExecute(napi_env env, void *data) { MacCtx *context = static_cast(data); - NapiMac *macClass = context->macClass; - HcfMac *macObj = macClass->GetMac(); + HcfMac *macObj = context->mac; HcfBlob *inBlob = reinterpret_cast(context->inBlob); context->errCode = macObj->update(macObj, inBlob); if (context->errCode != HCF_SUCCESS) { + napi_throw(env, GenerateBusinessError(env, context->errCode, "update failed!")); LOGE("update failed!"); context->errMsg = "update failed"; } @@ -175,7 +151,7 @@ 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) { + if (context->asyncType == ASYNC_CALLBACK) { ReturnCallbackResult(env, context, nullInstance); } else { ReturnPromiseResult(env, context, nullInstance); @@ -186,10 +162,10 @@ static void MacUpdateComplete(napi_env env, napi_status status, void *data) static void MacDoFinalExecute(napi_env env, void *data) { MacCtx *context = static_cast(data); - NapiMac *macClass = context->macClass; - HcfMac *macObj = macClass->GetMac(); + HcfMac *macObj = context->mac; HcfBlob *outBlob = reinterpret_cast(HcfMalloc(sizeof(HcfBlob), 0)); if (outBlob == nullptr) { + napi_throw(env, GenerateBusinessError(env, HCF_ERR_MALLOC, "outBlob is null!")); LOGE("outBlob is null!"); context->errCode = HCF_ERR_MALLOC; context->errMsg = "malloc data blob failed"; @@ -197,10 +173,10 @@ static void MacDoFinalExecute(napi_env env, void *data) } context->errCode = macObj->doFinal(macObj, outBlob); if (context->errCode != HCF_SUCCESS) { + napi_throw(env, GenerateBusinessError(env, context->errCode, "doFinal failed!")); + HcfFree(outBlob); LOGE("doFinal failed!"); context->errMsg = "doFinal failed"; - HcfFree(outBlob); - outBlob = nullptr; return; } context->outBlob = outBlob; @@ -214,7 +190,7 @@ static void MacDoFinalComplete(napi_env env, napi_status status, void *data) LOGE("returnOutBlob is nullptr!"); returnOutBlob = NapiGetNull(env); } - if (context->asyncType == ASYNC_TYPE_CALLBACK) { + if (context->asyncType == ASYNC_CALLBACK) { ReturnCallbackResult(env, context, returnOutBlob); } else { ReturnPromiseResult(env, context, returnOutBlob); @@ -222,209 +198,310 @@ static void MacDoFinalComplete(napi_env env, napi_status status, void *data) FreeCryptoFwkCtx(env, context); } -napi_value NapiMac::MacInit(napi_env env, napi_callback_info info) +static bool BuildMacJsInitCtx(napi_env env, napi_callback_info info, MacCtx *context) { + napi_value thisVar = nullptr; + NapiMac *napiMac = nullptr; size_t expectedArgsCount = ARGS_SIZE_TWO; size_t argc = expectedArgsCount; napi_value argv[ARGS_SIZE_TWO] = { nullptr }; - napi_value thisVar = nullptr; napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); if (!CheckArgsCount(env, argc, ARGS_SIZE_TWO, false)) { - return nullptr; + return false; } - MacCtx *context = static_cast(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_CALLBACK : ASYNC_PROMISE; NapiSymKey *symKey = nullptr; napi_unwrap(env, argv[PARAM0], reinterpret_cast(&symKey)); if (symKey == nullptr) { - napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "symKey is null")); LOGE("symKey is null!"); - FreeCryptoFwkCtx(env, context); - return nullptr; + return false; } 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_status status = napi_unwrap(env, thisVar, reinterpret_cast(&napiMac)); + if (status != napi_ok) { + LOGE("failed to unwrap napiMac obj!"); + return false; } - napi_create_async_work( - env, nullptr, GetResourceName(env, "Init"), - MacInitExecute, - MacInitComplete, - static_cast(context), - &context->asyncWork); - napi_queue_async_work(env, context->asyncWork); - if (context->asyncType == ASYNC_TYPE_PROMISE) { - return context->promise; + + context->mac = napiMac->GetMac(); + + if (context->asyncType == ASYNC_PROMISE) { + napi_create_promise(env, &context->deferred, &context->promise); + return true; } else { - return NapiGetNull(env); + return GetCallbackFromJSParams(env, argv[PARAM1], &context->callback); } } -napi_value NapiMac::MacUpdate(napi_env env, napi_callback_info info) +static bool BuildMacJsUpdateCtx(napi_env env, napi_callback_info info, MacCtx *context) { + napi_value thisVar = nullptr; + NapiMac *napiMac = nullptr; size_t expectedArgsCount = ARGS_SIZE_TWO; size_t argc = expectedArgsCount; napi_value argv[ARGS_SIZE_TWO] = { nullptr }; - 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 = static_cast(HcfMalloc(sizeof(MacCtx), 0)); - if (context == nullptr) { - napi_throw(env, GenerateBusinessError(env, HCF_ERR_MALLOC, "malloc context failed")); - LOGE("malloc context failed!"); - return nullptr; + return false; } - context->macClass = this; + + context->asyncType = (argc == expectedArgsCount) ? ASYNC_CALLBACK : ASYNC_PROMISE; 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!"); - FreeCryptoFwkCtx(env, context); - return nullptr; + return false; } - if (!CreateCallbackAndPromise(env, context, argc, ARGS_SIZE_TWO, argv[PARAM1])) { - FreeCryptoFwkCtx(env, context); - return nullptr; + napi_status status = napi_unwrap(env, thisVar, reinterpret_cast(&napiMac)); + if (status != napi_ok) { + LOGE("failed to unwrap napiMac obj!"); + return false; } - napi_create_async_work( - env, nullptr, GetResourceName(env, "MacUpate"), - MacUpdateExecute, - MacUpdateComplete, - static_cast(context), - &context->asyncWork); - napi_queue_async_work(env, context->asyncWork); - if (context->asyncType == ASYNC_TYPE_PROMISE) { - return context->promise; + + context->mac = napiMac->GetMac(); + + if (context->asyncType == ASYNC_PROMISE) { + napi_create_promise(env, &context->deferred, &context->promise); + return true; } else { - return NapiGetNull(env); + return GetCallbackFromJSParams(env, argv[PARAM1], &context->callback); } } -napi_value NapiMac::MacDoFinal(napi_env env, napi_callback_info info) +static bool BuildMacJsDoFinalCtx(napi_env env, napi_callback_info info, MacCtx *context) { + napi_value thisVar = nullptr; + NapiMac *napiMac = nullptr; size_t expectedArgsCount = ARGS_SIZE_ONE; size_t argc = expectedArgsCount; napi_value argv[ARGS_SIZE_ONE] = { nullptr }; - napi_value thisVar = nullptr; napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); if (!CheckArgsCount(env, argc, ARGS_SIZE_ONE, false)) { - return nullptr; + return false; } - MacCtx *context = static_cast(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->asyncType = (argc == expectedArgsCount) ? ASYNC_CALLBACK : ASYNC_PROMISE; + napi_status status = napi_unwrap(env, thisVar, reinterpret_cast(&napiMac)); + if (status != napi_ok) { + LOGE("failed to unwrap napiMac obj!"); + return false; } - 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; + + context->mac = napiMac->GetMac(); + + if (context->asyncType == ASYNC_PROMISE) { + napi_create_promise(env, &context->deferred, &context->promise); + return true; + } else { + return GetCallbackFromJSParams(env, argv[PARAM0], &context->callback); } - napi_create_async_work( - env, nullptr, GetResourceName(env, "MacDoFinal"), - MacDoFinalExecute, - MacDoFinalComplete, +} + +static napi_value NewMacJsInitAsyncWork(napi_env env, MacCtx *context) +{ + NAPI_CALL(env, napi_create_async_work( + env, nullptr, GetResourceName(env, "MacInit"), + [](napi_env env, void *data) { + MacInitExecute(env, data); + return; + }, + [](napi_env env, napi_status status, void *data) { + MacInitComplete(env, status, data); + return; + }, static_cast(context), - &context->asyncWork); - napi_queue_async_work(env, context->asyncWork); - if (context->asyncType == ASYNC_TYPE_PROMISE) { + &context->asyncWork)); + + NAPI_CALL(env, napi_queue_async_work(env, context->asyncWork)); + if (context->asyncType == ASYNC_PROMISE) { return context->promise; } else { return NapiGetNull(env); } } -napi_value NapiMac::GetMacLength(napi_env env, napi_callback_info info) +static napi_value NewMacJsUpdateAsyncWork(napi_env env, MacCtx *context) { - HcfMac *macObj = GetMac(); - uint32_t retLen = macObj->getMacLength(macObj); - napi_value napiLen = nullptr; - napi_create_uint32(env, retLen, &napiLen); - return napiLen; + NAPI_CALL(env, napi_create_async_work( + env, nullptr, GetResourceName(env, "MacUpdate"), + [](napi_env env, void *data) { + MacUpdateExecute(env, data); + return; + }, + [](napi_env env, napi_status status, void *data) { + MacUpdateComplete(env, status, data); + return; + }, + static_cast(context), + &context->asyncWork)); + + NAPI_CALL(env, napi_queue_async_work(env, context->asyncWork)); + if (context->asyncType == ASYNC_PROMISE) { + return context->promise; + } else { + return NapiGetNull(env); + } } -static napi_value NapiMacInit(napi_env env, napi_callback_info info) +static napi_value NewMacJsDoFinalAsyncWork(napi_env env, MacCtx *context) { - 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!"); + NAPI_CALL(env, napi_create_async_work( + env, nullptr, GetResourceName(env, "MacDoFinal"), + [](napi_env env, void *data) { + MacDoFinalExecute(env, data); + return; + }, + [](napi_env env, napi_status status, void *data) { + MacDoFinalComplete(env, status, data); + return; + }, + static_cast(context), + &context->asyncWork)); + + NAPI_CALL(env, napi_queue_async_work(env, context->asyncWork)); + if (context->asyncType == ASYNC_PROMISE) { + return context->promise; + } else { return NapiGetNull(env); } - return macObj->MacInit(env, info); } -static napi_value NapiMacUpdate(napi_env env, napi_callback_info info) + +NapiMac::NapiMac(HcfMac *macObj) +{ + this->macObj_ = macObj; +} + +NapiMac::~NapiMac() { - 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); + HcfObjDestroy(this->macObj_); +} + +HcfMac *NapiMac::GetMac() +{ + return this->macObj_; +} + +napi_value NapiMac::JsMacInit(napi_env env, napi_callback_info info) +{ + MacCtx *context = static_cast(HcfMalloc(sizeof(MacCtx), 0)); + if (context == nullptr) { + napi_throw(env, GenerateBusinessError(env, HCF_ERR_MALLOC, "malloc context failed")); + LOGE("malloc context failed!"); + return nullptr; + } + + if (!BuildMacJsInitCtx(env, info, context)) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "build context fail.")); + LOGE("build context fail."); + FreeCryptoFwkCtx(env, context); + return nullptr; } - return macObj->MacUpdate(env, info); + + return NewMacJsInitAsyncWork(env, context); } -static napi_value NapiMacDoFinal(napi_env env, napi_callback_info info) +napi_value NapiMac::JsMacUpdate(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); + MacCtx *context = static_cast(HcfMalloc(sizeof(MacCtx), 0)); + if (context == nullptr) { + napi_throw(env, GenerateBusinessError(env, HCF_ERR_MALLOC, "malloc context failed")); + LOGE("malloc context failed!"); + return nullptr; + } + + if (!BuildMacJsUpdateCtx(env, info, context)) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "build context fail.")); + LOGE("build context fail."); + FreeCryptoFwkCtx(env, context); + return nullptr; } - return macObj->MacDoFinal(env, info); + + return NewMacJsUpdateAsyncWork(env, context); } -static napi_value NapiGetMacLength(napi_env env, napi_callback_info info) +napi_value NapiMac::JsMacDoFinal(napi_env env, napi_callback_info info) +{ + MacCtx *context = static_cast(HcfMalloc(sizeof(MacCtx), 0)); + if (context == nullptr) { + napi_throw(env, GenerateBusinessError(env, HCF_ERR_MALLOC, "malloc context failed")); + LOGE("malloc context failed!"); + return nullptr; + } + + if (!BuildMacJsDoFinalCtx(env, info, context)) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "build context fail.")); + LOGE("build context fail."); + FreeCryptoFwkCtx(env, context); + return nullptr; + } + + return NewMacJsDoFinalAsyncWork(env, context); +} + +napi_value NapiMac::JsGetMacLength(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); + NapiMac *napiMac = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&napiMac))); + + HcfMac *mac = napiMac->GetMac(); + if (mac == nullptr) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "fail to get mac obj!")); + LOGE("fail to get mac obj!"); + return nullptr; } - return macObj->GetMacLength(env, info); + + uint32_t retLen = mac->getMacLength(mac); + napi_value napiLen = nullptr; + NAPI_CALL(env, napi_create_uint32(env, retLen, &napiLen)); + return napiLen; } napi_value NapiMac::MacConstructor(napi_env env, napi_callback_info info) { napi_value thisVar = nullptr; - napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); return thisVar; } +static napi_value NapiWrapMac(napi_env env, napi_value instance, NapiMac *macNapiObj) +{ + napi_status status = napi_wrap( + env, instance, macNapiObj, + [](napi_env env, void *data, void *hint) { + NapiMac *mac = static_cast(data); + delete mac; + return; + }, + nullptr, + nullptr); + if (status != napi_ok) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "failed to wrap NapiMac obj!")); + delete macNapiObj; + macNapiObj = nullptr; + LOGE("failed to wrap NapiMac obj!"); + return nullptr; + } + return instance; +} + napi_value NapiMac::CreateMac(napi_env env, napi_callback_info info) { size_t expectedArgc = ARGS_SIZE_ONE; size_t argc = expectedArgc; napi_value argv[ARGS_SIZE_ONE] = { nullptr }; - napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); if (argc != expectedArgc) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "The input args num is invalid.")); LOGE("The input args num is invalid."); return nullptr; } std::string algoName; if (!GetStringFromJSParams(env, argv[PARAM0], algoName)) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "Failed to get algorithm.")); LOGE("Failed to get algorithm."); return nullptr; } @@ -436,40 +513,34 @@ napi_value NapiMac::CreateMac(napi_env env, napi_callback_info info) return nullptr; } napi_value napiAlgName = nullptr; - napi_create_string_utf8(env, algoName.c_str(), NAPI_AUTO_LENGTH, &napiAlgName); + NAPI_CALL(env, napi_create_string_utf8(env, algoName.c_str(), NAPI_AUTO_LENGTH, &napiAlgName)); napi_value instance = nullptr; napi_value constructor = nullptr; - napi_get_reference_value(env, classRef_, &constructor); - napi_new_instance(env, constructor, argc, argv, &instance); - napi_set_named_property(env, instance, CRYPTO_TAG_ALG_NAME.c_str(), napiAlgName); + NAPI_CALL(env, napi_get_reference_value(env, classRef_, &constructor)); + NAPI_CALL(env, napi_new_instance(env, constructor, argc, argv, &instance)); + NAPI_CALL(env, napi_set_named_property(env, instance, CRYPTO_TAG_ALG_NAME.c_str(), napiAlgName)); NapiMac *macNapiObj = new (std::nothrow) NapiMac(macObj); if (macNapiObj == nullptr) { + napi_throw(env, GenerateBusinessError(env, HCF_ERR_MALLOC, "new mac napi obj failed.")); + HcfObjDestroy(macObj); LOGE("create napi obj failed"); return nullptr; } - napi_wrap( - env, instance, macNapiObj, - [](napi_env env, void *data, void *hint) { - NapiMac *mac = static_cast(data); - delete mac; - return; - }, - nullptr, - nullptr); - return instance; + + return NapiWrapMac(env, instance, macNapiObj); } void NapiMac::DefineMacJSClass(napi_env env, napi_value exports) { napi_property_descriptor desc[] = { - DECLARE_NAPI_FUNCTION("createMac", CreateMac), + DECLARE_NAPI_FUNCTION("createMac", NapiMac::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), + DECLARE_NAPI_FUNCTION("init", NapiMac::JsMacInit), + DECLARE_NAPI_FUNCTION("update", NapiMac::JsMacUpdate), + DECLARE_NAPI_FUNCTION("doFinal", NapiMac::JsMacDoFinal), + DECLARE_NAPI_FUNCTION("getMacLength", NapiMac::JsGetMacLength), }; napi_value constructor = nullptr; napi_define_class(env, "Mac", NAPI_AUTO_LENGTH, MacConstructor, nullptr, diff --git a/frameworks/js/napi/crypto/src/napi_md.cpp b/frameworks/js/napi/crypto/src/napi_md.cpp index 86dd81d..961b1e3 100644 --- a/frameworks/js/napi/crypto/src/napi_md.cpp +++ b/frameworks/js/napi/crypto/src/napi_md.cpp @@ -29,20 +29,20 @@ thread_local napi_ref NapiMd::classRef_ = nullptr; struct MdCtx { napi_env env = nullptr; - CfAsyncType asyncType = ASYNC_TYPE_CALLBACK; + AsyncType asyncType = ASYNC_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; + HcfMd *md = nullptr; }; static void FreeCryptoFwkCtx(napi_env env, MdCtx *context) @@ -73,6 +73,7 @@ static void FreeCryptoFwkCtx(napi_env env, MdCtx *context) context->outBlob = nullptr; } context->errMsg = nullptr; + context->md = nullptr; HcfFree(context); context = nullptr; } @@ -103,63 +104,25 @@ static void ReturnPromiseResult(napi_env env, MdCtx *context, napi_value result) } } -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() -{ - HcfObjDestroy(this->mdObj_); -} - static void MdUpdateExecute(napi_env env, void *data) { MdCtx *context = static_cast(data); - NapiMd *mdClass = context->mdClass; - HcfMd *mdObj = mdClass->GetMd(); + HcfMd *mdObj = context->md; context->errCode = mdObj->update(mdObj, context->inBlob); if (context->errCode != HCF_SUCCESS) { + napi_throw(env, GenerateBusinessError(env, context->errCode, "update failed!")); 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(); + HcfMd *mdObj = context->md; HcfBlob *outBlob = reinterpret_cast(HcfMalloc(sizeof(HcfBlob), 0)); if (outBlob == nullptr) { + napi_throw(env, GenerateBusinessError(env, HCF_ERR_MALLOC, "malloc data blob failed")); LOGE("outBlob is null!"); context->errCode = HCF_ERR_MALLOC; context->errMsg = "malloc data blob failed"; @@ -167,15 +130,28 @@ static void MdDoFinalExecute(napi_env env, void *data) } context->errCode = mdObj->doFinal(mdObj, outBlob); if (context->errCode != HCF_SUCCESS) { + napi_throw(env, GenerateBusinessError(env, context->errCode, "doFinal failed")); + HcfFree(outBlob); LOGE("doFinal failed!"); context->errMsg = "doFinal failed"; - HcfFree(outBlob); - outBlob = nullptr; return; } context->outBlob = outBlob; } +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_CALLBACK) { + ReturnCallbackResult(env, context, nullInstance); + } else { + ReturnPromiseResult(env, context, nullInstance); + } + FreeCryptoFwkCtx(env, context); +} + static void MdDoFinalComplete(napi_env env, napi_status status, void *data) { MdCtx *context = static_cast(data); @@ -184,7 +160,7 @@ static void MdDoFinalComplete(napi_env env, napi_status status, void *data) LOGE("returnOutBlob is nullptr!"); returnOutBlob = NapiGetNull(env); } - if (context->asyncType == ASYNC_TYPE_CALLBACK) { + if (context->asyncType == ASYNC_CALLBACK) { ReturnCallbackResult(env, context, returnOutBlob); } else { ReturnPromiseResult(env, context, returnOutBlob); @@ -192,150 +168,233 @@ static void MdDoFinalComplete(napi_env env, napi_status status, void *data) FreeCryptoFwkCtx(env, context); } -napi_value NapiMd::MdUpdate(napi_env env, napi_callback_info info) +static bool BuildMdJsUpdateCtx(napi_env env, napi_callback_info info, MdCtx *context) { - // check param count - size_t argc = ARGS_SIZE_TWO; - napi_value argv[ARGS_SIZE_TWO] = { nullptr }; napi_value thisVar = nullptr; + NapiMd *napiMd = nullptr; + size_t expectedArgsCount = ARGS_SIZE_TWO; + size_t argc = expectedArgsCount; + napi_value argv[ARGS_SIZE_TWO] = { nullptr }; napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); if (!CheckArgsCount(env, argc, ARGS_SIZE_TWO, false)) { - return nullptr; + return false; } - MdCtx *context = static_cast(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->asyncType = (argc == expectedArgsCount) ? ASYNC_CALLBACK : ASYNC_PROMISE; 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!"); - FreeCryptoFwkCtx(env, context); - return nullptr; + return false; } - if (!CreateCallbackAndPromise(env, context, argc, ARGS_SIZE_TWO, argv[PARAM1])) { - FreeCryptoFwkCtx(env, context); - return nullptr; + napi_status status = napi_unwrap(env, thisVar, reinterpret_cast(&napiMd)); + if (status != napi_ok) { + LOGE("failed to unwrap NapiMd obj!"); + return false; } - napi_create_async_work( - env, nullptr, GetResourceName(env, "MdUpdate"), - MdUpdateExecute, - MdUpdateComplete, - static_cast(context), - &context->asyncWork); - napi_queue_async_work(env, context->asyncWork); - if (context->asyncType == ASYNC_TYPE_PROMISE) { - return context->promise; + + context->md = napiMd->GetMd(); + + if (context->asyncType == ASYNC_PROMISE) { + napi_create_promise(env, &context->deferred, &context->promise); + return true; } else { - return NapiGetNull(env); + return GetCallbackFromJSParams(env, argv[PARAM1], &context->callback); } } -napi_value NapiMd::MdDoFinal(napi_env env, napi_callback_info info) +static bool BuildMdJsDoFinalCtx(napi_env env, napi_callback_info info, MdCtx *context) { + napi_value thisVar = nullptr; + NapiMd *napiMd = nullptr; size_t expectedArgsCount = ARGS_SIZE_ONE; size_t argc = expectedArgsCount; napi_value argv[ARGS_SIZE_ONE] = { nullptr }; - napi_value thisVar = nullptr; napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); if (!CheckArgsCount(env, argc, ARGS_SIZE_ONE, false)) { - return nullptr; + return false; } - MdCtx *context = static_cast(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->asyncType = (argc == expectedArgsCount) ? ASYNC_CALLBACK : ASYNC_PROMISE; + + napi_status status = napi_unwrap(env, thisVar, reinterpret_cast(&napiMd)); + if (status != napi_ok) { + LOGE("failed to unwrap NapiMd obj!"); + return false; } - context->mdClass = this; - if (!CreateCallbackAndPromise(env, context, argc, ARGS_SIZE_ONE, argv[PARAM0])) { - FreeCryptoFwkCtx(env, context); - return nullptr; + + context->md = napiMd->GetMd(); + + if (context->asyncType == ASYNC_PROMISE) { + napi_create_promise(env, &context->deferred, &context->promise); + return true; + } else { + return GetCallbackFromJSParams(env, argv[PARAM0], &context->callback); + } +} + +static napi_value NewMdJsUpdateAsyncWork(napi_env env, MdCtx *context) +{ + NAPI_CALL(env, napi_create_async_work( + env, nullptr, GetResourceName(env, "MdUpdate"), + [](napi_env env, void *data) { + MdUpdateExecute(env, data); + return; + }, + [](napi_env env, napi_status status, void *data) { + MdUpdateComplete(env, status, data); + return; + }, + static_cast(context), + &context->asyncWork)); + + NAPI_CALL(env, napi_queue_async_work(env, context->asyncWork)); + if (context->asyncType == ASYNC_PROMISE) { + return context->promise; + } else { + return NapiGetNull(env); } - napi_create_async_work( +} + +static napi_value NewMdJsDoFinalAsyncWork(napi_env env, MdCtx *context) +{ + NAPI_CALL(env, napi_create_async_work( env, nullptr, GetResourceName(env, "MdDoFinal"), - MdDoFinalExecute, - MdDoFinalComplete, + [](napi_env env, void *data) { + MdDoFinalExecute(env, data); + return; + }, + [](napi_env env, napi_status status, void *data) { + MdDoFinalComplete(env, status, data); + return; + }, static_cast(context), - &context->asyncWork); - napi_queue_async_work(env, context->asyncWork); - if (context->asyncType == ASYNC_TYPE_PROMISE) { + &context->asyncWork)); + + NAPI_CALL(env, napi_queue_async_work(env, context->asyncWork)); + if (context->asyncType == ASYNC_PROMISE) { return context->promise; } else { return NapiGetNull(env); } } -napi_value NapiMd::GetMdLength(napi_env env, napi_callback_info info) +NapiMd::NapiMd(HcfMd *mdObj) { - HcfMd *mdObj = GetMd(); - uint32_t retLen = mdObj->getMdLength(mdObj); - napi_value napiLen = nullptr; - napi_create_uint32(env, retLen, &napiLen); - return napiLen; + this->mdObj_ = mdObj; } -static napi_value NapiMdUpdate(napi_env env, napi_callback_info info) +NapiMd::~NapiMd() { - 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); + HcfObjDestroy(this->mdObj_); +} + +HcfMd *NapiMd::GetMd() +{ + return this->mdObj_; +} + +napi_value NapiMd::JsMdUpdate(napi_env env, napi_callback_info info) +{ + MdCtx *context = static_cast(HcfMalloc(sizeof(MdCtx), 0)); + if (context == nullptr) { + napi_throw(env, GenerateBusinessError(env, HCF_ERR_MALLOC, "malloc context failed")); + LOGE("malloc context failed!"); + return nullptr; + } + + if (!BuildMdJsUpdateCtx(env, info, context)) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "build context fail.")); + LOGE("build context fail."); + FreeCryptoFwkCtx(env, context); + return nullptr; } - return mdObj->MdUpdate(env, info); + + return NewMdJsUpdateAsyncWork(env, context); } -static napi_value NapiMdDoFinal(napi_env env, napi_callback_info info) +napi_value NapiMd::JsMdDoFinal(napi_env env, napi_callback_info info) { - 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); + MdCtx *context = static_cast(HcfMalloc(sizeof(MdCtx), 0)); + if (context == nullptr) { + napi_throw(env, GenerateBusinessError(env, HCF_ERR_MALLOC, "malloc context failed")); + LOGE("malloc context failed!"); + return nullptr; } - return mdObj->MdDoFinal(env, info); + + if (!BuildMdJsDoFinalCtx(env, info, context)) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "build context fail.")); + LOGE("build context fail."); + FreeCryptoFwkCtx(env, context); + return nullptr; + } + + return NewMdJsDoFinalAsyncWork(env, context); } -static napi_value NapiGetMdLength(napi_env env, napi_callback_info info) +napi_value NapiMd::JsGetMdLength(napi_env env, napi_callback_info info) { 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); + NapiMd *napiMd = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); + + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&napiMd))); + + HcfMd *md = napiMd->GetMd(); + if (md == nullptr) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "fail to get md obj!")); + LOGE("fail to get md obj!"); + return nullptr; } - return mdObj->GetMdLength(env, info); + + uint32_t retLen = md->getMdLength(md); + napi_value napiLen = nullptr; + NAPI_CALL(env, napi_create_uint32(env, retLen, &napiLen)); + return napiLen; } napi_value NapiMd::MdConstructor(napi_env env, napi_callback_info info) { napi_value thisVar = nullptr; - napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); return thisVar; } +static napi_value NapiWrapMd(napi_env env, napi_value instance, NapiMd *mdNapiObj) +{ + napi_status status = napi_wrap( + env, instance, mdNapiObj, + [](napi_env env, void *data, void *hint) { + NapiMd *md = static_cast(data); + delete md; + return; + }, + nullptr, + nullptr); + if (status != napi_ok) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "failed to wrap NapiMd obj!")); + delete mdNapiObj; + mdNapiObj = nullptr; + LOGE("failed to wrap NapiMd obj!"); + return nullptr; + } + return instance; +} + napi_value NapiMd::CreateMd(napi_env env, napi_callback_info info) { size_t expectedArgc = ARGS_SIZE_ONE; size_t argc = expectedArgc; napi_value argv[ARGS_SIZE_ONE] = { nullptr }; - napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); if (argc != expectedArgc) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "The input args num is invalid.")); LOGE("The input args num is invalid."); return nullptr; } std::string algoName; if (!GetStringFromJSParams(env, argv[PARAM0], algoName)) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "Failed to get algorithm.")); LOGE("Failed to get algorithm."); return nullptr; } @@ -347,39 +406,33 @@ napi_value NapiMd::CreateMd(napi_env env, napi_callback_info info) return nullptr; } napi_value napiAlgName = nullptr; - napi_create_string_utf8(env, algoName.c_str(), NAPI_AUTO_LENGTH, &napiAlgName); + NAPI_CALL(env, napi_create_string_utf8(env, algoName.c_str(), NAPI_AUTO_LENGTH, &napiAlgName)); napi_value instance = nullptr; napi_value constructor = nullptr; - napi_get_reference_value(env, classRef_, &constructor); - napi_new_instance(env, constructor, argc, argv, &instance); - napi_set_named_property(env, instance, CRYPTO_TAG_ALG_NAME.c_str(), napiAlgName); + NAPI_CALL(env, napi_get_reference_value(env, classRef_, &constructor)); + NAPI_CALL(env, napi_new_instance(env, constructor, argc, argv, &instance)); + NAPI_CALL(env, napi_set_named_property(env, instance, CRYPTO_TAG_ALG_NAME.c_str(), napiAlgName)); NapiMd *mdNapiObj = new (std::nothrow) NapiMd(mdObj); if (mdNapiObj == nullptr) { - LOGE("create napi obj failed"); + napi_throw(env, GenerateBusinessError(env, HCF_ERR_MALLOC, "new md napi obj failed!")); + HcfObjDestroy(mdObj); + LOGE("create md napi obj failed!"); return nullptr; } - napi_wrap( - env, instance, mdNapiObj, - [](napi_env env, void *data, void *hint) { - NapiMd *md = static_cast(data); - delete md; - return; - }, - nullptr, - nullptr); - return instance; + + return NapiWrapMd(env, instance, mdNapiObj); } void NapiMd::DefineMdJSClass(napi_env env, napi_value exports) { napi_property_descriptor desc[] = { - DECLARE_NAPI_FUNCTION("createMd", CreateMd), + DECLARE_NAPI_FUNCTION("createMd", NapiMd::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), + DECLARE_NAPI_FUNCTION("update", NapiMd::JsMdUpdate), + DECLARE_NAPI_FUNCTION("digest", NapiMd::JsMdDoFinal), + DECLARE_NAPI_FUNCTION("getMdLength", NapiMd::JsGetMdLength), }; napi_value constructor = nullptr; napi_define_class(env, "Md", NAPI_AUTO_LENGTH, MdConstructor, nullptr, diff --git a/frameworks/js/napi/crypto/src/napi_rand.cpp b/frameworks/js/napi/crypto/src/napi_rand.cpp index 24d8756..b7b5737 100644 --- a/frameworks/js/napi/crypto/src/napi_rand.cpp +++ b/frameworks/js/napi/crypto/src/napi_rand.cpp @@ -29,19 +29,19 @@ thread_local napi_ref NapiRand::classRef_ = nullptr; struct RandCtx { napi_env env = nullptr; - CfAsyncType asyncType = ASYNC_TYPE_CALLBACK; + AsyncType asyncType = ASYNC_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; + HcfRand *rand = nullptr; }; static void FreeCryptoFwkCtx(napi_env env, RandCtx *context) @@ -73,6 +73,7 @@ static void FreeCryptoFwkCtx(napi_env env, RandCtx *context) context->randBlob = nullptr; } context->errMsg = nullptr; + context->rand = nullptr; HcfFree(context); context = nullptr; } @@ -104,38 +105,13 @@ static void ReturnPromiseResult(napi_env env, RandCtx *context, napi_value resul } } -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() -{ - HcfObjDestroy(this->randObj_); -} - static void GenerateRandomExecute(napi_env env, void *data) { RandCtx *context = static_cast(data); - NapiRand *randClass = context->randClass; - HcfRand *randObj = randClass->GetRand(); + HcfRand *randObj = context->rand; HcfBlob *randBlob = reinterpret_cast(HcfMalloc(sizeof(HcfBlob), 0)); if (randBlob == nullptr) { + napi_throw(env, GenerateBusinessError(env, HCF_ERR_MALLOC, "randBlob is null!")); LOGE("randBlob is null!"); context->errCode = HCF_ERR_MALLOC; context->errMsg = "malloc data blob failed"; @@ -144,10 +120,10 @@ static void GenerateRandomExecute(napi_env env, void *data) uint32_t numBytes = context->numBytes; context->errCode = randObj->generateRandom(randObj, numBytes, randBlob); if (context->errCode != HCF_SUCCESS) { + napi_throw(env, GenerateBusinessError(env, context->errCode, "generateRandom failed!")); LOGE("generateRandom failed!"); context->errMsg = "generateRandom failed"; HcfFree(randBlob); - randBlob = nullptr; return; } context->randBlob = randBlob; @@ -161,7 +137,7 @@ static void GenerateRandomComplete(napi_env env, napi_status status, void *data) LOGE("returnOutBlob is nullptr!"); returnRandBlob = NapiGetNull(env); } - if (context->asyncType == ASYNC_TYPE_CALLBACK) { + if (context->asyncType == ASYNC_CALLBACK) { ReturnCallbackResult(env, context, returnRandBlob); } else { ReturnPromiseResult(env, context, returnRandBlob); @@ -169,101 +145,198 @@ static void GenerateRandomComplete(napi_env env, napi_status status, void *data) FreeCryptoFwkCtx(env, context); } -napi_value NapiRand::GenerateRandom(napi_env env, napi_callback_info info) +static bool BuildGenerateRandomCtx(napi_env env, napi_callback_info info, RandCtx *context) { + napi_value thisVar = nullptr; size_t expectedArgsCount = ARGS_SIZE_TWO; size_t argc = expectedArgsCount; napi_value argv[ARGS_SIZE_TWO] = { nullptr }; - 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 = static_cast(HcfMalloc(sizeof(RandCtx), 0)); - if (context == nullptr) { - napi_throw(env, GenerateBusinessError(env, HCF_ERR_MALLOC, "malloc context failed")); - LOGE("malloc context failed!"); - return ret; + return false; } - context->randClass = this; + if (!GetUint32FromJSParams(env, argv[PARAM0], context->numBytes)) { LOGE("get numBytes failed!"); - FreeCryptoFwkCtx(env, context); - return ret; + return false; } - if (!CreateCallbackAndPromise(env, context, argc, ARGS_SIZE_TWO, argv[PARAM1])) { - FreeCryptoFwkCtx(env, context); - return nullptr; + context->asyncType = isCallback(env, argv[expectedArgsCount - 1], argc, expectedArgsCount) ? + ASYNC_CALLBACK : ASYNC_PROMISE; + + NapiRand *napiRand = nullptr; + napi_status status = napi_unwrap(env, thisVar, reinterpret_cast(&napiRand)); + if (status != napi_ok) { + LOGE("failed to unwrap NapiRand obj!"); + return false; } - napi_create_async_work( + + context->rand = napiRand->GetRand(); + + if (context->asyncType == ASYNC_PROMISE) { + napi_create_promise(env, &context->deferred, &context->promise); + return true; + } else { + return GetCallbackFromJSParams(env, argv[PARAM1], &context->callback); + } +} + +static napi_value NewRandJsGenerateAsyncWork(napi_env env, RandCtx *context) +{ + NAPI_CALL(env, napi_create_async_work( env, nullptr, GetResourceName(env, "GenerateRandom"), - GenerateRandomExecute, - GenerateRandomComplete, + [](napi_env env, void *data) { + GenerateRandomExecute(env, data); + return; + }, + [](napi_env env, napi_status status, void *data) { + GenerateRandomComplete(env, status, data); + return; + }, static_cast(context), - &context->asyncWork); - napi_queue_async_work(env, context->asyncWork); - if (context->asyncType == ASYNC_TYPE_PROMISE) { + &context->asyncWork)); + + NAPI_CALL(env, napi_queue_async_work(env, context->asyncWork)); + if (context->asyncType == ASYNC_PROMISE) { return context->promise; } else { return NapiGetNull(env); } } -napi_value NapiRand::SetSeed(napi_env env, napi_callback_info info) +NapiRand::NapiRand(HcfRand *randObj) +{ + this->randObj_ = randObj; +} + +NapiRand::~NapiRand() +{ + HcfObjDestroy(this->randObj_); +} + +HcfRand *NapiRand::GetRand() +{ + return this->randObj_; +} + +napi_value NapiRand::JsGenerateRandom(napi_env env, napi_callback_info info) +{ + RandCtx *context = static_cast(HcfMalloc(sizeof(RandCtx), 0)); + if (context == nullptr) { + napi_throw(env, GenerateBusinessError(env, HCF_ERR_MALLOC, "malloc context failed")); + LOGE("malloc context failed!"); + return nullptr; + } + + if (!BuildGenerateRandomCtx(env, info, context)) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "build context fail.")); + LOGE("build context fail."); + FreeCryptoFwkCtx(env, context); + return nullptr; + } + + return NewRandJsGenerateAsyncWork(env, context); +} + +napi_value NapiRand::JsGenerateRandomSync(napi_env env, napi_callback_info info) { + napi_value thisVar = nullptr; + NapiRand *napiRand = nullptr; size_t expectedArgsCount = ARGS_SIZE_ONE; size_t argc = expectedArgsCount; napi_value argv[ARGS_SIZE_ONE] = { nullptr }; - napi_value thisVar = nullptr; - napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr)); if (argc != expectedArgsCount) { napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "invalid params count")); LOGE("The arguments count is not expected!"); return nullptr; } - HcfBlob *seedBlob = GetBlobFromNapiValue(env, argv[PARAM0]); - HcfRand *randObj = GetRand(); - HcfResult res = randObj->setSeed(randObj, seedBlob); + + uint32_t numBytes = 0; + if (!GetUint32FromJSParams(env, argv[PARAM0], numBytes)) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "get numBytes failed!")); + LOGE("get numBytes failed!"); + return nullptr; + } + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&napiRand))); + HcfRand *rand = napiRand->GetRand(); + if (rand == nullptr) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "fail to get rand obj!")); + LOGE("fail to get rand obj!"); + return nullptr; + } + + HcfBlob randBlob = { .data = nullptr, .len = 0}; + HcfResult res = rand->generateRandom(rand, numBytes, &randBlob); if (res != HCF_SUCCESS) { - napi_throw(env, GenerateBusinessError(env, res, "set seed failed.")); - LOGE("set seed failed."); + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "fail to get rand obj!")); + LOGE("generateRandom failed!"); + return nullptr; } - return nullptr; + + napi_value instance = ConvertBlobToNapiValue(env, &randBlob); + HcfBlobDataClearAndFree(&randBlob); + return instance; } -static napi_value NapiGenerateRandom(napi_env env, napi_callback_info info) +napi_value NapiRand::JsSetSeed(napi_env env, napi_callback_info info) { 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); + NapiRand *napiRand = nullptr; + size_t expectedArgsCount = ARGS_SIZE_ONE; + size_t argc = expectedArgsCount; + napi_value argv[ARGS_SIZE_ONE] = { nullptr }; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr)); + if (argc != expectedArgsCount) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "invalid params count")); + LOGE("The arguments count is not expected!"); + return nullptr; + } + HcfBlob *seedBlob = GetBlobFromNapiValue(env, argv[PARAM0]); + + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&napiRand))); + HcfRand *rand = napiRand->GetRand(); + if (rand == nullptr) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "fail to get rand obj!")); + LOGE("fail to get rand obj!"); + return nullptr; } - return randObj->GenerateRandom(env, info); + HcfResult res = rand->setSeed(rand, seedBlob); + if (res != HCF_SUCCESS) { + napi_throw(env, GenerateBusinessError(env, res, "set seed failed.")); + LOGE("set seed failed."); + return nullptr; + } + return thisVar; } -static napi_value NapiSetSeed(napi_env env, napi_callback_info info) +napi_value NapiRand::JsGetAlgorithm(napi_env env, napi_callback_info info) { 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!"); + NapiRand *napiRand = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); + NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast(&napiRand))); + + HcfRand *rand = napiRand->GetRand(); + if (rand == nullptr) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "fail to get rand obj!")); + LOGE("fail to get rand obj!"); return nullptr; } - return randObj->SetSeed(env, info); + + const char *algoName = rand->getAlgoName(rand); + napi_value instance = nullptr; + NAPI_CALL(env, napi_create_string_utf8(env, algoName, NAPI_AUTO_LENGTH, &instance)); + return instance; } napi_value NapiRand::RandConstructor(napi_env env, napi_callback_info info) { napi_value thisVar = nullptr; - napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr); + NAPI_CALL(env, napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr)); return thisVar; } @@ -278,14 +351,16 @@ napi_value NapiRand::CreateRand(napi_env env, napi_callback_info info) } napi_value instance = nullptr; napi_value constructor = nullptr; - napi_get_reference_value(env, classRef_, &constructor); - napi_new_instance(env, constructor, 0, nullptr, &instance); + NAPI_CALL(env, napi_get_reference_value(env, classRef_, &constructor)); + NAPI_CALL(env, napi_new_instance(env, constructor, 0, nullptr, &instance)); NapiRand *randNapiObj = new (std::nothrow) NapiRand(randObj); if (randNapiObj == nullptr) { - LOGE("create napi obj failed"); + napi_throw(env, GenerateBusinessError(env, HCF_ERR_MALLOC, "new rand napi obj failed.")); + HcfObjDestroy(randObj); + LOGE("create rand napi obj failed"); return nullptr; } - napi_wrap( + napi_status status = napi_wrap( env, instance, randNapiObj, [](napi_env env, void *data, void *hint) { NapiRand *rand = static_cast(data); @@ -294,18 +369,26 @@ napi_value NapiRand::CreateRand(napi_env env, napi_callback_info info) }, nullptr, nullptr); + if (status != napi_ok) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "failed to wrap NapiRand obj!")); + delete randNapiObj; + LOGE("failed to wrap NapiRand obj!"); + return nullptr; + } return instance; } void NapiRand::DefineRandJSClass(napi_env env, napi_value exports) { napi_property_descriptor desc[] = { - DECLARE_NAPI_FUNCTION("createRandom", CreateRand), + DECLARE_NAPI_FUNCTION("createRandom", NapiRand::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), + DECLARE_NAPI_FUNCTION("generateRandom", NapiRand::JsGenerateRandom), + DECLARE_NAPI_FUNCTION("generateRandomSync", NapiRand::JsGenerateRandomSync), + DECLARE_NAPI_FUNCTION("setSeed", NapiRand::JsSetSeed), + {.utf8name = "algName", .getter = NapiRand::JsGetAlgorithm}, }; napi_value constructor = nullptr; napi_define_class(env, "Random", NAPI_AUTO_LENGTH, RandConstructor, nullptr, diff --git a/frameworks/js/napi/crypto/src/napi_sym_key.cpp b/frameworks/js/napi/crypto/src/napi_sym_key.cpp index 0d2af9a..b06d949 100644 --- a/frameworks/js/napi/crypto/src/napi_sym_key.cpp +++ b/frameworks/js/napi/crypto/src/napi_sym_key.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022 Huawei Device Co., Ltd. + * Copyright (C) 2022-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/frameworks/js/napi/crypto/src/napi_sym_key_generator.cpp b/frameworks/js/napi/crypto/src/napi_sym_key_generator.cpp index 870ace0..d795bc0 100644 --- a/frameworks/js/napi/crypto/src/napi_sym_key_generator.cpp +++ b/frameworks/js/napi/crypto/src/napi_sym_key_generator.cpp @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022 Huawei Device Co., Ltd. + * Copyright (C) 2022-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -34,7 +34,7 @@ struct SymKeyGeneratorFwkCtxT { napi_value promise = nullptr; napi_async_work asyncWork = nullptr; - int32_t errCode = 0; + HcfResult errCode = HCF_SUCCESS; HcfSymKey *returnSymKey = nullptr; const char *errMsg = nullptr; @@ -80,15 +80,13 @@ static bool BuildContextForGenerateKey(napi_env env, napi_callback_info info, Sy 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; + context->asyncType = isCallback(env, argv[expectedArgc - 1], argc, expectedArgc) ? ASYNC_CALLBACK : ASYNC_PROMISE; NapiSymKeyGenerator *napiGenerator; napi_status status = napi_unwrap(env, thisVar, reinterpret_cast(&napiGenerator)); - if (status != napi_ok) { + if (status != napi_ok || napiGenerator == nullptr) { LOGE("failed to unwrap NapiSymKeyGenerator obj!"); return false; } @@ -119,11 +117,11 @@ static bool BuildContextForConvertKey(napi_env env, napi_callback_info info, Sym LOGE("wrong argument num. require 1 or 2 arguments. [Argc]: %zu!", argc); return false; } - context->asyncType = (argc == expectedArgc) ? ASYNC_CALLBACK : ASYNC_PROMISE; + context->asyncType = isCallback(env, argv[expectedArgc - 1], argc, expectedArgc) ? ASYNC_CALLBACK : ASYNC_PROMISE; NapiSymKeyGenerator *napiGenerator; napi_status status = napi_unwrap(env, thisVar, reinterpret_cast(&napiGenerator)); - if (status != napi_ok) { + if (status != napi_ok || napiGenerator == nullptr) { LOGE("failed to unwrap NapiSymKeyGenerator obj!"); return false; } @@ -185,10 +183,10 @@ static void AsyncGenKeyProcess(napi_env env, void *data) HcfSymKeyGenerator *generator = context->generator; HcfSymKey *key = nullptr; - HcfResult res = generator->generateSymKey(generator, &key); - if (res != HCF_SUCCESS) { + context->errCode = generator->generateSymKey(generator, &key); + if (context->errCode != HCF_SUCCESS) { + napi_throw(env, GenerateBusinessError(env, context->errCode, "generate sym key failed.")); LOGE("generate sym key failed."); - context->errCode = res; context->errMsg = "generate sym key failed."; return; } @@ -217,6 +215,7 @@ static void AsyncKeyReturn(napi_env env, napi_status status, void *data) }, nullptr, nullptr); if (ret != napi_ok) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "failed to wrap napiSymKey obj!")); LOGE("failed to wrap napiSymKey obj!"); context->errCode = HCF_INVALID_PARAMS; context->errMsg = "failed to wrap napiSymKey obj!"; @@ -237,24 +236,23 @@ static void AsyncConvertKeyProcess(napi_env env, void *data) HcfSymKeyGenerator *generator = context->generator; HcfSymKey *key = nullptr; - HcfResult res = generator->convertSymKey(generator, &context->keyMaterial, &key); - if (res != HCF_SUCCESS) { + context->errCode = generator->convertSymKey(generator, &context->keyMaterial, &key); + if (context->errCode != HCF_SUCCESS) { + napi_throw(env, GenerateBusinessError(env, context->errCode, "convertSymKey key failed!")); 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_CALL(env, napi_create_string_utf8(env, "convertSymKey", NAPI_AUTO_LENGTH, &resourceName)); - napi_create_async_work( + NAPI_CALL(env, napi_create_async_work( env, nullptr, resourceName, @@ -267,9 +265,9 @@ static napi_value NewConvertKeyAsyncWork(napi_env env, SymKeyGeneratorFwkCtx con return; }, static_cast(context), - &context->asyncWork); + &context->asyncWork)); - napi_queue_async_work(env, context->asyncWork); + NAPI_CALL(env, napi_queue_async_work(env, context->asyncWork)); if (context->asyncType == ASYNC_PROMISE) { return context->promise; } else { @@ -280,9 +278,9 @@ static napi_value NewConvertKeyAsyncWork(napi_env env, SymKeyGeneratorFwkCtx con static napi_value NewGenKeyAsyncWork(napi_env env, SymKeyGeneratorFwkCtx context) { napi_value resourceName = nullptr; - napi_create_string_utf8(env, "generatorSymKey", NAPI_AUTO_LENGTH, &resourceName); + NAPI_CALL(env, napi_create_string_utf8(env, "generatorSymKey", NAPI_AUTO_LENGTH, &resourceName)); - napi_create_async_work( + NAPI_CALL(env, napi_create_async_work( env, nullptr, resourceName, @@ -295,9 +293,9 @@ static napi_value NewGenKeyAsyncWork(napi_env env, SymKeyGeneratorFwkCtx context return; }, static_cast(context), - &context->asyncWork); + &context->asyncWork)); - napi_queue_async_work(env, context->asyncWork); + NAPI_CALL(env, napi_queue_async_work(env, context->asyncWork)); if (context->asyncType == ASYNC_PROMISE) { return context->promise; } else { @@ -324,11 +322,13 @@ napi_value NapiSymKeyGenerator::JsGenerateSymKey(napi_env env, napi_callback_inf { SymKeyGeneratorFwkCtx context = static_cast(HcfMalloc(sizeof(SymKeyGeneratorFwkCtxT), 0)); if (context == nullptr) { + napi_throw(env, GenerateBusinessError(env, HCF_ERR_MALLOC, "Create context failed!")); LOGE("Create context failed!"); return nullptr; } if (!BuildContextForGenerateKey(env, info, context)) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "Build context fail.")); LOGE("Build context fail."); FreeSymKeyGeneratorFwkCtx(env, context); return nullptr; @@ -347,6 +347,7 @@ napi_value NapiSymKeyGenerator::JsConvertKey(napi_env env, napi_callback_info in { SymKeyGeneratorFwkCtx context = static_cast(HcfMalloc(sizeof(SymKeyGeneratorFwkCtxT), 0)); if (context == nullptr) { + napi_throw(env, GenerateBusinessError(env, HCF_ERR_MALLOC, "malloc SymKeyGeneratorFwkCtx failed!")); LOGE("malloc SymKeyGeneratorFwkCtx failed!"); return nullptr; } @@ -378,7 +379,7 @@ napi_value NapiSymKeyGenerator::CreateSymKeyGenerator(napi_env env, napi_callbac 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, nullptr, nullptr); + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr)); if (argc != expectedArgc) { napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "The input args num is invalid.")); @@ -393,12 +394,13 @@ napi_value NapiSymKeyGenerator::CreateSymKeyGenerator(napi_env env, napi_callbac std::string algoName; if (!GetStringFromJSParams(env, argv[0], algoName)) { + napi_throw(env, GenerateBusinessError(env, HCF_INVALID_PARAMS, "failed to get algoName.")); LOGE("failed to get algoName."); return nullptr; } HcfSymKeyGenerator *generator = nullptr; - int32_t res = HcfSymKeyGeneratorCreate(algoName.c_str(), &generator); + HcfResult 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."); @@ -406,7 +408,8 @@ napi_value NapiSymKeyGenerator::CreateSymKeyGenerator(napi_env env, napi_callbac } NapiSymKeyGenerator *napiSymKeyGenerator = new (std::nothrow) NapiSymKeyGenerator(generator); if (napiSymKeyGenerator == nullptr) { - LOGE("new napiSymKeyGenerator failed!"); + napi_throw(env, GenerateBusinessError(env, HCF_ERR_MALLOC, "new napi sym key generator failed.")); + LOGE("new napi sym key generator failed!"); HcfObjDestroy(generator); return nullptr; } @@ -437,7 +440,7 @@ napi_value NapiSymKeyGenerator::JsGetAlgorithm(napi_env env, napi_callback_info const char *algo = generator->getAlgoName(generator); napi_value instance = nullptr; - napi_create_string_utf8(env, algo, NAPI_AUTO_LENGTH, &instance); + NAPI_CALL(env, napi_create_string_utf8(env, algo, NAPI_AUTO_LENGTH, &instance)); return instance; } @@ -454,8 +457,9 @@ void NapiSymKeyGenerator::DefineSymKeyGeneratorJSClass(napi_env env, napi_value { .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_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 diff --git a/frameworks/key/sym_key_generator.c b/frameworks/key/sym_key_generator.c index b45bd2b..f816229 100644 --- a/frameworks/key/sym_key_generator.c +++ b/frameworks/key/sym_key_generator.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022 Huawei Device Co., Ltd. + * Copyright (C) 2022-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -200,10 +200,10 @@ HcfResult HcfSymKeyGeneratorCreate(const char *algoName, HcfSymKeyGenerator **re if (strcpy_s(returnGenerator->algoName, HCF_MAX_ALGO_NAME_LEN, algoName)) { LOGE("Failed to copy algoName!"); HcfFree(returnGenerator); - return HCF_ERR_COPY; + return HCF_INVALID_PARAMS; } HcfSymKeyGeneratorSpi *spiObj = NULL; - int32_t res = funcSet->createFunc(&attr, &spiObj); + HcfResult res = funcSet->createFunc(&attr, &spiObj); if (res != HCF_SUCCESS) { LOGE("Failed to create spi object!"); HcfFree(returnGenerator); diff --git a/frameworks/spi/rand_spi.h b/frameworks/spi/rand_spi.h index 5825d79..8b554c6 100644 --- a/frameworks/spi/rand_spi.h +++ b/frameworks/spi/rand_spi.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022 Huawei Device Co., Ltd. + * Copyright (C) 2022-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -21,10 +21,14 @@ #include "blob.h" #include "object_base.h" +#define OPENSSL_RAND_ALGORITHM "CTR_DRBG" + typedef struct HcfRandSpi HcfRandSpi; struct HcfRandSpi { HcfObjectBase base; + + const char *(*engineGetAlgoName)(HcfRandSpi *self); HcfResult (*engineGenerateRandom)(HcfRandSpi *self, int32_t numBytes, HcfBlob *random); diff --git a/interfaces/innerkits/rand/rand.h b/interfaces/innerkits/crypto_operation/rand.h similarity index 95% rename from interfaces/innerkits/rand/rand.h rename to interfaces/innerkits/crypto_operation/rand.h index d272a09..2f1c77f 100644 --- a/interfaces/innerkits/rand/rand.h +++ b/interfaces/innerkits/crypto_operation/rand.h @@ -27,6 +27,8 @@ typedef struct HcfRand HcfRand; struct HcfRand { HcfObjectBase base; + const char *(*getAlgoName)(HcfRand *self); + HcfResult (*generateRandom)(HcfRand *self, int32_t numBytes, HcfBlob *random); HcfResult (*setSeed)(HcfRand *self, HcfBlob *seed); diff --git a/plugin/openssl_plugin/certificate/src/x509_crl_openssl.c b/plugin/openssl_plugin/certificate/src/x509_crl_openssl.c index 6cab590..8837abc 100644 --- a/plugin/openssl_plugin/certificate/src/x509_crl_openssl.c +++ b/plugin/openssl_plugin/certificate/src/x509_crl_openssl.c @@ -804,4 +804,4 @@ HcfResult HcfCX509CrlSpiCreate(const HcfEncodingBlob *inStream, HcfX509CrlSpi ** } *spi = (HcfX509CrlSpi *)returnCRL; 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/cipher/inc/aes_openssl.h similarity index 100% rename from plugin/openssl_plugin/crypto_operation/aes/inc/aes_openssl.h rename to plugin/openssl_plugin/crypto_operation/cipher/inc/aes_openssl.h diff --git a/plugin/openssl_plugin/crypto_operation/rsa/inc/cipher_rsa_openssl.h b/plugin/openssl_plugin/crypto_operation/cipher/inc/cipher_rsa_openssl.h similarity index 100% rename from plugin/openssl_plugin/crypto_operation/rsa/inc/cipher_rsa_openssl.h rename to plugin/openssl_plugin/crypto_operation/cipher/inc/cipher_rsa_openssl.h diff --git a/plugin/openssl_plugin/crypto_operation/aes/src/cipher_3des_openssl.c b/plugin/openssl_plugin/crypto_operation/cipher/src/cipher_3des_openssl.c similarity index 81% rename from plugin/openssl_plugin/crypto_operation/aes/src/cipher_3des_openssl.c rename to plugin/openssl_plugin/crypto_operation/cipher/src/cipher_3des_openssl.c index 5968fad..701eec3 100644 --- a/plugin/openssl_plugin/crypto_operation/aes/src/cipher_3des_openssl.c +++ b/plugin/openssl_plugin/crypto_operation/cipher/src/cipher_3des_openssl.c @@ -13,7 +13,6 @@ * limitations under the License. */ -#include #include "log.h" #include "blob.h" #include "memory.h" @@ -22,6 +21,7 @@ #include "securec.h" #include "aes_openssl_common.h" #include "sym_common_defines.h" +#include "openssl_adapter.h" #include "openssl_common.h" #include "openssl_class.h" @@ -41,25 +41,25 @@ static const char *GetDesGeneratorClass(void) static const EVP_CIPHER *DefaultCipherType(void) { - return EVP_des_ede3_ecb(); + return Openssl_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(); + return Openssl_EVP_des_ede3_ecb(); case HCF_ALG_MODE_CBC: - return EVP_des_ede3_cbc(); + return Openssl_EVP_des_ede3_cbc(); case HCF_ALG_MODE_OFB: - return EVP_des_ede3_ofb(); + return Openssl_EVP_des_ede3_ofb(); case HCF_ALG_MODE_CFB: case HCF_ALG_MODE_CFB64: - return EVP_des_ede3_cfb64(); + return Openssl_EVP_des_ede3_cfb64(); case HCF_ALG_MODE_CFB1: - return EVP_des_ede3_cfb1(); + return Openssl_EVP_des_ede3_cfb1(); case HCF_ALG_MODE_CFB8: - return EVP_des_ede3_cfb8(); + return Openssl_EVP_des_ede3_cfb8(); default: break; } @@ -72,15 +72,15 @@ static HcfResult InitCipherData(enum HcfCryptoMode opMode, CipherData **cipherDa *cipherData = (CipherData *)HcfMalloc(sizeof(CipherData), 0); if (*cipherData == NULL) { - LOGE("malloc failed!"); + LOGE("malloc failed."); return HCF_ERR_MALLOC; } (*cipherData)->enc = opMode; - (*cipherData)->ctx = EVP_CIPHER_CTX_new(); + (*cipherData)->ctx = Openssl_EVP_CIPHER_CTX_new(); if ((*cipherData)->ctx == NULL) { HcfPrintOpensslError(); - LOGE("Failed to allocate ctx memroy!"); + LOGE("Failed to allocate ctx memroy."); goto clearup; } @@ -95,7 +95,7 @@ static HcfResult EngineCipherInit(HcfCipherGeneratorSpi *self, enum HcfCryptoMod HcfKey *key, HcfParamsSpec *params) { if ((self == NULL) || (key == NULL)) { /* params maybe is null */ - LOGE("Invalid input parameter!"); + LOGE("Invalid input parameter."); return HCF_INVALID_PARAMS; } if (!IsClassMatch((const HcfObjectBase *)self, GetDesGeneratorClass())) { @@ -121,20 +121,20 @@ static HcfResult EngineCipherInit(HcfCipherGeneratorSpi *self, enum HcfCryptoMod } HcfResult ret = HCF_ERR_CRYPTO_OPERATION; CipherData *data = cipherImpl->cipherData; - if (EVP_CipherInit(data->ctx, GetCipherType(cipherImpl), NULL, NULL, enc) != HCF_OPENSSL_SUCCESS) { + if (Openssl_EVP_CipherInit(data->ctx, GetCipherType(cipherImpl), NULL, NULL, enc) != HCF_OPENSSL_SUCCESS) { HcfPrintOpensslError(); - LOGE("cipher init failed!"); + LOGE("Cipher init failed."); goto clearup; } - if (EVP_CipherInit(data->ctx, NULL, keyImpl->keyMaterial.data, GetIv(params), enc) != HCF_OPENSSL_SUCCESS) { + if (Openssl_EVP_CipherInit(data->ctx, NULL, keyImpl->keyMaterial.data, GetIv(params), enc) != HCF_OPENSSL_SUCCESS) { HcfPrintOpensslError(); - LOGE("cipher init key and iv failed!"); + 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) { + if (Openssl_EVP_CIPHER_CTX_set_padding(data->ctx, padding) != HCF_OPENSSL_SUCCESS) { HcfPrintOpensslError(); - LOGE("set padding!"); + LOGE("Set padding failed."); goto clearup; } return HCF_SUCCESS; @@ -151,7 +151,7 @@ static HcfResult AllocateOutput(HcfBlob *input, HcfBlob *output) } output->data = (uint8_t *)HcfMalloc(outLen, 0); if (output->data == NULL) { - LOGE("malloc output failed!"); + LOGE("Malloc output failed."); return HCF_ERR_MALLOC; } output->len = outLen; @@ -161,7 +161,7 @@ static HcfResult AllocateOutput(HcfBlob *input, HcfBlob *output) static HcfResult EngineUpdate(HcfCipherGeneratorSpi *self, HcfBlob *input, HcfBlob *output) { if ((self == NULL) || (input == NULL) || (output == NULL)) { - LOGE("Invalid input parameter!"); + LOGE("Invalid input parameter."); return HCF_INVALID_PARAMS; } if (!IsClassMatch((const HcfObjectBase *)self, GetDesGeneratorClass())) { @@ -172,20 +172,20 @@ static HcfResult EngineUpdate(HcfCipherGeneratorSpi *self, HcfBlob *input, HcfBl HcfCipherDesGeneratorSpiOpensslImpl *cipherImpl = (HcfCipherDesGeneratorSpiOpensslImpl *)self; CipherData *data = cipherImpl->cipherData; if (data == NULL) { - LOGE("cipherData is null!"); + LOGE("CipherData is null."); return HCF_INVALID_PARAMS; } HcfResult res = AllocateOutput(input, output); if (res != HCF_SUCCESS) { - LOGE("AllocateOutput failed!"); + LOGE("AllocateOutput failed."); goto clearup; } - int32_t ret = EVP_CipherUpdate(data->ctx, output->data, (int *)&output->len, + int32_t ret = Openssl_EVP_CipherUpdate(data->ctx, output->data, (int *)&output->len, input->data, input->len); if (ret != HCF_OPENSSL_SUCCESS) { HcfPrintOpensslError(); - LOGE("cipher update failed!"); + LOGE("Cipher update failed."); res = HCF_ERR_CRYPTO_OPERATION; goto clearup; } @@ -206,19 +206,19 @@ static HcfResult DesDoFinal(CipherData *data, HcfBlob *input, HcfBlob *output) uint32_t len = 0; if (IsBlobValid(input)) { - ret = EVP_CipherUpdate(data->ctx, output->data, (int *)&output->len, + ret = Openssl_EVP_CipherUpdate(data->ctx, output->data, (int *)&output->len, input->data, input->len); if (ret != HCF_OPENSSL_SUCCESS) { HcfPrintOpensslError(); - LOGE("cipher update failed!"); + LOGE("Cipher update failed."); return HCF_ERR_CRYPTO_OPERATION; } len += output->len; } - ret = EVP_CipherFinal_ex(data->ctx, output->data + len, (int *)&output->len); + ret = Openssl_EVP_CipherFinal_ex(data->ctx, output->data + len, (int *)&output->len); if (ret != HCF_OPENSSL_SUCCESS) { HcfPrintOpensslError(); - LOGE("cipher final filed!"); + LOGE("Cipher final filed."); return HCF_ERR_CRYPTO_OPERATION; } output->len += len; @@ -228,7 +228,7 @@ static HcfResult DesDoFinal(CipherData *data, HcfBlob *input, HcfBlob *output) static HcfResult EngineDoFinal(HcfCipherGeneratorSpi *self, HcfBlob *input, HcfBlob *output) { if ((self == NULL) || (output == NULL)) { /* input maybe is null */ - LOGE("Invalid input parameter!"); + LOGE("Invalid input parameter."); return HCF_INVALID_PARAMS; } if (!IsClassMatch((const HcfObjectBase *)self, GetDesGeneratorClass())) { @@ -238,18 +238,18 @@ static HcfResult EngineDoFinal(HcfCipherGeneratorSpi *self, HcfBlob *input, HcfB HcfCipherDesGeneratorSpiOpensslImpl *cipherImpl = (HcfCipherDesGeneratorSpiOpensslImpl *)self; CipherData *data = cipherImpl->cipherData; if (data == NULL) { - LOGE("cipherData is null!"); + LOGE("CipherData is null."); return HCF_INVALID_PARAMS; } HcfResult res = AllocateOutput(input, output); if (res != HCF_SUCCESS) { - LOGE("AllocateOutput failed!"); + LOGE("AllocateOutput failed."); goto clearup; } res = DesDoFinal(data, input, output); if (res != HCF_SUCCESS) { - LOGE("DesDoFinal failed!"); + LOGE("DesDoFinal failed."); } clearup: if (res != HCF_SUCCESS) { @@ -278,13 +278,13 @@ static void EngineDesGeneratorDestroy(HcfObjectBase *self) HcfResult HcfCipherDesGeneratorSpiCreate(CipherAttr *attr, HcfCipherGeneratorSpi **generator) { if ((attr == NULL) || (generator == NULL)) { - LOGE("Invalid input parameter!"); + LOGE("Invalid input parameter."); return HCF_INVALID_PARAMS; } HcfCipherDesGeneratorSpiOpensslImpl *returnImpl = (HcfCipherDesGeneratorSpiOpensslImpl *)HcfMalloc( sizeof(HcfCipherDesGeneratorSpiOpensslImpl), 0); if (returnImpl == NULL) { - LOGE("Failed to allocate returnImpl memroy!"); + LOGE("Failed to allocate returnImpl memroy."); return HCF_ERR_MALLOC; } (void)memcpy_s(&returnImpl->attr, sizeof(CipherAttr), attr, sizeof(CipherAttr)); diff --git a/plugin/openssl_plugin/crypto_operation/aes/src/cipher_aes_common.c b/plugin/openssl_plugin/crypto_operation/cipher/src/cipher_aes_common.c similarity index 96% rename from plugin/openssl_plugin/crypto_operation/aes/src/cipher_aes_common.c rename to plugin/openssl_plugin/crypto_operation/cipher/src/cipher_aes_common.c index 933e307..ef62d00 100644 --- a/plugin/openssl_plugin/crypto_operation/aes/src/cipher_aes_common.c +++ b/plugin/openssl_plugin/crypto_operation/cipher/src/cipher_aes_common.c @@ -18,6 +18,7 @@ #include "log.h" #include "memory.h" #include "result.h" +#include "openssl_adapter.h" const unsigned char *GetIv(HcfParamsSpec *params) { @@ -55,7 +56,7 @@ void FreeCipherData(CipherData **data) return; } if ((*data)->ctx != NULL) { - EVP_CIPHER_CTX_free((*data)->ctx); + Openssl_EVP_CIPHER_CTX_free((*data)->ctx); (*data)->ctx = NULL; } if ((*data)->aad != NULL) { diff --git a/plugin/openssl_plugin/crypto_operation/aes/src/cipher_aes_openssl.c b/plugin/openssl_plugin/crypto_operation/cipher/src/cipher_aes_openssl.c similarity index 75% rename from plugin/openssl_plugin/crypto_operation/aes/src/cipher_aes_openssl.c rename to plugin/openssl_plugin/crypto_operation/cipher/src/cipher_aes_openssl.c index ac74eb2..122fa48 100644 --- a/plugin/openssl_plugin/crypto_operation/aes/src/cipher_aes_openssl.c +++ b/plugin/openssl_plugin/crypto_operation/cipher/src/cipher_aes_openssl.c @@ -21,6 +21,7 @@ #include "utils.h" #include "aes_openssl_common.h" #include "sym_common_defines.h" +#include "openssl_adapter.h" #include "openssl_common.h" #include "openssl_class.h" @@ -46,189 +47,189 @@ static const char *GetAesGeneratorClass(void) return OPENSSL_AES_CIPHER_CLASS; } -static const EVP_CIPHER *CipherEcbType(HCF_ALG_PARA_VALUE value) +static const EVP_CIPHER *CipherEcbType(SymKeyImpl *symKey) { - 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(); + switch (symKey->keyMaterial.len) { + case AES_SIZE_128: + return Openssl_EVP_aes_128_ecb(); + case AES_SIZE_192: + return Openssl_EVP_aes_192_ecb(); + case AES_SIZE_256: + return Openssl_EVP_aes_256_ecb(); default: break; } - return EVP_aes_128_ecb(); + return Openssl_EVP_aes_128_ecb(); } -static const EVP_CIPHER *CipherCbcType(HCF_ALG_PARA_VALUE value) +static const EVP_CIPHER *CipherCbcType(SymKeyImpl *symKey) { - 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(); + switch (symKey->keyMaterial.len) { + case AES_SIZE_128: + return Openssl_EVP_aes_128_cbc(); + case AES_SIZE_192: + return Openssl_EVP_aes_192_cbc(); + case AES_SIZE_256: + return Openssl_EVP_aes_256_cbc(); default: break; } - return EVP_aes_128_cbc(); + return Openssl_EVP_aes_128_cbc(); } -static const EVP_CIPHER *CipherCtrType(HCF_ALG_PARA_VALUE value) +static const EVP_CIPHER *CipherCtrType(SymKeyImpl *symKey) { - 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(); + switch (symKey->keyMaterial.len) { + case AES_SIZE_128: + return Openssl_EVP_aes_128_ctr(); + case AES_SIZE_192: + return Openssl_EVP_aes_192_ctr(); + case AES_SIZE_256: + return Openssl_EVP_aes_256_ctr(); default: break; } - return EVP_aes_128_ctr(); + return Openssl_EVP_aes_128_ctr(); } -static const EVP_CIPHER *CipherOfbType(HCF_ALG_PARA_VALUE value) +static const EVP_CIPHER *CipherOfbType(SymKeyImpl *symKey) { - 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(); + switch (symKey->keyMaterial.len) { + case AES_SIZE_128: + return Openssl_EVP_aes_128_ofb(); + case AES_SIZE_192: + return Openssl_EVP_aes_192_ofb(); + case AES_SIZE_256: + return Openssl_EVP_aes_256_ofb(); default: break; } - return EVP_aes_128_ofb(); + return Openssl_EVP_aes_128_ofb(); } -static const EVP_CIPHER *CipherCfbType(HCF_ALG_PARA_VALUE value) +static const EVP_CIPHER *CipherCfbType(SymKeyImpl *symKey) { - 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(); + switch (symKey->keyMaterial.len) { + case AES_SIZE_128: + return Openssl_EVP_aes_128_cfb(); + case AES_SIZE_192: + return Openssl_EVP_aes_192_cfb(); + case AES_SIZE_256: + return Openssl_EVP_aes_256_cfb(); default: break; } - return EVP_aes_128_cfb(); + return Openssl_EVP_aes_128_cfb(); } -static const EVP_CIPHER *CipherCfb1Type(HCF_ALG_PARA_VALUE value) +static const EVP_CIPHER *CipherCfb1Type(SymKeyImpl *symKey) { - 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(); + switch (symKey->keyMaterial.len) { + case AES_SIZE_128: + return Openssl_EVP_aes_128_cfb1(); + case AES_SIZE_192: + return Openssl_EVP_aes_192_cfb1(); + case AES_SIZE_256: + return Openssl_EVP_aes_256_cfb1(); default: break; } - return EVP_aes_128_cfb1(); + return Openssl_EVP_aes_128_cfb1(); } -static const EVP_CIPHER *CipherCfb128Type(HCF_ALG_PARA_VALUE value) +static const EVP_CIPHER *CipherCfb128Type(SymKeyImpl *symKey) { - 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(); + switch (symKey->keyMaterial.len) { + case AES_SIZE_128: + return Openssl_EVP_aes_128_cfb128(); + case AES_SIZE_192: + return Openssl_EVP_aes_192_cfb128(); + case AES_SIZE_256: + return Openssl_EVP_aes_256_cfb128(); default: break; } - return EVP_aes_128_cfb128(); + return Openssl_EVP_aes_128_cfb128(); } -static const EVP_CIPHER *CipherCfb8Type(HCF_ALG_PARA_VALUE value) +static const EVP_CIPHER *CipherCfb8Type(SymKeyImpl *symKey) { - 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(); + switch (symKey->keyMaterial.len) { + case AES_SIZE_128: + return Openssl_EVP_aes_128_cfb8(); + case AES_SIZE_192: + return Openssl_EVP_aes_192_cfb8(); + case AES_SIZE_256: + return Openssl_EVP_aes_256_cfb8(); default: break; } - return EVP_aes_128_cfb8(); + return Openssl_EVP_aes_128_cfb8(); } -static const EVP_CIPHER *CipherCcmType(HCF_ALG_PARA_VALUE value) +static const EVP_CIPHER *CipherCcmType(SymKeyImpl *symKey) { - 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(); + switch (symKey->keyMaterial.len) { + case AES_SIZE_128: + return Openssl_EVP_aes_128_ccm(); + case AES_SIZE_192: + return Openssl_EVP_aes_192_ccm(); + case AES_SIZE_256: + return Openssl_EVP_aes_256_ccm(); default: break; } - return EVP_aes_128_ccm(); + return Openssl_EVP_aes_128_ccm(); } -static const EVP_CIPHER *CipherGcmType(HCF_ALG_PARA_VALUE value) +static const EVP_CIPHER *CipherGcmType(SymKeyImpl *symKey) { - 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(); + switch (symKey->keyMaterial.len) { + case AES_SIZE_128: + return Openssl_EVP_aes_128_gcm(); + case AES_SIZE_192: + return Openssl_EVP_aes_192_gcm(); + case AES_SIZE_256: + return Openssl_EVP_aes_256_gcm(); default: break; } - return EVP_aes_128_gcm(); + return Openssl_EVP_aes_128_gcm(); } -static const EVP_CIPHER *DefaultCiherType(HCF_ALG_PARA_VALUE value) +static const EVP_CIPHER *DefaultCiherType(SymKeyImpl *symKey) { - return CipherEcbType(value); + return CipherEcbType(symKey); } -static const EVP_CIPHER *GetCipherType(HcfCipherAesGeneratorSpiOpensslImpl *impl) +static const EVP_CIPHER *GetCipherType(HcfCipherAesGeneratorSpiOpensslImpl *impl, SymKeyImpl *symKey) { switch (impl->attr.mode) { case HCF_ALG_MODE_ECB: - return CipherEcbType(impl->attr.keySize); + return CipherEcbType(symKey); case HCF_ALG_MODE_CBC: - return CipherCbcType(impl->attr.keySize); + return CipherCbcType(symKey); case HCF_ALG_MODE_CTR: - return CipherCtrType(impl->attr.keySize); + return CipherCtrType(symKey); case HCF_ALG_MODE_OFB: - return CipherOfbType(impl->attr.keySize); + return CipherOfbType(symKey); case HCF_ALG_MODE_CFB: - return CipherCfbType(impl->attr.keySize); + return CipherCfbType(symKey); case HCF_ALG_MODE_CFB1: - return CipherCfb1Type(impl->attr.keySize); + return CipherCfb1Type(symKey); case HCF_ALG_MODE_CFB8: - return CipherCfb8Type(impl->attr.keySize); + return CipherCfb8Type(symKey); case HCF_ALG_MODE_CFB128: - return CipherCfb128Type(impl->attr.keySize); + return CipherCfb128Type(symKey); case HCF_ALG_MODE_CCM: - return CipherCcmType(impl->attr.keySize); + return CipherCcmType(symKey); case HCF_ALG_MODE_GCM: - return CipherGcmType(impl->attr.keySize); + return CipherGcmType(symKey); default: break; } - return DefaultCiherType(impl->attr.keySize); + return DefaultCiherType(symKey); } static bool IsGcmParamsValid(HcfGcmParamsSpec *params) @@ -346,7 +347,7 @@ static HcfResult InitCipherData(HcfCipherGeneratorSpi *self, enum HcfCryptoMode HCF_ALG_PARA_VALUE mode = cipherImpl->attr.mode; (*cipherData)->enc = opMode; - (*cipherData)->ctx = EVP_CIPHER_CTX_new(); + (*cipherData)->ctx = Openssl_EVP_CIPHER_CTX_new(); if ((*cipherData)->ctx == NULL) { HcfPrintOpensslError(); LOGE("Failed to allocate ctx memory!"); @@ -369,22 +370,6 @@ clearup: return ret; } -static HcfResult IsKeySizeMatchCipher(SymKeyImpl *keyImpl, HcfCipherAesGeneratorSpiOpensslImpl *cipherImpl) -{ - size_t keySize = keyImpl->keyMaterial.len; - HCF_ALG_PARA_VALUE cipherValue = cipherImpl->attr.keySize; - switch (cipherValue) { - case HCF_ALG_AES_128: - return (keySize < AES_SIZE_128) ? HCF_INVALID_PARAMS : HCF_SUCCESS; - case HCF_ALG_AES_192: - return (keySize < AES_SIZE_192) ? HCF_INVALID_PARAMS : HCF_SUCCESS; - case HCF_ALG_AES_256: - return (keySize < AES_SIZE_256) ? HCF_INVALID_PARAMS : HCF_SUCCESS; - default: - return HCF_INVALID_PARAMS; - } -} - static HcfResult EngineCipherInit(HcfCipherGeneratorSpi *self, enum HcfCryptoMode opMode, HcfKey *key, HcfParamsSpec *params) { @@ -400,10 +385,7 @@ static HcfResult EngineCipherInit(HcfCipherGeneratorSpi *self, enum HcfCryptoMod HcfCipherAesGeneratorSpiOpensslImpl *cipherImpl = (HcfCipherAesGeneratorSpiOpensslImpl *)self; SymKeyImpl *keyImpl = (SymKeyImpl *)key; int enc = (opMode == ENCRYPT_MODE) ? 1 : 0; - if (IsKeySizeMatchCipher(keyImpl, cipherImpl) != HCF_SUCCESS) { - LOGE("Init failed, key size is smaller than cipher size."); - return HCF_INVALID_PARAMS; - } + cipherImpl->attr.keySize = keyImpl->keyMaterial.len; if (InitCipherData(self, opMode, params, &(cipherImpl->cipherData)) != HCF_SUCCESS) { LOGE("InitCipherData failed!"); return HCF_INVALID_PARAMS; @@ -411,15 +393,15 @@ static HcfResult EngineCipherInit(HcfCipherGeneratorSpi *self, enum HcfCryptoMod 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) { + if (Openssl_EVP_CipherInit(data->ctx, GetCipherType(cipherImpl, keyImpl), 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) { + if (Openssl_EVP_CIPHER_CTX_set_padding(data->ctx, padding) != HCF_OPENSSL_SUCCESS) { HcfPrintOpensslError(); LOGE("set padding failed!"); goto clearup; @@ -429,8 +411,8 @@ static HcfResult EngineCipherInit(HcfCipherGeneratorSpi *self, enum HcfCryptoMod 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) { + if (Openssl_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; @@ -443,7 +425,7 @@ clearup: static HcfResult CommonUpdate(CipherData *data, HcfBlob *input, HcfBlob *output) { - int32_t ret = EVP_CipherUpdate(data->ctx, output->data, (int *)&output->len, + int32_t ret = Openssl_EVP_CipherUpdate(data->ctx, output->data, (int *)&output->len, input->data, input->len); if (ret != HCF_OPENSSL_SUCCESS) { HcfPrintOpensslError(); @@ -456,20 +438,20 @@ static HcfResult CommonUpdate(CipherData *data, HcfBlob *input, HcfBlob *output) 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) { + if (Openssl_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); + int32_t ret = Openssl_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); + ret = Openssl_EVP_CipherUpdate(data->ctx, output->data, (int *)&output->len, input->data, input->len); if (ret != HCF_OPENSSL_SUCCESS) { HcfPrintOpensslError(); LOGE("gcm cipher update failed!"); @@ -543,14 +525,14 @@ static HcfResult CommonDoFinal(CipherData *data, HcfBlob *input, HcfBlob *output return res; } if (isUpdateInput) { - ret = EVP_CipherUpdate(data->ctx, output->data, (int32_t *)&len, input->data, input->len); + ret = Openssl_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); + ret = Openssl_EVP_CipherFinal_ex(data->ctx, output->data + len, (int *)&output->len); if (ret != HCF_OPENSSL_SUCCESS) { HcfPrintOpensslError(); LOGE("EVP_CipherFinal_ex failed!"); @@ -595,7 +577,7 @@ static HcfResult CcmDecryptDoFinal(HcfBlob *output, bool isUpdateInput) 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); + int32_t ret = Openssl_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!"); @@ -637,13 +619,13 @@ static HcfResult GcmDecryptDoFinal(CipherData *data, HcfBlob *input, HcfBlob *ou 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); + int32_t ret = Openssl_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); + ret = Openssl_EVP_CipherFinal_ex(data->ctx, output->data + len, (int *)&output->len); if (ret != HCF_OPENSSL_SUCCESS) { HcfPrintOpensslError(); LOGE("EVP_CipherFinal_ex failed!"); @@ -655,14 +637,14 @@ static HcfResult GcmDecryptDoFinal(CipherData *data, HcfBlob *input, HcfBlob *ou 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); + int32_t ret = Openssl_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, + ret = Openssl_EVP_CIPHER_CTX_ctrl(data->ctx, EVP_CTRL_AEAD_GET_TAG, data->tagLen, output->data + output->len); if (ret != HCF_OPENSSL_SUCCESS) { HcfPrintOpensslError(); diff --git a/plugin/openssl_plugin/crypto_operation/hmac/src/mac_openssl.c b/plugin/openssl_plugin/crypto_operation/hmac/src/mac_openssl.c index 958ffa9..98f66bd 100644 --- a/plugin/openssl_plugin/crypto_operation/hmac/src/mac_openssl.c +++ b/plugin/openssl_plugin/crypto_operation/hmac/src/mac_openssl.c @@ -15,6 +15,7 @@ #include "mac_openssl.h" +#include "openssl_adapter.h" #include "sym_common_defines.h" #include "openssl_common.h" #include "securec.h" @@ -23,8 +24,6 @@ #include "config.h" #include "utils.h" -#include - typedef struct { HcfMacSpi base; @@ -50,15 +49,15 @@ static HMAC_CTX *OpensslGetMacCtx(HcfMacSpi *self) static const EVP_MD *OpensslGetMacAlgoFromString(const char *mdName) { if (strcmp(mdName, "SHA1") == 0) { - return EVP_sha1(); + return Openssl_EVP_sha1(); } else if (strcmp(mdName, "SHA224") == 0) { - return EVP_sha224(); + return Openssl_EVP_sha224(); } else if (strcmp(mdName, "SHA256") == 0) { - return EVP_sha256(); + return Openssl_EVP_sha256(); } else if (strcmp(mdName, "SHA384") == 0) { - return EVP_sha384(); + return Openssl_EVP_sha384(); } else if (strcmp(mdName, "SHA512") == 0) { - return EVP_sha512(); + return Openssl_EVP_sha512(); } return NULL; } @@ -83,7 +82,7 @@ static HcfResult OpensslEngineInitMac(HcfMacSpi *self, const HcfSymKey *key) 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); + int32_t ret = Openssl_HMAC_Init_ex(OpensslGetMacCtx(self), keyBlob.data, keyBlob.len, mdfunc, NULL); if (ret != HCF_OPENSSL_SUCCESS) { LOGE("HMAC_Init_ex return error!"); HcfPrintOpensslError(); @@ -114,7 +113,7 @@ static HcfResult OpensslEngineDoFinalMac(HcfMacSpi *self, HcfBlob *output) } unsigned char outputBuf[EVP_MAX_MD_SIZE]; uint32_t outputLen; - int32_t ret = HMAC_Final(OpensslGetMacCtx(self), outputBuf, &outputLen); + int32_t ret = Openssl_HMAC_Final(OpensslGetMacCtx(self), outputBuf, &outputLen); if (ret != HCF_OPENSSL_SUCCESS) { LOGE("HMAC_Final return error!"); HcfPrintOpensslError(); @@ -136,7 +135,7 @@ static uint32_t OpensslEngineGetMacLength(HcfMacSpi *self) LOGE("The CTX is NULL!"); return HCF_OPENSSL_INVALID_MAC_LEN; } - return HMAC_size(OpensslGetMacCtx(self)); + return Openssl_HMAC_size(OpensslGetMacCtx(self)); } static void OpensslDestroyMac(HcfObjectBase *self) @@ -150,7 +149,7 @@ static void OpensslDestroyMac(HcfObjectBase *self) return; } if (OpensslGetMacCtx((HcfMacSpi *)self) != NULL) { - HMAC_CTX_free(OpensslGetMacCtx((HcfMacSpi *)self)); + Openssl_HMAC_CTX_free(OpensslGetMacCtx((HcfMacSpi *)self)); } HcfFree(self); } @@ -169,9 +168,9 @@ HcfResult OpensslMacSpiCreate(const char *opensslAlgoName, HcfMacSpi **spiObj) if (strcpy_s(returnSpiImpl->opensslAlgoName, HCF_MAX_ALGO_NAME_LEN, opensslAlgoName) != EOK) { LOGE("Failed to copy algoName!"); HcfFree(returnSpiImpl); - return HCF_ERR_COPY; + return HCF_INVALID_PARAMS; } - returnSpiImpl->ctx = HMAC_CTX_new(); + returnSpiImpl->ctx = Openssl_HMAC_CTX_new(); if (returnSpiImpl->ctx == NULL) { LOGE("Failed to create ctx!"); HcfFree(returnSpiImpl); diff --git a/plugin/openssl_plugin/crypto_operation/md/src/md_openssl.c b/plugin/openssl_plugin/crypto_operation/md/src/md_openssl.c index a7aa197..f0f8607 100644 --- a/plugin/openssl_plugin/crypto_operation/md/src/md_openssl.c +++ b/plugin/openssl_plugin/crypto_operation/md/src/md_openssl.c @@ -15,6 +15,7 @@ #include "md_openssl.h" +#include "openssl_adapter.h" #include "openssl_common.h" #include "securec.h" #include "log.h" @@ -22,8 +23,6 @@ #include "config.h" #include "utils.h" -#include - typedef struct { HcfMdSpi base; @@ -49,17 +48,17 @@ static EVP_MD_CTX *OpensslGetMdCtx(HcfMdSpi *self) static const EVP_MD *OpensslGetMdAlgoFromString(const char *mdName) { if (strcmp(mdName, "SHA1") == 0) { - return EVP_sha1(); + return Openssl_EVP_sha1(); } else if (strcmp(mdName, "SHA224") == 0) { - return EVP_sha224(); + return Openssl_EVP_sha224(); } else if (strcmp(mdName, "SHA256") == 0) { - return EVP_sha256(); + return Openssl_EVP_sha256(); } else if (strcmp(mdName, "SHA384") == 0) { - return EVP_sha384(); + return Openssl_EVP_sha384(); } else if (strcmp(mdName, "SHA512") == 0) { - return EVP_sha512(); + return Openssl_EVP_sha512(); } else if (strcmp(mdName, "MD5") == 0) { - return EVP_md5(); + return Openssl_EVP_md5(); } return NULL; } @@ -87,7 +86,7 @@ static HcfResult OpensslEngineDoFinalMd(HcfMdSpi *self, HcfBlob *output) } unsigned char outputBuf[EVP_MAX_MD_SIZE]; uint32_t outputLen; - int32_t ret = EVP_DigestFinal_ex(localCtx, outputBuf, &outputLen); + int32_t ret = Openssl_EVP_DigestFinal_ex(localCtx, outputBuf, &outputLen); if (ret != HCF_OPENSSL_SUCCESS) { LOGE("EVP_DigestFinal_ex return error!"); HcfPrintOpensslError(); @@ -109,7 +108,7 @@ static uint32_t OpensslEngineGetMdLength(HcfMdSpi *self) LOGE("The CTX is NULL!"); return HCF_OPENSSL_INVALID_MD_LEN; } - int32_t size = EVP_MD_CTX_size(OpensslGetMdCtx(self)); + int32_t size = Openssl_EVP_MD_CTX_size(OpensslGetMdCtx(self)); if (size < 0) { LOGE("Get the overflow path length in openssl!"); return HCF_OPENSSL_INVALID_MD_LEN; @@ -128,7 +127,7 @@ static void OpensslDestroyMd(HcfObjectBase *self) return; } if (OpensslGetMdCtx((HcfMdSpi *)self) != NULL) { - EVP_MD_CTX_free(OpensslGetMdCtx((HcfMdSpi *)self)); + Openssl_EVP_MD_CTX_free(OpensslGetMdCtx((HcfMdSpi *)self)); } HcfFree(self); } @@ -144,18 +143,18 @@ HcfResult OpensslMdSpiCreate(const char *opensslAlgoName, HcfMdSpi **spiObj) LOGE("Failed to allocate returnImpl memory!"); return HCF_ERR_MALLOC; } - returnSpiImpl->ctx = EVP_MD_CTX_new(); + returnSpiImpl->ctx = Openssl_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); + int32_t ret = Openssl_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); + Openssl_EVP_MD_CTX_free(returnSpiImpl->ctx); return HCF_ERR_CRYPTO_OPERATION; } returnSpiImpl->base.base.getClass = OpensslGetMdClass; diff --git a/plugin/openssl_plugin/rand/inc/rand_openssl.h b/plugin/openssl_plugin/crypto_operation/rand/inc/rand_openssl.h similarity index 100% rename from plugin/openssl_plugin/rand/inc/rand_openssl.h rename to plugin/openssl_plugin/crypto_operation/rand/inc/rand_openssl.h diff --git a/plugin/openssl_plugin/rand/src/rand_openssl.c b/plugin/openssl_plugin/crypto_operation/rand/src/rand_openssl.c similarity index 81% rename from plugin/openssl_plugin/rand/src/rand_openssl.c rename to plugin/openssl_plugin/crypto_operation/rand/src/rand_openssl.c index 91c0a3b..dff9713 100644 --- a/plugin/openssl_plugin/rand/src/rand_openssl.c +++ b/plugin/openssl_plugin/crypto_operation/rand/src/rand_openssl.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022 Huawei Device Co., Ltd. + * Copyright (C) 2022-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -15,14 +15,13 @@ #include "rand_openssl.h" +#include "openssl_adapter.h" #include "openssl_common.h" #include "securec.h" #include "log.h" #include "memory.h" #include "utils.h" -#include - typedef struct { HcfRandSpi base; } HcfRandSpiImpl; @@ -35,7 +34,7 @@ static const char *GetRandOpenSSLClass(void) static HcfResult OpensslGenerateRandom(HcfRandSpi *self, int32_t numBytes, HcfBlob *random) { unsigned char randBuf[numBytes]; - int32_t ret = RAND_priv_bytes(randBuf, numBytes); + int32_t ret = Openssl_RAND_priv_bytes(randBuf, numBytes); if (ret != HCF_OPENSSL_SUCCESS) { LOGE("RAND_bytes return error!"); HcfPrintOpensslError(); @@ -51,9 +50,23 @@ static HcfResult OpensslGenerateRandom(HcfRandSpi *self, int32_t numBytes, HcfBl return HCF_SUCCESS; } +static const char *GetRandAlgoName(HcfRandSpi *self) +{ + if (self == NULL) { + LOGE("Invalid input parameter."); + return NULL; + } + if (!IsClassMatch((HcfObjectBase *)self, GetRandOpenSSLClass())) { + LOGE("Class is not match."); + return NULL; + } + + return OPENSSL_RAND_ALGORITHM; +} + static void OpensslSetSeed(HcfRandSpi *self, HcfBlob *seed) { - RAND_seed(seed->data, seed->len); + Openssl_RAND_seed(seed->data, seed->len); } static void DestroyRandOpenssl(HcfObjectBase *self) @@ -84,6 +97,7 @@ HcfResult HcfRandSpiCreate(HcfRandSpi **spiObj) returnSpiImpl->base.base.destroy = DestroyRandOpenssl; returnSpiImpl->base.engineGenerateRandom = OpensslGenerateRandom; returnSpiImpl->base.engineSetSeed = OpensslSetSeed; + returnSpiImpl->base.engineGetAlgoName = GetRandAlgoName; *spiObj = (HcfRandSpi *)returnSpiImpl; return HCF_SUCCESS; } \ 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 deleted file mode 100644 index 6326164..0000000 --- a/plugin/openssl_plugin/crypto_operation/rsa/src/cipher_rsa_openssl.c +++ /dev/null @@ -1,338 +0,0 @@ -/* - * 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(void); - -typedef struct { - HcfCipherGeneratorSpi 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 = NewEvpPkeyByRsa(rsa, false); - if (pkey == NULL) { - LOGE("NewEvpPkeyByRsa fail"); - HcfPrintOpensslError(); - RSA_free(rsa); - 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(HcfCipherGeneratorSpi *self, enum HcfCryptoMode opMode, - HcfKey *key, HcfParamsSpec *params) -{ - LOGI("EngineInit start"); - 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(HcfCipherGeneratorSpi *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(HcfCipherGeneratorSpi *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); -} - -static const char *EngineGetClass(void) -{ - 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, HcfCipherGeneratorSpi **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; - } - (void)memcpy_s(&returnImpl->attr, sizeof(CipherAttr), params, sizeof(CipherAttr)); - - 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 = (HcfCipherGeneratorSpi *)returnImpl; - LOGI("Rsa Cipher create success."); - return HCF_SUCCESS; -} 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 index 9580590..5a9d24a 100644 --- 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 @@ -13,13 +13,13 @@ * 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_adapter.h" #include "openssl_common.h" #define MAX_KEY_STR_SIZE 12 @@ -119,7 +119,7 @@ static HcfResult RandomSymmKey(int32_t keyLen, HcfBlob *symmKey) LOGE("keyMaterial malloc failed!"); return HCF_ERR_MALLOC; } - int ret = RAND_priv_bytes(keyMaterial, keyLen); + int ret = Openssl_RAND_priv_bytes(keyMaterial, keyLen); if (ret != HCF_OPENSSL_SUCCESS) { LOGE("RAND_bytes failed!"); HcfPrintOpensslError(); @@ -137,7 +137,7 @@ static HcfResult HcfSymmKeySpiCreate(int32_t keyLen, SymKeyImpl *symKey) LOGE("Invalid input parameter!"); return HCF_INVALID_PARAMS; } - int32_t res = RandomSymmKey(keyLen, &symKey->keyMaterial); + HcfResult res = RandomSymmKey(keyLen, &symKey->keyMaterial); if (res != HCF_SUCCESS) { LOGE("RandomSymmKey failed!"); return res; @@ -259,7 +259,7 @@ static HcfResult GenerateSymmKey(HcfSymKeyGeneratorSpi *self, HcfSymKey **symmKe return HCF_ERR_MALLOC; } HcfSymKeyGeneratorSpiOpensslImpl *impl = (HcfSymKeyGeneratorSpiOpensslImpl *)self; - int32_t res = HcfSymmKeySpiCreate(impl->attr.keySize / KEY_BIT, returnSymmKey); + HcfResult res = HcfSymmKeySpiCreate(impl->attr.keySize / KEY_BIT, returnSymmKey); if (res != HCF_SUCCESS) { HcfFree(returnSymmKey); return res; @@ -297,7 +297,7 @@ static HcfResult ConvertSymmKey(HcfSymKeyGeneratorSpi *self, const HcfBlob *key, LOGE("Failed to allocate returnKeyPair memory!"); return HCF_ERR_MALLOC; } - int32_t res = CopySymmKey(key, &returnSymmKey->keyMaterial); + HcfResult res = CopySymmKey(key, &returnSymmKey->keyMaterial); if (res != HCF_SUCCESS) { HcfFree(returnSymmKey); return res; -- Gitee