diff --git a/frameworks/js/ani/BUILD.gn b/frameworks/js/ani/BUILD.gn index 554cf2584deb33432d845d1b9cf707cfa45afa44..13a32969c54d924bd91e17f09dda0733f60a2a7c 100644 --- a/frameworks/js/ani/BUILD.gn +++ b/frameworks/js/ani/BUILD.gn @@ -13,7 +13,6 @@ import("//base/security/crypto_framework/common/common.gni") import("//base/security/crypto_framework/frameworks/frameworks.gni") -import("//base/security/crypto_framework/plugin/plugin.gni") import("//build/config/components/ets_frontend/ets2abc_config.gni") import("//build/ohos.gni") import("//build/ohos/taihe_idl/taihe.gni") @@ -43,10 +42,16 @@ taihe_shared_library("crypto_framework_ani") { include_dirs += [ "${framework_path}/js/ani/inc" ] sources = get_target_outputs(":run_taihe") sources += [ + "${framework_path}/js/ani/src/ani_asy_key_generator.cpp", + "${framework_path}/js/ani/src/ani_cipher.cpp", "${framework_path}/js/ani/src/ani_constructor.cpp", + "${framework_path}/js/ani/src/ani_kdf.cpp", "${framework_path}/js/ani/src/ani_key.cpp", + "${framework_path}/js/ani/src/ani_key_pair.cpp", "${framework_path}/js/ani/src/ani_mac.cpp", "${framework_path}/js/ani/src/ani_md.cpp", + "${framework_path}/js/ani/src/ani_pri_key.cpp", + "${framework_path}/js/ani/src/ani_pub_key.cpp", "${framework_path}/js/ani/src/ani_rand.cpp", "${framework_path}/js/ani/src/ani_sym_key.cpp", "${framework_path}/js/ani/src/ani_sym_key_generator.cpp", @@ -72,7 +77,6 @@ taihe_shared_library("crypto_framework_ani") { "c_utils:utils", "hilog:libhilog", "openssl:libcrypto_shared", - "runtime_core:ani", ] } diff --git a/frameworks/js/ani/idl/ohos.security.cryptoFramework.cryptoFramework.taihe b/frameworks/js/ani/idl/ohos.security.cryptoFramework.cryptoFramework.taihe index 5eadd501352e43a9587158a0e870034c1badaa64..c9206dd7565e87452326cb5faae3aeb668930231 100644 --- a/frameworks/js/ani/idl/ohos.security.cryptoFramework.cryptoFramework.taihe +++ b/frameworks/js/ani/idl/ohos.security.cryptoFramework.cryptoFramework.taihe @@ -20,7 +20,22 @@ static { loadLibrary("crypto_framework_ani.z"); } """) struct DataBlob { - data: @typedarray Array; + data: @typedarray @typedarray Array; +} + +union OptString { + STRING: String; + @null EMPTY; +} + +union OptDataBlob { + DATABLOB: DataBlob; + @null EMPTY; +} + +union OptStrUint8Arr { + STRING: String; + UINT8ARRAY: @typedarray Array; } interface Md { @@ -60,14 +75,77 @@ interface Mac { function CreateMac(algName: String): Mac; interface Key { + GetKeyObj(): i64; GetEncoded(): DataBlob; @get GetFormat(): String; @get GetAlgName(): String; } -interface SymKey: Key { +enum AsyKeySpecEnum: i32 { + DSA_P_BN = 101, + DSA_Q_BN = 102, + DSA_G_BN = 103, + DSA_SK_BN = 104, + DSA_PK_BN = 105, + ECC_FP_P_BN = 201, + ECC_A_BN = 202, + ECC_B_BN = 203, + ECC_G_X_BN = 204, + ECC_G_Y_BN = 205, + ECC_N_BN = 206, + ECC_H_NUM = 207, + ECC_SK_BN = 208, + ECC_PK_X_BN = 209, + ECC_PK_Y_BN = 210, + ECC_FIELD_TYPE_STR = 211, + ECC_FIELD_SIZE_NUM = 212, + ECC_CURVE_NAME_STR = 213, + RSA_N_BN = 301, + RSA_SK_BN = 302, + RSA_PK_BN = 303, + DH_P_BN = 401, + DH_G_BN = 402, + DH_L_NUM = 403, + DH_SK_BN = 404, + DH_PK_BN = 405, + ED25519_SK_BN = 501, + ED25519_PK_BN = 502, + X25519_SK_BN = 601, + X25519_PK_BN = 602 +} + +struct KeyEncodingConfig { + password: String; + cipherName: String; +} + +union OptKeySpec { + BIGINT: @bigint Array; + STRING: String; + INT32: i32; +} + +interface PriKey: Key { ClearMem(): void; + GetAsyKeySpec(itemType: AsyKeySpecEnum): OptKeySpec; + GetEncodedDer(format: String): DataBlob; + GetEncodedPem(format: String, config: Optional): String; +} + +interface PubKey: Key { + GetAsyKeySpec(itemType: AsyKeySpecEnum): OptKeySpec; + GetEncodedDer(format: String): DataBlob; + GetEncodedPem(format: String): String; +} + +interface KeyPair { + @get GetPriKey(): PriKey; + @get GetPubKey(): PubKey; +} + +interface SymKey: Key { GetSymKeyObj(): i64; + ClearMem(): void; } interface SymKeyGenerator { @@ -80,3 +158,117 @@ interface SymKeyGenerator { @get GetAlgName(): String; } function CreateSymKeyGenerator(algName: String): SymKeyGenerator; + +interface AsyKeyGenerator { + @gen_async("generateKeyPair") + @gen_promise("generateKeyPair") + GenerateKeyPairSync(): KeyPair; + @gen_async("convertKey") + @gen_promise("convertKey") + ConvertKeySync(pubKey: OptDataBlob, priKey: OptDataBlob): KeyPair; + @gen_async("convertKeySync") + @gen_promise("convertKeySync") + ConvertPemKeySync(pubKey: OptString, priKey: OptString, password: Optional): KeyPair; + @get GetAlgName(): String; +} +function CreateAsyKeyGenerator(algName: String): AsyKeyGenerator; + +struct KdfSpec { + algName: String; +} + +struct PBKDF2Spec { + @extends base: KdfSpec; + password: OptStrUint8Arr; + salt: @typedarray Array; + iterations: i32; + keySize: i32; +} + +struct HKDFSpec { + @extends base: KdfSpec; + key: OptStrUint8Arr; + salt: @typedarray Array; + info: @typedarray Array; + keySize: i32; +} + +struct ScryptSpec { + @extends base: KdfSpec; + passphrase: OptStrUint8Arr; + salt: @typedarray Array; + n: i32; + r: i32; + p: i32; + maxMemory: i32; + keySize: i32; +} + +union OptExtKdfSpec { + PBKDF2SPEC: PBKDF2Spec; + HKDFSPEC: HKDFSpec; + SCRYPTSPEC: ScryptSpec; + KDFSPEC: KdfSpec; +} + +interface Kdf { + @gen_async("generateSecret") + @gen_promise("generateSecret") + GenerateSecretSync(params: OptExtKdfSpec): DataBlob; + @get GetAlgName(): String; +} +function CreateKdf(algName: String): Kdf; + +enum CryptoMode: i32 { + ENCRYPT_MODE = 0, + DECRYPT_MODE = 1 +} + +struct ParamsSpec { + algName: String; +} + +struct IvParamsSpec { + @extends base: ParamsSpec; + iv: DataBlob; +} + +struct GcmParamsSpec { + @extends base: ParamsSpec; + iv: DataBlob; + aad: DataBlob; + authTag: DataBlob; +} + +struct CcmParamsSpec { + @extends base: ParamsSpec; + iv: DataBlob; + aad: DataBlob; + authTag: DataBlob; +} + +union OptExtParamsSpec { + IVPARAMSSPEC: IvParamsSpec; + GCMPARAMSSPEC: GcmParamsSpec; + CCMPARAMSSPEC: CcmParamsSpec; + PARAMSSPEC: ParamsSpec; +} + +union OptParamsSpec { + PARAMSSPEC: OptExtParamsSpec; + @null EMPTY; +} + +interface Cipher { + @gen_async("init") + @gen_promise("init") + InitSync(opMode: CryptoMode, key: Key, params: OptParamsSpec): void; + @gen_async("update") + @gen_promise("update") + UpdateSync(input: DataBlob): DataBlob; + @gen_async("doFinal") + @gen_promise("doFinal") + DoFinalSync(input: OptDataBlob): DataBlob; + @get GetAlgName(): String; +} +function CreateCipher(transformation: String): Cipher; diff --git a/frameworks/js/ani/inc/ani_asy_key_generator.h b/frameworks/js/ani/inc/ani_asy_key_generator.h new file mode 100644 index 0000000000000000000000000000000000000000..a38e565bc6e7a7a04c31444915a02a8918c92478 --- /dev/null +++ b/frameworks/js/ani/inc/ani_asy_key_generator.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2025-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANI_ASY_KEY_GENERATOR_H +#define ANI_ASY_KEY_GENERATOR_H + +#include "ani_common.h" +#include "asy_key_generator.h" + +namespace ANI::CryptoFramework { +using namespace taihe; +using namespace ohos::security::cryptoFramework::cryptoFramework; + +class AsyKeyGeneratorImpl { +public: + AsyKeyGeneratorImpl(); + explicit AsyKeyGeneratorImpl(HcfAsyKeyGenerator *generator); + ~AsyKeyGeneratorImpl(); + + KeyPair GenerateKeyPairSync(); + KeyPair ConvertKeySync(OptDataBlob const& pubKey, OptDataBlob const& priKey); + KeyPair ConvertPemKeySync(OptString const& pubKey, OptString const& priKey, optional_view password); + string GetAlgName(); + +private: + HcfAsyKeyGenerator *generator_ = nullptr; +}; +} // namespace ANI::CryptoFramework + +#endif // ANI_ASY_KEY_GENERATOR_H diff --git a/frameworks/js/ani/inc/ani_cipher.h b/frameworks/js/ani/inc/ani_cipher.h new file mode 100644 index 0000000000000000000000000000000000000000..e01bd5ef4131e719d9b24aeb766df1569ae9b95b --- /dev/null +++ b/frameworks/js/ani/inc/ani_cipher.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2025-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANI_CIPHER_H +#define ANI_CIPHER_H + +#include "ani_common.h" +#include "cipher.h" + +namespace ANI::CryptoFramework { +using namespace taihe; +using namespace ohos::security::cryptoFramework::cryptoFramework; + +class CipherImpl { +public: + CipherImpl(); + explicit CipherImpl(HcfCipher *cipher); + ~CipherImpl(); + + void InitSync(CryptoMode opMode, weak::Key key, OptParamsSpec const& params); + DataBlob UpdateSync(DataBlob const& input); + DataBlob DoFinalSync(OptDataBlob const& input); + string GetAlgName(); + +private: + HcfCipher *cipher_ = nullptr; +}; +} // namespace ANI::CryptoFramework + +#endif // ANI_CIPHER_H diff --git a/frameworks/js/ani/inc/ani_common.h b/frameworks/js/ani/inc/ani_common.h index ce4e8ba6a67188432ee1ce0c9a0ba6c07e57a3df..a4498760ba7745fa6ea9192d3914b7c9f69135c5 100644 --- a/frameworks/js/ani/inc/ani_common.h +++ b/frameworks/js/ani/inc/ani_common.h @@ -24,12 +24,13 @@ #include "log.h" #include "blob.h" #include "result.h" +#include "memory.h" #include "object_base.h" #define ANI_LOGE_THROW(code, msg) \ do { \ - taihe::set_business_error(code, msg); \ LOGE(msg); \ + set_business_error(code, msg); \ } while (0) #endif // ANI_COMMON_H diff --git a/frameworks/js/ani/inc/ani_kdf.h b/frameworks/js/ani/inc/ani_kdf.h new file mode 100644 index 0000000000000000000000000000000000000000..a788af533a6c1763770847c29e59ac9842205d35 --- /dev/null +++ b/frameworks/js/ani/inc/ani_kdf.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2025-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANI_MAC_H +#define ANI_MAC_H + +#include "ani_common.h" +#include "kdf.h" + +namespace ANI::CryptoFramework { +using namespace taihe; +using namespace ohos::security::cryptoFramework::cryptoFramework; + +class KdfImpl { +public: + KdfImpl(); + explicit KdfImpl(HcfKdf *kdf); + ~KdfImpl(); + + DataBlob GenerateSecretSync(OptExtKdfSpec const& params); + string GetAlgName(); + +private: + HcfKdf *kdf_ = nullptr; +}; +} // namespace ANI::CryptoFramework + +#endif // ANI_MAC_H diff --git a/frameworks/js/ani/inc/ani_key.h b/frameworks/js/ani/inc/ani_key.h index 1cf1f4021071d687dc44585217470366f19c09df..4e59de39a109155497c1f78bb78b5eb57f1f4b36 100644 --- a/frameworks/js/ani/inc/ani_key.h +++ b/frameworks/js/ani/inc/ani_key.h @@ -26,11 +26,16 @@ using namespace ohos::security::cryptoFramework::cryptoFramework; class KeyImpl { public: KeyImpl(); + explicit KeyImpl(HcfKey *key); ~KeyImpl(); + int64_t GetKeyObj(); DataBlob GetEncoded(); string GetFormat(); string GetAlgName(); + +private: + HcfKey *key_ = nullptr; }; } // namespace ANI::CryptoFramework diff --git a/frameworks/js/ani/inc/ani_key_pair.h b/frameworks/js/ani/inc/ani_key_pair.h new file mode 100644 index 0000000000000000000000000000000000000000..af3b14f6129c42b7df206487a6b3860265eb7242 --- /dev/null +++ b/frameworks/js/ani/inc/ani_key_pair.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2025-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANI_KEY_PAIR_H +#define ANI_KEY_PAIR_H + +#include "ani_common.h" +#include "key_pair.h" + +namespace ANI::CryptoFramework { +using namespace taihe; +using namespace ohos::security::cryptoFramework::cryptoFramework; + +class KeyPairImpl { +public: + KeyPairImpl(); + explicit KeyPairImpl(HcfKeyPair *keyPair); + ~KeyPairImpl(); + + PriKey GetPriKey(); + PubKey GetPubKey(); + +private: + HcfKeyPair *keyPair_ = nullptr; +}; +} // namespace ANI::CryptoFramework + +#endif // ANI_KEY_PAIR_H diff --git a/frameworks/js/ani/inc/ani_mac.h b/frameworks/js/ani/inc/ani_mac.h index 0416ef2670564b81cecea7032a1aae9e8f85bdd3..339ae7bd30ce888bd6aa9ccdd40c44e04eedead0 100644 --- a/frameworks/js/ani/inc/ani_mac.h +++ b/frameworks/js/ani/inc/ani_mac.h @@ -26,7 +26,7 @@ using namespace ohos::security::cryptoFramework::cryptoFramework; class MacImpl { public: MacImpl(); - explicit MacImpl(HcfMac *obj); + explicit MacImpl(HcfMac *mac); ~MacImpl(); void InitSync(weak::SymKey key); @@ -36,7 +36,7 @@ public: string GetAlgName(); private: - HcfMac *macObj = nullptr; + HcfMac *mac_ = nullptr; }; } // namespace ANI::CryptoFramework diff --git a/frameworks/js/ani/inc/ani_md.h b/frameworks/js/ani/inc/ani_md.h index 35cbe7cc7bccec19761845672133eed483b9fc37..fb0adc356fddd57fb54e6f217a702421768d39a8 100644 --- a/frameworks/js/ani/inc/ani_md.h +++ b/frameworks/js/ani/inc/ani_md.h @@ -26,7 +26,7 @@ using namespace ohos::security::cryptoFramework::cryptoFramework; class MdImpl { public: MdImpl(); - explicit MdImpl(HcfMd *obj); + explicit MdImpl(HcfMd *md); ~MdImpl(); void UpdateSync(DataBlob const& input); @@ -35,7 +35,7 @@ public: string GetAlgName(); private: - HcfMd *mdObj = nullptr; + HcfMd *md_ = nullptr; }; } // namespace ANI::CryptoFramework diff --git a/frameworks/js/ani/inc/ani_pri_key.h b/frameworks/js/ani/inc/ani_pri_key.h new file mode 100644 index 0000000000000000000000000000000000000000..26bbf67204f8c72a360181ff6e44043266b67e48 --- /dev/null +++ b/frameworks/js/ani/inc/ani_pri_key.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2025-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANI_PRI_KEY_H +#define ANI_PRI_KEY_H + +#include "ani_common.h" +#include "pri_key.h" + +namespace ANI::CryptoFramework { +using namespace taihe; +using namespace ohos::security::cryptoFramework::cryptoFramework; + +class PriKeyImpl { +public: + PriKeyImpl(); + explicit PriKeyImpl(HcfPriKey *priKey); + ~PriKeyImpl(); + + void ClearMem(); + OptKeySpec GetAsyKeySpec(AsyKeySpecEnum itemType); + DataBlob GetEncodedDer(string_view format); + string GetEncodedPem(string_view format, optional_view config); + int64_t GetKeyObj(); + DataBlob GetEncoded(); + string GetFormat(); + string GetAlgName(); + +private: + HcfPriKey *priKey_ = nullptr; +}; +} // namespace ANI::CryptoFramework + +#endif // ANI_PRI_KEY_H diff --git a/frameworks/js/ani/inc/ani_pub_key.h b/frameworks/js/ani/inc/ani_pub_key.h new file mode 100644 index 0000000000000000000000000000000000000000..af63a254e18d29158ed2d91c4f29d19b488fdb7c --- /dev/null +++ b/frameworks/js/ani/inc/ani_pub_key.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2025-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ANI_PUB_KEY_H +#define ANI_PUB_KEY_H + +#include "ani_common.h" +#include "pub_key.h" + +namespace ANI::CryptoFramework { +using namespace taihe; +using namespace ohos::security::cryptoFramework::cryptoFramework; + +class PubKeyImpl { +public: + PubKeyImpl(); + explicit PubKeyImpl(HcfPubKey *pubKey); + ~PubKeyImpl(); + + OptKeySpec GetAsyKeySpec(AsyKeySpecEnum itemType); + DataBlob GetEncodedDer(string_view format); + string GetEncodedPem(string_view format); + int64_t GetKeyObj(); + DataBlob GetEncoded(); + string GetFormat(); + string GetAlgName(); + +private: + HcfPubKey *pubKey_ = nullptr; +}; +} // namespace ANI::CryptoFramework + +#endif // ANI_PUB_KEY_H diff --git a/frameworks/js/ani/inc/ani_rand.h b/frameworks/js/ani/inc/ani_rand.h index f027dcd3a1202548568f1e77068803c8cdc5cb04..1a5d1892074b4e59214456d9f19c3c3d9a2ea772 100644 --- a/frameworks/js/ani/inc/ani_rand.h +++ b/frameworks/js/ani/inc/ani_rand.h @@ -26,7 +26,7 @@ using namespace ohos::security::cryptoFramework::cryptoFramework; class RandomImpl { public: RandomImpl(); - explicit RandomImpl(HcfRand *obj); + explicit RandomImpl(HcfRand *rand); ~RandomImpl(); DataBlob GenerateRandomSync(int32_t len); @@ -34,7 +34,7 @@ public: string GetAlgName(); private: - HcfRand *randObj = nullptr; + HcfRand *rand_ = nullptr; }; } // namespace ANI::CryptoFramework diff --git a/frameworks/js/ani/inc/ani_sym_key.h b/frameworks/js/ani/inc/ani_sym_key.h index af42597e1eaf517827d5e5fa5a43b4171817a0bf..f18dce4a2143768e3e0e8e675b5aa8dafb22298e 100644 --- a/frameworks/js/ani/inc/ani_sym_key.h +++ b/frameworks/js/ani/inc/ani_sym_key.h @@ -26,17 +26,18 @@ using namespace ohos::security::cryptoFramework::cryptoFramework; class SymKeyImpl { public: SymKeyImpl(); - explicit SymKeyImpl(HcfSymKey *obj); + explicit SymKeyImpl(HcfSymKey *symKey); ~SymKeyImpl(); - void ClearMem(); + int64_t GetKeyObj(); int64_t GetSymKeyObj(); + void ClearMem(); DataBlob GetEncoded(); string GetFormat(); string GetAlgName(); private: - HcfSymKey *symKey = nullptr; + HcfSymKey *symKey_ = nullptr; }; } // namespace ANI::CryptoFramework diff --git a/frameworks/js/ani/inc/ani_sym_key_generator.h b/frameworks/js/ani/inc/ani_sym_key_generator.h index 4ad82506d77db225d8c87930f0fdd64c23e6d690..ae8ad16d794f0f1ffd118c43fe575735888c936c 100644 --- a/frameworks/js/ani/inc/ani_sym_key_generator.h +++ b/frameworks/js/ani/inc/ani_sym_key_generator.h @@ -26,7 +26,7 @@ using namespace ohos::security::cryptoFramework::cryptoFramework; class SymKeyGeneratorImpl { public: SymKeyGeneratorImpl(); - explicit SymKeyGeneratorImpl(HcfSymKeyGenerator *obj); + explicit SymKeyGeneratorImpl(HcfSymKeyGenerator *generator); ~SymKeyGeneratorImpl(); SymKey GenerateSymKeySync(); @@ -34,7 +34,7 @@ public: string GetAlgName(); private: - HcfSymKeyGenerator *generator = nullptr; + HcfSymKeyGenerator *generator_ = nullptr; }; } // namespace ANI::CryptoFramework diff --git a/frameworks/js/ani/src/ani_asy_key_generator.cpp b/frameworks/js/ani/src/ani_asy_key_generator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9b75a76065ee236b18e4ad5915cdafa8c836c11a --- /dev/null +++ b/frameworks/js/ani/src/ani_asy_key_generator.cpp @@ -0,0 +1,108 @@ +/* + * Copyright (c)2025-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "ani_asy_key_generator.h" +#include "ani_key_pair.h" + +using namespace taihe; +using namespace ohos::security::cryptoFramework::cryptoFramework; +using namespace ANI::CryptoFramework; + +namespace ANI::CryptoFramework { +AsyKeyGeneratorImpl::AsyKeyGeneratorImpl() {} + +AsyKeyGeneratorImpl::AsyKeyGeneratorImpl(HcfAsyKeyGenerator *generator) : generator_(generator) {} + +AsyKeyGeneratorImpl::~AsyKeyGeneratorImpl() +{ + HcfObjDestroy(this->generator_); + this->generator_ = nullptr; +} + +KeyPair AsyKeyGeneratorImpl::GenerateKeyPairSync() +{ + if (this->generator_ == nullptr) { + ANI_LOGE_THROW(HCF_INVALID_PARAMS, "generator obj is nullptr!"); + return make_holder(); + } + HcfKeyPair *keyPair = nullptr; + HcfResult res = this->generator_->generateKeyPair(this->generator_, nullptr, &(keyPair)); + if (res != HCF_SUCCESS) { + ANI_LOGE_THROW(res, "generate key pair fail."); + return make_holder(); + } + return make_holder(keyPair); +} + +KeyPair AsyKeyGeneratorImpl::ConvertKeySync(OptDataBlob const& pubKey, OptDataBlob const& priKey) +{ + if (this->generator_ == nullptr) { + ANI_LOGE_THROW(HCF_INVALID_PARAMS, "generator obj is nullptr!"); + return make_holder(); + } + HcfKeyPair *keyPair = nullptr; + HcfBlob *pubKeyBlob = nullptr; + HcfBlob *priKeyBlob = nullptr; + HcfBlob skBlob = { .data = nullptr, .len = 0 }; + HcfBlob pkBlob = { .data = nullptr, .len = 0 }; + if (pubKey.get_tag() == OptDataBlob::tag_t::DATABLOB) { + pkBlob.data = pubKey.get_DATABLOB_ref().data.data(); + pkBlob.len = pubKey.get_DATABLOB_ref().data.size(); + pubKeyBlob = &pkBlob; + } + if (priKey.get_tag() == OptDataBlob::tag_t::DATABLOB) { + skBlob.data = priKey.get_DATABLOB_ref().data.data(); + skBlob.len = priKey.get_DATABLOB_ref().data.size(); + priKeyBlob = &skBlob; + } + HcfResult res = this->generator_->convertKey(this->generator_, nullptr, pubKeyBlob, priKeyBlob, &(keyPair)); + if (res != HCF_SUCCESS) { + ANI_LOGE_THROW(res, "convert key fail."); + return make_holder(); + } + return make_holder(keyPair); +} + +KeyPair AsyKeyGeneratorImpl::ConvertPemKeySync(OptString const& pubKey, + OptString const& priKey, optional_view password) +{ + // The parameters in the make_holder function should be of the same type + // as the parameters in the constructor of the actual implementation class. + return make_holder(); +} + +string AsyKeyGeneratorImpl::GetAlgName() +{ + if (this->generator_ == nullptr) { + ANI_LOGE_THROW(HCF_INVALID_PARAMS, "generator obj is nullptr!"); + return ""; + } + const char *algName = this->generator_->getAlgoName(this->generator_); + return (algName == nullptr) ? "" : string(algName); +} + +AsyKeyGenerator CreateAsyKeyGenerator(string_view algName) +{ + HcfAsyKeyGenerator *generator = nullptr; + HcfResult res = HcfAsyKeyGeneratorCreate(algName.c_str(), &generator); + if (res != HCF_SUCCESS) { + ANI_LOGE_THROW(res, "create C generator obj fail!"); + return make_holder(); + } + return make_holder(generator); +} +} // namespace ANI::CryptoFramework + +TH_EXPORT_CPP_API_CreateAsyKeyGenerator(CreateAsyKeyGenerator); diff --git a/frameworks/js/ani/src/ani_cipher.cpp b/frameworks/js/ani/src/ani_cipher.cpp new file mode 100644 index 0000000000000000000000000000000000000000..df7d83569d23d3ea845cac06f1de1f0fde15cead --- /dev/null +++ b/frameworks/js/ani/src/ani_cipher.cpp @@ -0,0 +1,185 @@ +/* + * Copyright (c)2025-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "ani_cipher.h" +#include "detailed_iv_params.h" +#include "detailed_gcm_params.h" +#include "detailed_ccm_params.h" + +using namespace taihe; +using namespace ohos::security::cryptoFramework::cryptoFramework; +using namespace ANI::CryptoFramework; + +namespace { +const std::string IV_PARAMS_SPEC = "IvParamsSpec"; +const std::string GCM_PARAMS_SPEC = "GcmParamsSpec"; +const std::string CCM_PARAMS_SPEC = "CcmParamsSpec"; + +const char *GetIvParamsSpecType() +{ + return IV_PARAMS_SPEC.c_str(); +} + +const char *GetGcmParamsSpecType() +{ + return GCM_PARAMS_SPEC.c_str(); +} + +const char *GetCcmParamsSpecType() +{ + return CCM_PARAMS_SPEC.c_str(); +} + +void SetIvParamsSpecAttribute(const IvParamsSpec ¶ms, HcfIvParamsSpec &ivParamsSpec) +{ + ivParamsSpec.base.getType = GetIvParamsSpecType; + ivParamsSpec.iv.data = params.iv.data.data(); + ivParamsSpec.iv.len = params.iv.data.size(); +} + +void SetGcmParamsSpecAttribute(const GcmParamsSpec ¶ms, HcfGcmParamsSpec &gcmParamsSpec) +{ + gcmParamsSpec.base.getType = GetGcmParamsSpecType; + gcmParamsSpec.iv.data = params.iv.data.data(); + gcmParamsSpec.iv.len = params.iv.data.size(); + gcmParamsSpec.aad.data = params.aad.data.data(); + gcmParamsSpec.aad.len = params.aad.data.size(); + gcmParamsSpec.tag.data = params.authTag.data.data(); + gcmParamsSpec.tag.len = params.authTag.data.size(); +} + +void SetCcmParamsSpecAttribute(const CcmParamsSpec ¶ms, HcfCcmParamsSpec &ccmParamsSpec) +{ + ccmParamsSpec.base.getType = GetCcmParamsSpecType; + ccmParamsSpec.iv.data = params.iv.data.data(); + ccmParamsSpec.iv.len = params.iv.data.size(); + ccmParamsSpec.aad.data = params.aad.data.data(); + ccmParamsSpec.aad.len = params.aad.data.size(); + ccmParamsSpec.tag.data = params.authTag.data.data(); + ccmParamsSpec.tag.len = params.authTag.data.size(); +} +} // namespace + +namespace ANI::CryptoFramework { +CipherImpl::CipherImpl() {} + +CipherImpl::CipherImpl(HcfCipher *cipher) : cipher_(cipher) {} + +CipherImpl::~CipherImpl() +{ + HcfObjDestroy(this->cipher_); + this->cipher_ = nullptr; +} + +void CipherImpl::InitSync(CryptoMode opMode, weak::Key key, OptParamsSpec const& params) +{ + if (this->cipher_ == nullptr) { + ANI_LOGE_THROW(HCF_INVALID_PARAMS, "cipher obj is nullptr!"); + return; + } + HcfParamsSpec *paramsSpec = nullptr; + HcfIvParamsSpec ivParamsSpec = {}; + HcfGcmParamsSpec gcmParamsSpec = {}; + HcfCcmParamsSpec ccmParamsSpec = {}; + if (params.get_tag() != OptParamsSpec::tag_t::EMPTY) { + const OptExtParamsSpec &tmp = params.get_PARAMSSPEC_ref(); + const std::string &algName = tmp.get_PARAMSSPEC_ref().algName.c_str(); + if (tmp.get_tag() == OptExtParamsSpec::tag_t::IVPARAMSSPEC && algName == IV_PARAMS_SPEC) { + SetIvParamsSpecAttribute(tmp.get_IVPARAMSSPEC_ref(), ivParamsSpec); + paramsSpec = reinterpret_cast(&ivParamsSpec); + } else if (tmp.get_tag() == OptExtParamsSpec::tag_t::GCMPARAMSSPEC && algName == GCM_PARAMS_SPEC) { + SetGcmParamsSpecAttribute(tmp.get_GCMPARAMSSPEC_ref(), gcmParamsSpec); + paramsSpec = reinterpret_cast(&gcmParamsSpec); + } else if (tmp.get_tag() == OptExtParamsSpec::tag_t::CCMPARAMSSPEC && algName == CCM_PARAMS_SPEC) { + SetCcmParamsSpecAttribute(tmp.get_CCMPARAMSSPEC_ref(), ccmParamsSpec); + paramsSpec = reinterpret_cast(&ccmParamsSpec); + } else { + ANI_LOGE_THROW(HCF_INVALID_PARAMS, "invalid cipher spec!"); + return; + } + } + HcfKey *obj = reinterpret_cast(key->GetKeyObj()); + HcfResult res = this->cipher_->init(this->cipher_, static_cast(opMode.get_value()), obj, paramsSpec); + if (res != HCF_SUCCESS) { + ANI_LOGE_THROW(res, "init cipher fail."); + return; + } +} + +DataBlob CipherImpl::UpdateSync(DataBlob const& input) +{ + if (this->cipher_ == nullptr) { + ANI_LOGE_THROW(HCF_INVALID_PARAMS, "cipher obj is nullptr!"); + return { array(nullptr, 0) }; + } + HcfBlob inBlob = { .data = input.data.data(), .len = input.data.size() }; + HcfBlob outBlob = { .data = nullptr, .len = 0 }; + HcfResult res = this->cipher_->update(this->cipher_, &inBlob, &outBlob); + if (res != HCF_SUCCESS) { + ANI_LOGE_THROW(res, "cipher update failed!"); + return { array(nullptr, 0) }; + } + array data(move_data_t{}, outBlob.data, outBlob.len); + HcfBlobDataClearAndFree(&outBlob); + return { data }; +} + +DataBlob CipherImpl::DoFinalSync(OptDataBlob const& input) +{ + if (this->cipher_ == nullptr) { + ANI_LOGE_THROW(HCF_INVALID_PARAMS, "cipher obj is nullptr!"); + return { array(nullptr, 0) }; + } + HcfBlob *inBlob = nullptr; + HcfBlob dataBlob = { .data = nullptr, .len = 0 }; + if (input.get_tag() == OptDataBlob::tag_t::DATABLOB) { + dataBlob.data = input.get_DATABLOB_ref().data.data(); + dataBlob.len = input.get_DATABLOB_ref().data.size(); + inBlob = &dataBlob; + } + HcfBlob outBlob = { .data = nullptr, .len = 0 }; + HcfResult res = this->cipher_->doFinal(this->cipher_, inBlob, &outBlob); + if (res != HCF_SUCCESS) { + ANI_LOGE_THROW(res, "cipher doFinal failed!"); + return { array(nullptr, 0) }; + } + array data(move_data_t{}, outBlob.data, outBlob.len); + HcfBlobDataClearAndFree(&outBlob); + return { data }; +} + +string CipherImpl::GetAlgName() +{ + if (this->cipher_ == nullptr) { + ANI_LOGE_THROW(HCF_INVALID_PARAMS, "cipher obj is nullptr!"); + return ""; + } + const char *algName = this->cipher_->getAlgorithm(this->cipher_); + return (algName == nullptr) ? "" : string(algName); +} + +Cipher CreateCipher(string_view transformation) +{ + HcfCipher *cipher = nullptr; + HcfResult res = HcfCipherCreate(transformation.c_str(), &cipher); + if (res != HCF_SUCCESS) { + ANI_LOGE_THROW(res, "create C cipher obj fail!"); + return make_holder(); + } + return make_holder(cipher); +} +} // namespace ANI::CryptoFramework + +TH_EXPORT_CPP_API_CreateCipher(CreateCipher); diff --git a/frameworks/js/ani/src/ani_constructor.cpp b/frameworks/js/ani/src/ani_constructor.cpp index 9d38ae4c497803e0ad462e2bec33e2b7d09ebf37..15c0af8e404db610e1851786cea0d52976ed45f2 100644 --- a/frameworks/js/ani/src/ani_constructor.cpp +++ b/frameworks/js/ani/src/ani_constructor.cpp @@ -22,7 +22,7 @@ ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result) return ANI_ERROR; } if (ANI_OK != ohos::security::cryptoFramework::cryptoFramework::ANIRegister(env)) { - std::cerr << "ohos::security::cryptoFramework::cryptoFramework" << std::endl; + std::cerr << "Error from ohos::security::cryptoFramework::cryptoFramework::ANIRegister" << std::endl; return ANI_ERROR; } *result = ANI_VERSION_1; diff --git a/frameworks/js/ani/src/ani_kdf.cpp b/frameworks/js/ani/src/ani_kdf.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4c9523c8ebc6566382597c167f50017beb3ef49d --- /dev/null +++ b/frameworks/js/ani/src/ani_kdf.cpp @@ -0,0 +1,162 @@ +/* + * Copyright (c) 2025-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "ani_kdf.h" +#include "detailed_pbkdf2_params.h" +#include "detailed_hkdf_params.h" +#include "detailed_scrypt_params.h" + +using namespace taihe; +using namespace ohos::security::cryptoFramework::cryptoFramework; +using namespace ANI::CryptoFramework; + +namespace { +const std::string PBKDF2_ALG_NAME = "PBKDF2"; +const std::string HKDF_ALG_NAME = "HKDF"; +const std::string SCRYPT_ALG_NAME = "SCRYPT"; + +void SetPBKDF2ParamsSpecAttribute(const PBKDF2Spec ¶ms, HcfPBKDF2ParamsSpec &pbkdf2Spec, HcfBlob &outBlob) +{ + pbkdf2Spec.base.algName = params.base.algName.c_str(); + if (params.password.get_tag() == OptStrUint8Arr::tag_t::STRING) { + pbkdf2Spec.password.data = reinterpret_cast + (const_cast(params.password.get_STRING_ref().c_str())); + pbkdf2Spec.password.len = params.password.get_STRING_ref().size(); + } else { // OptStrUint8Arr::tag_t::UINT8ARRAY + pbkdf2Spec.password.data = params.password.get_UINT8ARRAY_ref().data(); + pbkdf2Spec.password.len = params.password.get_UINT8ARRAY_ref().size(); + } + pbkdf2Spec.salt.data = params.salt.data(); + pbkdf2Spec.salt.len = params.salt.size(); + pbkdf2Spec.iterations = params.iterations; + int32_t keySize = params.keySize; + outBlob.data = static_cast(HcfMalloc(keySize, 0)); + outBlob.len = (outBlob.data == nullptr) ? 0 : keySize; + pbkdf2Spec.output = outBlob; +} + +void SetHkdfParamsSpecAttribute(const HKDFSpec ¶ms, HcfHkdfParamsSpec &hkdfSpec, HcfBlob &outBlob) +{ + hkdfSpec.base.algName = params.base.algName.c_str(); + if (params.key.get_tag() == OptStrUint8Arr::tag_t::STRING) { + hkdfSpec.key.data = reinterpret_cast(const_cast(params.key.get_STRING_ref().c_str())); + hkdfSpec.key.len = params.key.get_STRING_ref().size(); + } else { // OptStrUint8Arr::tag_t::UINT8ARRAY + hkdfSpec.key.data = params.key.get_UINT8ARRAY_ref().data(); + hkdfSpec.key.len = params.key.get_UINT8ARRAY_ref().size(); + } + hkdfSpec.salt.data = params.salt.data(); + hkdfSpec.salt.len = params.salt.size(); + hkdfSpec.info.data = params.info.data(); + hkdfSpec.info.len = params.info.size(); + int32_t keySize = params.keySize; + outBlob.data = static_cast(HcfMalloc(keySize, 0)); + outBlob.len = (outBlob.data == nullptr) ? 0 : keySize; + hkdfSpec.output = outBlob; +} + +void SetScryptParamsSpecAttribute(const ScryptSpec ¶ms, HcfScryptParamsSpec &scryptSpec, HcfBlob &outBlob) +{ + scryptSpec.base.algName = params.base.algName.c_str(); + if (params.passphrase.get_tag() == OptStrUint8Arr::tag_t::STRING) { + scryptSpec.passPhrase.data = reinterpret_cast + (const_cast(params.passphrase.get_STRING_ref().c_str())); + scryptSpec.passPhrase.len = params.passphrase.get_STRING_ref().size(); + } else { // OptStrUint8Arr::tag_t::UINT8ARRAY + scryptSpec.passPhrase.data = params.passphrase.get_UINT8ARRAY_ref().data(); + scryptSpec.passPhrase.len = params.passphrase.get_UINT8ARRAY_ref().size(); + } + scryptSpec.salt.data = params.salt.data(); + scryptSpec.salt.len = params.salt.size(); + scryptSpec.n = params.n; + scryptSpec.r = params.r; + scryptSpec.p = params.p; + scryptSpec.maxMem = params.maxMemory; + int32_t keySize = params.keySize; + outBlob.data = static_cast(HcfMalloc(keySize, 0)); + outBlob.len = (outBlob.data == nullptr) ? 0 : keySize; + scryptSpec.output = outBlob; +} +} // namespace + +namespace ANI::CryptoFramework { +KdfImpl::KdfImpl() {} + +KdfImpl::KdfImpl(HcfKdf *kdf) : kdf_(kdf) {} + +KdfImpl::~KdfImpl() +{ + HcfObjDestroy(this->kdf_); + this->kdf_ = nullptr; +} + +DataBlob KdfImpl::GenerateSecretSync(OptExtKdfSpec const& params) +{ + if (this->kdf_ == nullptr) { + ANI_LOGE_THROW(HCF_INVALID_PARAMS, "kdf obj is nullptr!"); + return { array(nullptr, 0) }; + } + HcfKdfParamsSpec *paramsSpec = nullptr; + HcfPBKDF2ParamsSpec pbkdf2Spec = {}; + HcfHkdfParamsSpec hkdfSpec = {}; + HcfScryptParamsSpec scryptSpec = {}; + HcfBlob outBlob = { .data = nullptr, .len = 0 }; + const std::string &algName = params.get_KDFSPEC_ref().algName.c_str(); + if (params.get_tag() == OptExtKdfSpec::tag_t::PBKDF2SPEC && algName == PBKDF2_ALG_NAME) { + SetPBKDF2ParamsSpecAttribute(params.get_PBKDF2SPEC_ref(), pbkdf2Spec, outBlob); + paramsSpec = reinterpret_cast(&pbkdf2Spec); + } else if (params.get_tag() == OptExtKdfSpec::tag_t::HKDFSPEC && algName == HKDF_ALG_NAME) { + SetHkdfParamsSpecAttribute(params.get_HKDFSPEC_ref(), hkdfSpec, outBlob); + paramsSpec = reinterpret_cast(&hkdfSpec); + } else if (params.get_tag() == OptExtKdfSpec::tag_t::SCRYPTSPEC && algName == SCRYPT_ALG_NAME) { + SetScryptParamsSpecAttribute(params.get_SCRYPTSPEC_ref(), scryptSpec, outBlob); + paramsSpec = reinterpret_cast(&scryptSpec); + } else { + ANI_LOGE_THROW(HCF_INVALID_PARAMS, "invalid kdf spec!"); + return { array(nullptr, 0) }; + } + HcfResult res = this->kdf_->generateSecret(this->kdf_, paramsSpec); + if (res != HCF_SUCCESS) { + ANI_LOGE_THROW(res, "kdf generateSecret failed!"); + return { array(nullptr, 0) }; + } + array data(move_data_t{}, outBlob.data, outBlob.len); + HcfBlobDataClearAndFree(&outBlob); + return { data }; +} + +string KdfImpl::GetAlgName() +{ + if (this->kdf_ == nullptr) { + ANI_LOGE_THROW(HCF_INVALID_PARAMS, "kdf obj is nullptr!"); + return ""; + } + const char *algName = this->kdf_->getAlgorithm(this->kdf_); + return (algName == nullptr) ? "" : string(algName); +} + +Kdf CreateKdf(string_view algName) +{ + HcfKdf *kdf = nullptr; + HcfResult res = HcfKdfCreate(algName.c_str(), &kdf); + if (res != HCF_SUCCESS) { + ANI_LOGE_THROW(res, "create C kdf obj failed."); + return make_holder(); + } + return make_holder(kdf); +} +} // namespace ANI::CryptoFramework + +TH_EXPORT_CPP_API_CreateKdf(CreateKdf); diff --git a/frameworks/js/ani/src/ani_key.cpp b/frameworks/js/ani/src/ani_key.cpp index d2979155632bb69d28bcfce4e274bf68b81018f2..cac240521667d4e439ee3a5e44c26eabf9ffb46d 100644 --- a/frameworks/js/ani/src/ani_key.cpp +++ b/frameworks/js/ani/src/ani_key.cpp @@ -22,20 +22,53 @@ using namespace ANI::CryptoFramework; namespace ANI::CryptoFramework { KeyImpl::KeyImpl() {} -KeyImpl::~KeyImpl() {} +KeyImpl::KeyImpl(HcfKey *key) : key_(key) {} + +KeyImpl::~KeyImpl() +{ + HcfObjDestroy(this->key_); + this->key_ = nullptr; +} + +int64_t KeyImpl::GetKeyObj() +{ + return reinterpret_cast(this->key_); +} DataBlob KeyImpl::GetEncoded() { - TH_THROW(std::runtime_error, "GetEncoded not implemented"); + if (this->key_ == nullptr) { + ANI_LOGE_THROW(HCF_INVALID_PARAMS, "key obj is nullptr!"); + return { array(nullptr, 0) }; + } + HcfBlob outBlob = { .data = nullptr, .len = 0 }; + HcfResult res = this->key_->getEncoded(this->key_, &outBlob); + if (res != HCF_SUCCESS) { + ANI_LOGE_THROW(res, "getEncoded failed."); + return { array(nullptr, 0) }; + } + array data(move_data_t{}, outBlob.data, outBlob.len); + HcfBlobDataClearAndFree(&outBlob); + return { data }; } string KeyImpl::GetFormat() { - TH_THROW(std::runtime_error, "GetFormat not implemented"); + if (this->key_ == nullptr) { + ANI_LOGE_THROW(HCF_INVALID_PARAMS, "key obj is nullptr!"); + return ""; + } + const char *format = this->key_->getFormat(this->key_); + return (format == nullptr) ? "" : string(format); } string KeyImpl::GetAlgName() { - TH_THROW(std::runtime_error, "GetAlgName not implemented"); + if (this->key_ == nullptr) { + ANI_LOGE_THROW(HCF_INVALID_PARAMS, "key obj is nullptr!"); + return ""; + } + const char *algName = this->key_->getAlgorithm(this->key_); + return (algName == nullptr) ? "" : string(algName); } } // namespace ANI::CryptoFramework diff --git a/frameworks/js/ani/src/ani_key_pair.cpp b/frameworks/js/ani/src/ani_key_pair.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8ecbde166af5c8261a2523769ef63a4cdfebb058 --- /dev/null +++ b/frameworks/js/ani/src/ani_key_pair.cpp @@ -0,0 +1,54 @@ +/* + * Copyright (c)2025-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "ani_key_pair.h" +#include "ani_pri_key.h" +#include "ani_pub_key.h" + +using namespace taihe; +using namespace ohos::security::cryptoFramework::cryptoFramework; +using namespace ANI::CryptoFramework; + +namespace ANI::CryptoFramework { +KeyPairImpl::KeyPairImpl() {} + +KeyPairImpl::KeyPairImpl(HcfKeyPair *keyPair) : keyPair_(keyPair) {} + +KeyPairImpl::~KeyPairImpl() +{ + HcfObjDestroy(this->keyPair_); + this->keyPair_ = nullptr; +} + +PriKey KeyPairImpl::GetPriKey() +{ + if (this->keyPair_ == nullptr) { + ANI_LOGE_THROW(HCF_INVALID_PARAMS, "keyPair obj is nullptr!"); + return make_holder(); + } + HcfPriKey *priKey = this->keyPair_->priKey; + return make_holder(priKey); +} + +PubKey KeyPairImpl::GetPubKey() +{ + if (this->keyPair_ == nullptr) { + ANI_LOGE_THROW(HCF_INVALID_PARAMS, "keyPair obj is nullptr!"); + return make_holder(); + } + HcfPubKey *pubKey = this->keyPair_->pubKey; + return make_holder(pubKey); +} +} // namespace ANI::CryptoFramework diff --git a/frameworks/js/ani/src/ani_mac.cpp b/frameworks/js/ani/src/ani_mac.cpp index 918562fd89b423527e0aa803f083282ee7e8b66c..bea7fcc01ec343aa82451528f56d2b0e925e48e0 100644 --- a/frameworks/js/ani/src/ani_mac.cpp +++ b/frameworks/js/ani/src/ani_mac.cpp @@ -21,23 +21,24 @@ using namespace ohos::security::cryptoFramework::cryptoFramework; using namespace ANI::CryptoFramework; namespace ANI::CryptoFramework { -MacImpl::MacImpl() : macObj(nullptr) {} +MacImpl::MacImpl() {} -MacImpl::MacImpl(HcfMac *obj) : macObj(obj) {} +MacImpl::MacImpl(HcfMac *mac) : mac_(mac) {} MacImpl::~MacImpl() { - HcfObjDestroy(macObj); + HcfObjDestroy(this->mac_); + this->mac_ = nullptr; } void MacImpl::InitSync(weak::SymKey key) { - if (macObj == nullptr) { + if (this->mac_ == nullptr) { ANI_LOGE_THROW(HCF_INVALID_PARAMS, "mac obj is nullptr!"); return; } - HcfSymKey *symKey = reinterpret_cast(key->GetSymKeyObj()); - HcfResult res = macObj->init(macObj, symKey); + HcfSymKey *obj = reinterpret_cast(key->GetSymKeyObj()); + HcfResult res = this->mac_->init(this->mac_, obj); if (res != HCF_SUCCESS) { ANI_LOGE_THROW(res, "mac init failed!"); return; @@ -46,12 +47,12 @@ void MacImpl::InitSync(weak::SymKey key) void MacImpl::UpdateSync(DataBlob const& input) { - if (macObj == nullptr) { + if (this->mac_ == nullptr) { ANI_LOGE_THROW(HCF_INVALID_PARAMS, "mac obj is nullptr!"); return; } HcfBlob inBlob = { .data = input.data.data(), .len = input.data.size() }; - HcfResult res = macObj->update(macObj, &inBlob); + HcfResult res = this->mac_->update(this->mac_, &inBlob); if (res != HCF_SUCCESS) { ANI_LOGE_THROW(res, "mac update failed!"); return; @@ -60,50 +61,51 @@ void MacImpl::UpdateSync(DataBlob const& input) DataBlob MacImpl::DoFinalSync() { - if (macObj == nullptr) { + if (this->mac_ == nullptr) { ANI_LOGE_THROW(HCF_INVALID_PARAMS, "mac obj is nullptr!"); - return { taihe::array(nullptr, 0) }; + return { array(nullptr, 0) }; } HcfBlob outBlob = { .data = nullptr, .len = 0 }; - HcfResult res = macObj->doFinal(macObj, &outBlob); + HcfResult res = this->mac_->doFinal(this->mac_, &outBlob); if (res != HCF_SUCCESS) { ANI_LOGE_THROW(res, "mac doFinal failed!"); - return { taihe::array(nullptr, 0) }; + return { array(nullptr, 0) }; } - taihe::array data(move_data_t{}, outBlob.data, outBlob.len); + array data(move_data_t{}, outBlob.data, outBlob.len); HcfBlobDataClearAndFree(&outBlob); return { data }; } int32_t MacImpl::GetMacLength() { - if (macObj == nullptr) { + if (this->mac_ == nullptr) { ANI_LOGE_THROW(HCF_INVALID_PARAMS, "mac obj is nullptr!"); return 0; } - uint32_t length = macObj->getMacLength(macObj); + uint32_t length = this->mac_->getMacLength(this->mac_); return static_cast(length); } string MacImpl::GetAlgName() { - if (macObj == nullptr) { + if (this->mac_ == nullptr) { + ANI_LOGE_THROW(HCF_INVALID_PARAMS, "mac obj is nullptr!"); return ""; } - const char *algName = macObj->getAlgoName(macObj); + const char *algName = this->mac_->getAlgoName(this->mac_); return (algName == nullptr) ? "" : string(algName); } Mac CreateMac(string_view algName) { - HcfMac *macObj = nullptr; + HcfMac *mac = nullptr; HcfHmacParamsSpec parmas = { { "HMAC" }, algName.c_str() }; - HcfResult res = HcfMacCreate(reinterpret_cast(&parmas), &macObj); + HcfResult res = HcfMacCreate(reinterpret_cast(&parmas), &mac); if (res != HCF_SUCCESS) { ANI_LOGE_THROW(res, "create C mac obj failed."); - return make_holder(nullptr); + return make_holder(); } - return make_holder(macObj); + return make_holder(mac); } } // namespace ANI::CryptoFramework diff --git a/frameworks/js/ani/src/ani_md.cpp b/frameworks/js/ani/src/ani_md.cpp index c264161e20b7fcffdd4fa72a56d20af4b4376515..9b431f18d1e23771f8dd8b101bd27be745231c49 100644 --- a/frameworks/js/ani/src/ani_md.cpp +++ b/frameworks/js/ani/src/ani_md.cpp @@ -20,20 +20,24 @@ using namespace ohos::security::cryptoFramework::cryptoFramework; using namespace ANI::CryptoFramework; namespace ANI::CryptoFramework { -MdImpl::MdImpl() : mdObj(nullptr) {} +MdImpl::MdImpl() {} -MdImpl::MdImpl(HcfMd *obj) : mdObj(obj) {} +MdImpl::MdImpl(HcfMd *md) : md_(md) {} -MdImpl::~MdImpl() {} +MdImpl::~MdImpl() +{ + HcfObjDestroy(this->md_); + this->md_ = nullptr; +} void MdImpl::UpdateSync(DataBlob const& input) { - if (mdObj == nullptr) { + if (this->md_ == nullptr) { ANI_LOGE_THROW(HCF_INVALID_PARAMS, "md obj is nullptr!"); return; } HcfBlob inBlob = { .data = input.data.data(), .len = input.data.size() }; - HcfResult res = mdObj->update(mdObj, &inBlob); + HcfResult res = this->md_->update(this->md_, &inBlob); if (res != HCF_SUCCESS) { ANI_LOGE_THROW(res, "md doFinal failed!"); return; @@ -42,49 +46,50 @@ void MdImpl::UpdateSync(DataBlob const& input) DataBlob MdImpl::DigestSync() { - if (mdObj == nullptr) { + if (this->md_ == nullptr) { ANI_LOGE_THROW(HCF_INVALID_PARAMS, "md obj is nullptr!"); - return { taihe::array(nullptr, 0) }; + return { array(nullptr, 0) }; } HcfBlob outBlob = { .data = nullptr, .len = 0 }; - HcfResult res = mdObj->doFinal(mdObj, &outBlob); + HcfResult res = this->md_->doFinal(this->md_, &outBlob); if (res != HCF_SUCCESS) { ANI_LOGE_THROW(res, "mac doFinal failed!"); - return { taihe::array(nullptr, 0) }; + return { array(nullptr, 0) }; } - taihe::array data(move_data_t{}, outBlob.data, outBlob.len); + array data(move_data_t{}, outBlob.data, outBlob.len); HcfBlobDataClearAndFree(&outBlob); return { data }; } int32_t MdImpl::GetMdLength() { - if (mdObj == nullptr) { + if (this->md_ == nullptr) { ANI_LOGE_THROW(HCF_INVALID_PARAMS, "md obj is nullptr!"); return 0; } - uint32_t length = mdObj->getMdLength(mdObj); + uint32_t length = this->md_->getMdLength(this->md_); return static_cast(length); } string MdImpl::GetAlgName() { - if (mdObj == nullptr) { + if (this->md_ == nullptr) { + ANI_LOGE_THROW(HCF_INVALID_PARAMS, "md obj is nullptr!"); return ""; } - const char *algName = mdObj->getAlgoName(mdObj); + const char *algName = this->md_->getAlgoName(this->md_); return (algName == nullptr) ? "" : string(algName); } Md CreateMd(string_view algName) { - HcfMd *mdObj = nullptr; - HcfResult res = HcfMdCreate(algName.c_str(), &mdObj); + HcfMd *md = nullptr; + HcfResult res = HcfMdCreate(algName.c_str(), &md); if (res != HCF_SUCCESS) { ANI_LOGE_THROW(res, "create C md obj failed."); - return make_holder(nullptr); + return make_holder(); } - return make_holder(mdObj); + return make_holder(md); } } // namespace ANI::CryptoFramework diff --git a/frameworks/js/ani/src/ani_pri_key.cpp b/frameworks/js/ani/src/ani_pri_key.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a39cd08335afff4f2bd12244a856adf26ddb115e --- /dev/null +++ b/frameworks/js/ani/src/ani_pri_key.cpp @@ -0,0 +1,84 @@ +/* + * Copyright (c)2025-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "ani_pri_key.h" + +using namespace taihe; +using namespace ohos::security::cryptoFramework::cryptoFramework; +using namespace ANI::CryptoFramework; + +namespace ANI::CryptoFramework { +PriKeyImpl::PriKeyImpl() {} + +PriKeyImpl::PriKeyImpl(HcfPriKey *priKey) : priKey_(priKey) {} + +PriKeyImpl::~PriKeyImpl() +{ + HcfObjDestroy(this->priKey_); + this->priKey_ = nullptr; +} + +void PriKeyImpl::ClearMem() +{ + TH_THROW(std::runtime_error, "ClearMem not implemented"); +} + +OptKeySpec PriKeyImpl::GetAsyKeySpec(AsyKeySpecEnum itemType) +{ + TH_THROW(std::runtime_error, "GetAsyKeySpec not implemented"); +} + +DataBlob PriKeyImpl::GetEncodedDer(string_view format) +{ + TH_THROW(std::runtime_error, "GetEncodedDer not implemented"); +} + +string PriKeyImpl::GetEncodedPem(string_view format, optional_view config) +{ + TH_THROW(std::runtime_error, "GetEncodedPem not implemented"); +} + +int64_t PriKeyImpl::GetKeyObj() +{ + TH_THROW(std::runtime_error, "GetKeyObj not implemented"); +} + +DataBlob PriKeyImpl::GetEncoded() +{ + if (this->priKey_ == nullptr) { + ANI_LOGE_THROW(HCF_INVALID_PARAMS, "priKey obj is nullptr!"); + return { array(nullptr, 0) }; + } + HcfBlob outBlob = { .data = nullptr, .len = 0 }; + HcfResult res = this->priKey_->base.getEncoded(&this->priKey_->base, &outBlob); + if (res != HCF_SUCCESS) { + ANI_LOGE_THROW(res, "getEncoded failed."); + return { array(nullptr, 0) }; + } + array data(move_data_t{}, outBlob.data, outBlob.len); + HcfBlobDataClearAndFree(&outBlob); + return { data }; +} + +string PriKeyImpl::GetFormat() +{ + TH_THROW(std::runtime_error, "GetFormat not implemented"); +} + +string PriKeyImpl::GetAlgName() +{ + TH_THROW(std::runtime_error, "GetAlgName not implemented"); +} +} // namespace ANI::CryptoFramework diff --git a/frameworks/js/ani/src/ani_pub_key.cpp b/frameworks/js/ani/src/ani_pub_key.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6bc75a9f947f99446da5c783d166ddd9ce751e9d --- /dev/null +++ b/frameworks/js/ani/src/ani_pub_key.cpp @@ -0,0 +1,79 @@ +/* + * Copyright (c)2025-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "ani_pub_key.h" + +using namespace taihe; +using namespace ohos::security::cryptoFramework::cryptoFramework; +using namespace ANI::CryptoFramework; + +namespace ANI::CryptoFramework { +PubKeyImpl::PubKeyImpl() {} + +PubKeyImpl::PubKeyImpl(HcfPubKey *pubKey) : pubKey_(pubKey) {} + +PubKeyImpl::~PubKeyImpl() +{ + HcfObjDestroy(this->pubKey_); + this->pubKey_ = nullptr; +} + +OptKeySpec PubKeyImpl::GetAsyKeySpec(AsyKeySpecEnum itemType) +{ + TH_THROW(std::runtime_error, "GetAsyKeySpec not implemented"); +} + +DataBlob PubKeyImpl::GetEncodedDer(string_view format) +{ + TH_THROW(std::runtime_error, "GetEncodedDer not implemented"); +} + +string PubKeyImpl::GetEncodedPem(string_view format) +{ + TH_THROW(std::runtime_error, "GetEncodedPem not implemented"); +} + +int64_t PubKeyImpl::GetKeyObj() +{ + TH_THROW(std::runtime_error, "GetKeyObj not implemented"); +} + +DataBlob PubKeyImpl::GetEncoded() +{ + if (this->pubKey_ == nullptr) { + ANI_LOGE_THROW(HCF_INVALID_PARAMS, "pubKey obj is nullptr!"); + return { array(nullptr, 0) }; + } + HcfBlob outBlob = { .data = nullptr, .len = 0 }; + HcfResult res = this->pubKey_->base.getEncoded(&this->pubKey_->base, &outBlob); + if (res != HCF_SUCCESS) { + ANI_LOGE_THROW(res, "getEncoded failed."); + return { array(nullptr, 0) }; + } + array data(move_data_t{}, outBlob.data, outBlob.len); + HcfBlobDataClearAndFree(&outBlob); + return { data }; +} + +string PubKeyImpl::GetFormat() +{ + TH_THROW(std::runtime_error, "GetFormat not implemented"); +} + +string PubKeyImpl::GetAlgName() +{ + TH_THROW(std::runtime_error, "GetAlgName not implemented"); +} +} // namespace ANI::CryptoFramework diff --git a/frameworks/js/ani/src/ani_rand.cpp b/frameworks/js/ani/src/ani_rand.cpp index 00220173a4fae3c11f6bfa80d1f6b23a27989d4d..a9ca8d31c426238ce9af80faeede0a8b0fea3ea1 100644 --- a/frameworks/js/ani/src/ani_rand.cpp +++ b/frameworks/js/ani/src/ani_rand.cpp @@ -20,40 +20,41 @@ using namespace ohos::security::cryptoFramework::cryptoFramework; using namespace ANI::CryptoFramework; namespace ANI::CryptoFramework { -RandomImpl::RandomImpl() : randObj(nullptr) {} +RandomImpl::RandomImpl() {} -RandomImpl::RandomImpl(HcfRand *obj) : randObj(obj) {} +RandomImpl::RandomImpl(HcfRand *rand) : rand_(rand) {} RandomImpl::~RandomImpl() { - HcfObjDestroy(randObj); + HcfObjDestroy(this->rand_); + this->rand_ = nullptr; } DataBlob RandomImpl::GenerateRandomSync(int32_t len) { - if (randObj == nullptr) { + if (this->rand_ == nullptr) { ANI_LOGE_THROW(HCF_INVALID_PARAMS, "rand obj is nullptr!"); - return { taihe::array(nullptr, 0) }; + return { array(nullptr, 0) }; } HcfBlob outBlob = { .data = nullptr, .len = 0 }; - HcfResult res = randObj->generateRandom(randObj, len, &outBlob); + HcfResult res = this->rand_->generateRandom(this->rand_, len, &outBlob); if (res != HCF_SUCCESS) { ANI_LOGE_THROW(res, "generateRandom failed!"); - return { taihe::array(nullptr, 0) }; + return { array(nullptr, 0) }; } - taihe::array data(move_data_t{}, outBlob.data, outBlob.len); + array data(move_data_t{}, outBlob.data, outBlob.len); HcfBlobDataClearAndFree(&outBlob); return { data }; } void RandomImpl::SetSeed(DataBlob const& seed) { - if (randObj == nullptr) { + if (this->rand_ == nullptr) { ANI_LOGE_THROW(HCF_INVALID_PARAMS, "rand obj is nullptr!"); return; } HcfBlob seedBlob = { .data = seed.data.data(), .len = seed.data.size() }; - HcfResult res = randObj->setSeed(randObj, &seedBlob); + HcfResult res = this->rand_->setSeed(this->rand_, &seedBlob); if (res != HCF_SUCCESS) { ANI_LOGE_THROW(res, "set seed failed."); return; @@ -62,22 +63,23 @@ void RandomImpl::SetSeed(DataBlob const& seed) string RandomImpl::GetAlgName() { - if (randObj == nullptr) { + if (this->rand_ == nullptr) { + ANI_LOGE_THROW(HCF_INVALID_PARAMS, "rand obj is nullptr!"); return ""; } - const char *algName = randObj->getAlgoName(randObj); + const char *algName = this->rand_->getAlgoName(this->rand_); return (algName == nullptr) ? "" : string(algName); } Random CreateRandom() { - HcfRand *randObj = nullptr; - HcfResult res = HcfRandCreate(&randObj); + HcfRand *rand = nullptr; + HcfResult res = HcfRandCreate(&rand); if (res != HCF_SUCCESS) { ANI_LOGE_THROW(res, "create C rand obj failed."); - return make_holder(nullptr); + return make_holder(); } - return make_holder(randObj); + return make_holder(rand); } } // namespace ANI::CryptoFramework diff --git a/frameworks/js/ani/src/ani_sym_key.cpp b/frameworks/js/ani/src/ani_sym_key.cpp index cb089457c4224d0c32d91485e44195af2e52b491..9c4f50eca6b2137ad3f46ae6c1d8f2751d12cc6a 100644 --- a/frameworks/js/ani/src/ani_sym_key.cpp +++ b/frameworks/js/ani/src/ani_sym_key.cpp @@ -20,28 +20,46 @@ using namespace ohos::security::cryptoFramework::cryptoFramework; using namespace ANI::CryptoFramework; namespace ANI::CryptoFramework { -SymKeyImpl::SymKeyImpl() : symKey(nullptr) {} +SymKeyImpl::SymKeyImpl() : symKey_(nullptr) {} -SymKeyImpl::SymKeyImpl(HcfSymKey *obj) : symKey(obj) {} +SymKeyImpl::SymKeyImpl(HcfSymKey *symKey) : symKey_(symKey) {} SymKeyImpl::~SymKeyImpl() { - HcfObjDestroy(symKey); + HcfObjDestroy(this->symKey_); + this->symKey_ = nullptr; } -void SymKeyImpl::ClearMem() +int64_t SymKeyImpl::GetKeyObj() { - TH_THROW(std::runtime_error, "ClearMem not implemented"); + return reinterpret_cast(&this->symKey_->key); } int64_t SymKeyImpl::GetSymKeyObj() { - return reinterpret_cast(symKey); + return reinterpret_cast(this->symKey_); +} + +void SymKeyImpl::ClearMem() +{ + TH_THROW(std::runtime_error, "ClearMem not implemented"); } DataBlob SymKeyImpl::GetEncoded() { - TH_THROW(std::runtime_error, "GetEncoded not implemented"); + if (this->symKey_ == nullptr) { + ANI_LOGE_THROW(HCF_INVALID_PARAMS, "symKey obj is nullptr!"); + return { array(nullptr, 0) }; + } + HcfBlob outBlob = { .data = nullptr, .len = 0 }; + HcfResult res = this->symKey_->key.getEncoded(&this->symKey_->key, &outBlob); + if (res != HCF_SUCCESS) { + ANI_LOGE_THROW(res, "getEncoded failed."); + return { array(nullptr, 0) }; + } + array data(move_data_t{}, outBlob.data, outBlob.len); + HcfBlobDataClearAndFree(&outBlob); + return { data }; } string SymKeyImpl::GetFormat() diff --git a/frameworks/js/ani/src/ani_sym_key_generator.cpp b/frameworks/js/ani/src/ani_sym_key_generator.cpp index 5b45115910404dbf18688b0a577225cf29ead7bf..3e4ce23842527c410fc11588ffb7c0de50eb349e 100644 --- a/frameworks/js/ani/src/ani_sym_key_generator.cpp +++ b/frameworks/js/ani/src/ani_sym_key_generator.cpp @@ -21,42 +21,54 @@ using namespace ohos::security::cryptoFramework::cryptoFramework; using namespace ANI::CryptoFramework; namespace ANI::CryptoFramework { -SymKeyGeneratorImpl::SymKeyGeneratorImpl() : generator(nullptr) {} +SymKeyGeneratorImpl::SymKeyGeneratorImpl() {} -SymKeyGeneratorImpl::SymKeyGeneratorImpl(HcfSymKeyGenerator *obj) : generator(obj) {} +SymKeyGeneratorImpl::SymKeyGeneratorImpl(HcfSymKeyGenerator *generator) : generator_(generator) {} SymKeyGeneratorImpl::~SymKeyGeneratorImpl() { - HcfObjDestroy(generator); + HcfObjDestroy(this->generator_); + this->generator_ = nullptr; } SymKey SymKeyGeneratorImpl::GenerateSymKeySync() { - return make_holder(nullptr); + if (this->generator_ == nullptr) { + ANI_LOGE_THROW(HCF_INVALID_PARAMS, "generator obj is nullptr!"); + return make_holder(); + } + HcfSymKey *symKey = nullptr; + HcfResult res = this->generator_->generateSymKey(this->generator_, &symKey); + if (res != HCF_SUCCESS) { + ANI_LOGE_THROW(res, "generate sym key failed."); + return make_holder(); + } + return make_holder(symKey); } SymKey SymKeyGeneratorImpl::ConvertKeySync(DataBlob const& key) { - if (generator == nullptr) { + if (this->generator_ == nullptr) { ANI_LOGE_THROW(HCF_INVALID_PARAMS, "generator obj is nullptr!"); - return make_holder(nullptr); + return make_holder(); } HcfSymKey *symKey = nullptr; HcfBlob keyData = { .data = key.data.data(), .len = key.data.size() }; - HcfResult res = generator->convertSymKey(generator, &keyData, &symKey); + HcfResult res = this->generator_->convertSymKey(this->generator_, &keyData, &symKey); if (res != HCF_SUCCESS) { ANI_LOGE_THROW(res, "convertSymKey key failed!"); - return make_holder(nullptr); + return make_holder(); } return make_holder(symKey); } string SymKeyGeneratorImpl::GetAlgName() { - if (generator == nullptr) { + if (this->generator_ == nullptr) { + ANI_LOGE_THROW(HCF_INVALID_PARAMS, "generator obj is nullptr!"); return ""; } - const char *algName = generator->getAlgoName(generator); + const char *algName = this->generator_->getAlgoName(this->generator_); return (algName == nullptr) ? "" : string(algName); } @@ -66,7 +78,7 @@ SymKeyGenerator CreateSymKeyGenerator(string_view algName) HcfResult res = HcfSymKeyGeneratorCreate(algName.c_str(), &generator); if (res != HCF_SUCCESS) { ANI_LOGE_THROW(res, "create C generator obj fail."); - return make_holder(nullptr); + return make_holder(); } return make_holder(generator); } diff --git a/frameworks/js/ani/src/impl/ohos.security.cryptoFramework.cryptoFramework.impl.cpp b/frameworks/js/ani/src/impl/ohos.security.cryptoFramework.cryptoFramework.impl.cpp index 5327a103aa53a212fafe9c25c4d4caf117d5372f..f182912e20cfeb533a6bdc10d9fa97b1cf348eaa 100644 --- a/frameworks/js/ani/src/impl/ohos.security.cryptoFramework.cryptoFramework.impl.cpp +++ b/frameworks/js/ani/src/impl/ohos.security.cryptoFramework.cryptoFramework.impl.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025-2025 Huawei Device Co., Ltd. + * Copyright (c)2025-2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -99,6 +99,10 @@ public: // Don't forget to implement the constructor. } + int64_t GetKeyObj() { + TH_THROW(std::runtime_error, "GetKeyObj not implemented"); + } + DataBlob GetEncoded() { TH_THROW(std::runtime_error, "GetEncoded not implemented"); } @@ -112,9 +116,9 @@ public: } }; -class SymKeyImpl { +class PriKeyImpl { public: - SymKeyImpl() { + PriKeyImpl() { // Don't forget to implement the constructor. } @@ -122,10 +126,107 @@ public: TH_THROW(std::runtime_error, "ClearMem not implemented"); } + OptKeySpec GetAsyKeySpec(AsyKeySpecEnum itemType) { + TH_THROW(std::runtime_error, "GetAsyKeySpec not implemented"); + } + + DataBlob GetEncodedDer(string_view format) { + TH_THROW(std::runtime_error, "GetEncodedDer not implemented"); + } + + string GetEncodedPem(string_view format, optional_view config) { + TH_THROW(std::runtime_error, "GetEncodedPem not implemented"); + } + + int64_t GetKeyObj() { + TH_THROW(std::runtime_error, "GetKeyObj not implemented"); + } + + DataBlob GetEncoded() { + TH_THROW(std::runtime_error, "GetEncoded not implemented"); + } + + string GetFormat() { + TH_THROW(std::runtime_error, "GetFormat not implemented"); + } + + string GetAlgName() { + TH_THROW(std::runtime_error, "GetAlgName not implemented"); + } +}; + +class PubKeyImpl { +public: + PubKeyImpl() { + // Don't forget to implement the constructor. + } + + OptKeySpec GetAsyKeySpec(AsyKeySpecEnum itemType) { + TH_THROW(std::runtime_error, "GetAsyKeySpec not implemented"); + } + + DataBlob GetEncodedDer(string_view format) { + TH_THROW(std::runtime_error, "GetEncodedDer not implemented"); + } + + string GetEncodedPem(string_view format) { + TH_THROW(std::runtime_error, "GetEncodedPem not implemented"); + } + + int64_t GetKeyObj() { + TH_THROW(std::runtime_error, "GetKeyObj not implemented"); + } + + DataBlob GetEncoded() { + TH_THROW(std::runtime_error, "GetEncoded not implemented"); + } + + string GetFormat() { + TH_THROW(std::runtime_error, "GetFormat not implemented"); + } + + string GetAlgName() { + TH_THROW(std::runtime_error, "GetAlgName not implemented"); + } +}; + +class KeyPairImpl { +public: + KeyPairImpl() { + // Don't forget to implement the constructor. + } + + PriKey GetPriKey() { + // The parameters in the make_holder function should be of the same type + // as the parameters in the constructor of the actual implementation class. + return make_holder(); + } + + PubKey GetPubKey() { + // The parameters in the make_holder function should be of the same type + // as the parameters in the constructor of the actual implementation class. + return make_holder(); + } +}; + +class SymKeyImpl { +public: + SymKeyImpl() { + // Don't forget to implement the constructor. + } + int64_t GetSymKeyObj() { TH_THROW(std::runtime_error, "GetSymKeyObj not implemented"); } + void ClearMem() { + TH_THROW(std::runtime_error, "ClearMem not implemented"); + } + + int64_t GetKeyObj() { + TH_THROW(std::runtime_error, "GetKeyObj not implemented"); + } + DataBlob GetEncoded() { TH_THROW(std::runtime_error, "GetEncoded not implemented"); } @@ -162,6 +263,73 @@ public: } }; +class AsyKeyGeneratorImpl { +public: + AsyKeyGeneratorImpl() { + // Don't forget to implement the constructor. + } + + KeyPair GenerateKeyPairSync() { + // The parameters in the make_holder function should be of the same type + // as the parameters in the constructor of the actual implementation class. + return make_holder(); + } + + KeyPair ConvertKeySync(OptDataBlob const& pubKey, OptDataBlob const& priKey) { + // The parameters in the make_holder function should be of the same type + // as the parameters in the constructor of the actual implementation class. + return make_holder(); + } + + KeyPair ConvertPemKeySync(OptString const& pubKey, OptString const& priKey, optional_view password) { + // The parameters in the make_holder function should be of the same type + // as the parameters in the constructor of the actual implementation class. + return make_holder(); + } + + string GetAlgName() { + TH_THROW(std::runtime_error, "GetAlgName not implemented"); + } +}; + +class KdfImpl { +public: + KdfImpl() { + // Don't forget to implement the constructor. + } + + DataBlob GenerateSecretSync(OptExtKdfSpec const& params) { + TH_THROW(std::runtime_error, "GenerateSecretSync not implemented"); + } + + string GetAlgName() { + TH_THROW(std::runtime_error, "GetAlgName not implemented"); + } +}; + +class CipherImpl { +public: + CipherImpl() { + // Don't forget to implement the constructor. + } + + void InitSync(CryptoMode opMode, weak::Key key, OptParamsSpec const& params) { + TH_THROW(std::runtime_error, "InitSync not implemented"); + } + + DataBlob UpdateSync(DataBlob const& input) { + TH_THROW(std::runtime_error, "UpdateSync not implemented"); + } + + DataBlob DoFinalSync(OptDataBlob const& input) { + TH_THROW(std::runtime_error, "DoFinalSync not implemented"); + } + + string GetAlgName() { + TH_THROW(std::runtime_error, "GetAlgName not implemented"); + } +}; + Md CreateMd(string_view algName) { // The parameters in the make_holder function should be of the same type // as the parameters in the constructor of the actual implementation class. @@ -185,9 +353,33 @@ SymKeyGenerator CreateSymKeyGenerator(string_view algName) { // as the parameters in the constructor of the actual implementation class. return make_holder(); } + +AsyKeyGenerator CreateAsyKeyGenerator(string_view algName) { + // The parameters in the make_holder function should be of the same type + // as the parameters in the constructor of the actual implementation class. + return make_holder(); +} + +Kdf CreateKdf(string_view algName) { + // The parameters in the make_holder function should be of the same type + // as the parameters in the constructor of the actual implementation class. + return make_holder(); +} + +Cipher CreateCipher(string_view transformation) { + // The parameters in the make_holder function should be of the same type + // as the parameters in the constructor of the actual implementation class. + return make_holder(); +} } // namespace +// Since these macros are auto-generate, lint will cause false positive. +// NOLINTBEGIN TH_EXPORT_CPP_API_CreateMd(CreateMd); TH_EXPORT_CPP_API_CreateRandom(CreateRandom); TH_EXPORT_CPP_API_CreateMac(CreateMac); TH_EXPORT_CPP_API_CreateSymKeyGenerator(CreateSymKeyGenerator); +TH_EXPORT_CPP_API_CreateAsyKeyGenerator(CreateAsyKeyGenerator); +TH_EXPORT_CPP_API_CreateKdf(CreateKdf); +TH_EXPORT_CPP_API_CreateCipher(CreateCipher); +// NOLINTEND diff --git a/frameworks/js/ani/test/test_asy_key_generator.ets b/frameworks/js/ani/test/test_asy_key_generator.ets new file mode 100644 index 0000000000000000000000000000000000000000..e6ff25ae43eaefd952aecb034426753c27314697 --- /dev/null +++ b/frameworks/js/ani/test/test_asy_key_generator.ets @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2025-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import cryptoFramework from "@ohos.security.cryptoFramework"; +import utils from "./test_utils"; + +function testAsyKeyGeneratorSync() { + try { + let generator = cryptoFramework.createAsyKeyGenerator('RSA1024|PRIMES_2'); + let keyPair = generator.generateKeyPairSync(); + let pkBlob = keyPair.pubKey.getEncoded(); + let skBlob = keyPair.priKey.getEncoded(); + let pkStr = utils.uint8ArrayToHexStr(pkBlob.data); + let skStr = utils.uint8ArrayToHexStr(skBlob.data); + console.info('generateKeyPair pubKey: ' + pkStr); + console.info('generateKeyPair priKey: ' + skStr); + } catch (err) { + console.error("[error] generateKeyPair: " + err); + } +} + + function testAsyKeyConvertKeySync() { + try { + let pubKeyArray = new Uint8Array([48, 89, 48, 19, 6, 7, 42, 134, 72, 206, 61, 2, 1, 6, 8, 42, 129, 28, 207, 85, 1, 130, 45, 3, 66, 0, 4, 90, 3, 58, 157, 190, 248, 76, 7, 132, 200, 151, 208, 112, 230, 96, 140, 90, 238, 211, 155, 128, 109, 248, 40, 83, 214, 78, 42, 104, 106, 55, 148, 249, 35, 61, 32, 221, 135, 143, 100, 45, 97, 194, 176, 52, 73, 136, 174, 40, 70, 70, 34, 103, 103, 161, 99, 27, 187, 13, 187, 109, 244, 13, 7]); + let priKeyArray = new Uint8Array([48, 49, 2, 1, 1, 4, 32, 54, 41, 239, 240, 63, 188, 134, 113, 31, 102, 149, 203, 245, 89, 15, 15, 47, 202, 170, 60, 38, 154, 28, 169, 189, 100, 251, 76, 112, 223, 156, 159, 160, 10, 6, 8, 42, 129, 28, 207, 85, 1, 130, 45]); + let pubKeyBlob: cryptoFramework.DataBlob = { + data: pubKeyArray + }; + let priKeyBlob: cryptoFramework.DataBlob = { + data: priKeyArray + }; + let generator = cryptoFramework.createAsyKeyGenerator('SM2_256'); + let keyPair = generator.convertKeySync(pubKeyBlob, priKeyBlob); + let pkBlob = keyPair.pubKey.getEncoded(); + let skBlob = keyPair.priKey.getEncoded(); + let pkStr = utils.uint8ArrayToHexStr(pkBlob.data); + let skStr = utils.uint8ArrayToHexStr(skBlob.data); + console.info('convertPemKey pubKey: ' + pkStr); + console.info('convertPemKey priKey: ' + skStr); + } catch (err) { + console.error("[error] convertPemKey: " + err); + } +} + +export function testAsyKeyGenerator() { + console.log(">>>>>>>>>>>>>>>>>>>> AsyKeyGeneratorSync"); + testAsyKeyGeneratorSync(); + console.log(">>>>>>>>>>>>>>>>>>>> AsyKeyConvertKeySync"); + testAsyKeyConvertKeySync(); +} diff --git a/frameworks/js/ani/test/test_cipher.ets b/frameworks/js/ani/test/test_cipher.ets new file mode 100644 index 0000000000000000000000000000000000000000..e8c53402f18928dfd03a4c4062b30885001ed2f4 --- /dev/null +++ b/frameworks/js/ani/test/test_cipher.ets @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2025-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import cryptoFramework from "@ohos.security.cryptoFramework"; +import utils from "./test_utils"; + +function generateRandom(len: int) { + let rand = cryptoFramework.createRandom(); + let generater = rand.generateRandomSync(len); + return generater; +} + +function genSymKeyByData(symKeyData: Uint8Array) { + let symKeyBlob: cryptoFramework.DataBlob = { + data: symKeyData + }; + let generator = cryptoFramework.createSymKeyGenerator('AES128'); + let symKey = generator.convertKeySync(symKeyBlob); + return symKey; +} + +function encrypt(algorithm: string, symKey: cryptoFramework.SymKey, data: cryptoFramework.DataBlob, + params: cryptoFramework.GcmParamsSpec | cryptoFramework.CcmParamsSpec | cryptoFramework.IvParamsSpec | null +): cryptoFramework.DataBlob { + let cipher = cryptoFramework.createCipher(algorithm); + cipher.initSync(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, params); + if (algorithm.includes('GCM') || algorithm.includes('CCM')) { + let encryptData = cipher.updateSync(data); + if (algorithm.includes('GCM')) { + (params as cryptoFramework.GcmParamsSpec).authTag = cipher.doFinalSync(null); + } else if (algorithm.includes('CCM')) { + (params as cryptoFramework.CcmParamsSpec).authTag = cipher.doFinalSync(null); + } + return encryptData; + } else { // CBC/ECB + return cipher.doFinalSync(data); + } +} + +function decrypt(algorithm: string, symKey: cryptoFramework.SymKey, data: cryptoFramework.DataBlob, + params: cryptoFramework.GcmParamsSpec | cryptoFramework.CcmParamsSpec | cryptoFramework.IvParamsSpec | null +): cryptoFramework.DataBlob { + let decoder = cryptoFramework.createCipher(algorithm); + decoder.initSync(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, params); + if (algorithm.includes('GCM')) { + let decryptData = decoder.updateSync(data); + decoder.doFinalSync(null); + return decryptData; + } else if (algorithm.includes('CCM')) { + return decoder.doFinalSync(data); + } else { // CBC/ECB + return decoder.doFinalSync(data); + } +} + +function aesCipher(algorithm: string, + params: cryptoFramework.GcmParamsSpec | cryptoFramework.CcmParamsSpec | cryptoFramework.IvParamsSpec | null) { + try { + let keyData = new Uint8Array([83, 217, 231, 76, 28, 113, 23, 219, 250, 71, 209, 210, 205, 97, 32, 159]); + let symKey = genSymKeyByData(keyData); + let message = "This is a test"; + let plainText: cryptoFramework.DataBlob = { + data: utils.stringToUint8Array(message) + }; + let encryptText = encrypt(algorithm, symKey, plainText, params); + let decryptText = decrypt(algorithm, symKey, encryptText, params); + if (plainText.data.toString() === decryptText.data.toString()) { + console.info(`${algorithm} success`); + } else { + console.error(`${algorithm} failed`); + } + } catch (err) { + console.error(`[error] ${algorithm}: ${err}`); + } +} + +function testAesGcmSync() { + let params: cryptoFramework.GcmParamsSpec = { + algName: "GcmParamsSpec", + iv: generateRandom(12), + aad: generateRandom(8), + authTag: generateRandom(16), + }; + aesCipher('AES128|GCM|PKCS7', params); +} + +function testAesCcmSync() { + let params: cryptoFramework.CcmParamsSpec = { + algName: "CcmParamsSpec", + iv: generateRandom(7), + aad: generateRandom(8), + authTag: generateRandom(12), + }; + aesCipher('AES128|CCM', params); +} + +function testAesCbcSync() { + let params: cryptoFramework.IvParamsSpec = { + algName: "IvParamsSpec", + iv: generateRandom(16), + }; + aesCipher('AES128|CBC|PKCS7', params); +} + +function testAesEcbSync() { + aesCipher('AES128|ECB|PKCS7', null); +} + +export function testCipher() { + console.log(">>>>>>>>>>>>>>>>>>>> AesGcmSync"); + testAesGcmSync(); + console.log(">>>>>>>>>>>>>>>>>>>> AesCcmSync"); + testAesCcmSync(); + console.log(">>>>>>>>>>>>>>>>>>>> AesCbcSync"); + testAesCbcSync(); + console.log(">>>>>>>>>>>>>>>>>>>> AesEcbSync"); + testAesEcbSync(); +} diff --git a/frameworks/js/ani/test/test_kdf.ets b/frameworks/js/ani/test/test_kdf.ets new file mode 100644 index 0000000000000000000000000000000000000000..7a707876e507a5859df68165b5d9192e1582f2dc --- /dev/null +++ b/frameworks/js/ani/test/test_kdf.ets @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2025-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import cryptoFramework from "@ohos.security.cryptoFramework"; +import utils from "./test_utils"; + +function testPBKDF2Sync() { + try { + let spec: cryptoFramework.PBKDF2Spec = { + algName: 'PBKDF2', + password: utils.stringToUint8Array("123456"), + salt: utils.stringToUint8Array("0123456789"), + iterations: 10000, + keySize: 32, + }; + let kdf = cryptoFramework.createKdf('PBKDF2|SHA256'); + let secret = kdf.generateSecretSync(spec); + let str = utils.uint8ArrayToHexStr(secret.data); + console.log("PBKDF2 algName: " + kdf.algName); + console.info("PBKDF2: " + str); + } + catch (err) { + console.error("[error] PBKDF2: " + err); + } +} + +function testHKDFSync() { + try { + let spec: cryptoFramework.HKDFSpec = { + algName: 'HKDF', + key: utils.stringToUint8Array("012345678901234567890123456789"), + salt: utils.stringToUint8Array("0123456789"), + info: utils.stringToUint8Array("infostring"), + keySize: 32, + }; + let kdf = cryptoFramework.createKdf('HKDF|SHA256|EXTRACT_AND_EXPAND'); + let secret = kdf.generateSecretSync(spec); + let str = utils.uint8ArrayToHexStr(secret.data); + console.log("HKDF algName: " + kdf.algName); + console.info("HKDF: " + str); + } catch (err) { + console.error("[error] HKDF: " + err); + } +} + +function testScryptSync() { + try { + let spec: cryptoFramework.ScryptSpec = { + algName: 'SCRYPT', + passphrase: "123456", + salt: utils.stringToUint8Array("0123456789"), + n: 1024, + p: 16, + r: 8, + maxMemory: 1024 * 16 * 8 * 10, // n * p * r * 10 + keySize: 64, + }; + let kdf = cryptoFramework.createKdf('SCRYPT'); + let secret = kdf.generateSecretSync(spec); + let str = utils.uint8ArrayToHexStr(secret.data); + console.log("Scrypt algName: " + kdf.algName); + console.info("Scrypt: " + str); + } catch (err) { + console.error("[error] Scrypt: " + err); + } +} + +export function testKdf() { + console.log(">>>>>>>>>>>>>>>>>>>> PBKDF2Sync"); + testPBKDF2Sync(); + console.log(">>>>>>>>>>>>>>>>>>>> HKDFSync"); + testHKDFSync(); + console.log(">>>>>>>>>>>>>>>>>>>> ScryptSync"); + testScryptSync(); +} diff --git a/frameworks/js/ani/test/test_mac.ets b/frameworks/js/ani/test/test_mac.ets index 69f74d5243426eb6e3008160188079df9df52318..7aebb47ff6cbbe31552dfbbc1fe862867c85a80f 100644 --- a/frameworks/js/ani/test/test_mac.ets +++ b/frameworks/js/ani/test/test_mac.ets @@ -16,13 +16,14 @@ import cryptoFramework from "@ohos.security.cryptoFramework"; import utils from "./test_utils"; -export function testMac() { +function testMacSync() { try { let key = "1234567890"; - let keyBytes = utils.hexStrToUint8Array(key); let data = "Hello World"; + let keyBytes = utils.hexStrToUint8Array(key); let dataBytes = utils.stringToUint8Array(data); - let symKey = cryptoFramework.createSymKeyGenerator("HMAC").convertKeySync({ + let generator = cryptoFramework.createSymKeyGenerator("HMAC"); + let symKey = generator.convertKeySync({ data: keyBytes }); let mac = cryptoFramework.createMac("SHA256"); @@ -36,6 +37,38 @@ export function testMac() { console.log("HMAC-SHA256: " + str); } catch (err) { - console.error("HMAC-SHA256: " + err) + console.error("[error] HMAC-SHA256: " + err); } } + +function testMacAsync() { + try { + let key = "1234567890"; + let data = "Hello World"; + let keyBytes = utils.hexStrToUint8Array(key); + let dataBytes = utils.stringToUint8Array(data);; + let generator = cryptoFramework.createSymKeyGenerator("HMAC"); + let symKey = await generator.convertKey({ + data: keyBytes + }); + let mac = cryptoFramework.createMac("SHA256"); + await mac.init(symKey); + await mac.update({ + data: dataBytes + }); + let output = await mac.doFinal(); + let str = utils.uint8ArrayToHexStr(output.data); + console.log("HMAC algName: " + mac.algName); + console.log("HMAC-SHA256: " + str); + } + catch (err) { + console.error("[error] HMAC-SHA256: " + err); + } +} + +export function testMac() { + console.log(">>>>>>>>>>>>>>>>>>>> MacSync"); + testMacSync(); + console.log(">>>>>>>>>>>>>>>>>>>> MacAsync"); + testMacAsync(); +} diff --git a/frameworks/js/ani/test/test_main.ets b/frameworks/js/ani/test/test_main.ets index 616b5c3cad3eca2fe041be07f294068b803fbd55..334b461cf3ff287f10e95bd5a49a03c2133cbf37 100644 --- a/frameworks/js/ani/test/test_main.ets +++ b/frameworks/js/ani/test/test_main.ets @@ -13,12 +13,20 @@ * limitations under the License. */ -import { testMd } from "./test_md"; import { testRandom } from "./test_rand"; +import { testMd } from "./test_md"; import { testMac } from "./test_mac"; +import { testKdf } from "./test_kdf"; +import { testAsyKeyGenerator } from "./test_asy_key_generator"; +import { testSymKeyGenerator } from "./test_sym_key_generator"; +import { testCipher } from "./test_cipher"; function main() { - testMac(); - testMd(); testRandom(); + testMd(); + testMac(); + testKdf(); + testAsyKeyGenerator(); + testSymKeyGenerator(); + testCipher(); } diff --git a/frameworks/js/ani/test/test_md.ets b/frameworks/js/ani/test/test_md.ets index e2f7949787459a31839bdc5a52306af40214ffb0..3263177e77834d36268022b7d64f685780a309a7 100644 --- a/frameworks/js/ani/test/test_md.ets +++ b/frameworks/js/ani/test/test_md.ets @@ -16,11 +16,11 @@ import cryptoFramework from "@ohos.security.cryptoFramework"; import utils from "./test_utils"; -export function testMd() { +function testMdSync() { try { - let md = cryptoFramework.createMd("MD5"); let data = "Hello World"; let dataBytes = utils.stringToUint8Array(data); + let md = cryptoFramework.createMd("MD5"); md.updateSync({ data: dataBytes }); @@ -30,6 +30,31 @@ export function testMd() { let length = md.getMdLength(); console.log("MD5 length: " + length); } catch (err) { - console.log("MD5: " + err); + console.log("[error] MD5: " + err); + } +} + +function testMdAsync() { + try { + let data = "Hello World"; + let dataBytes = utils.stringToUint8Array(data); + let md = cryptoFramework.createMd("MD5"); + await md.update({ + data: dataBytes + }); + let output = await md.digest(); + let str = utils.uint8ArrayToHexStr(output.data); + console.log("MD5: " + str); + let length = md.getMdLength(); + console.log("MD5 length: " + length); + } catch (err) { + console.log("[error] MD5: " + err); } } + +export function testMd() { + console.log(">>>>>>>>>>>>>>>>>>>> MdSync"); + testMdSync(); + console.log(">>>>>>>>>>>>>>>>>>>> MdAsync"); + testMdAsync(); +} diff --git a/frameworks/js/ani/test/test_rand.ets b/frameworks/js/ani/test/test_rand.ets index 5dcf01e6e8b00470c774916998e80cd03523f1ad..c61047917a685bd772e55ae7ea4717ae385d658a 100644 --- a/frameworks/js/ani/test/test_rand.ets +++ b/frameworks/js/ani/test/test_rand.ets @@ -17,11 +17,11 @@ import cryptoFramework from "@ohos.security.cryptoFramework"; import utils from "./test_utils"; -export function testRandom() { +function testRandomSync() { try { - let random = cryptoFramework.createRandom(); let data = "Hello World"; let dataBytes = utils.stringToUint8Array(data); + let random = cryptoFramework.createRandom(); random.setSeed({ data: dataBytes }); @@ -29,6 +29,11 @@ export function testRandom() { let str = utils.uint8ArrayToHexStr(output.data); console.log("Random: " + str); } catch (err) { - console.error("Random: " + err) + console.error("[error] Random: " + err); } } + +export function testRandom() { + console.log(">>>>>>>>>>>>>>>>>>>> RandomSync"); + testRandomSync(); +} diff --git a/frameworks/js/ani/test/test_sym_key_generator.ets b/frameworks/js/ani/test/test_sym_key_generator.ets new file mode 100644 index 0000000000000000000000000000000000000000..d06e8389bda4918905f618d06fd2950803a3deb5 --- /dev/null +++ b/frameworks/js/ani/test/test_sym_key_generator.ets @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2025-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import cryptoFramework from "@ohos.security.cryptoFramework"; +import utils from "./test_utils"; + +function testSymKeyGeneratorSync() { + try { + let generator = cryptoFramework.createSymKeyGenerator('SM4_128'); + let symKey = generator.generateSymKeySync(); + let encodedKey = symKey.getEncoded(); + let str = utils.uint8ArrayToHexStr(encodedKey.data); + console.log("generateSymKey: " + str); + } catch (err) { + console.error("[error] generateSymKey: " + err); + } +} + +function testSymKeyConvertKeySync() { + try { + let keyBlob: cryptoFramework.DataBlob = { + data: utils.stringToUint8Array('12345678abcdefgh12345678abcdefgh12345678abcdefgh12345678abcdefgh') + } + let generator = cryptoFramework.createSymKeyGenerator('HMAC'); + let symKey = generator.convertKeySync(keyBlob); + let encodedKey = symKey.getEncoded(); + let str = utils.uint8ArrayToHexStr(encodedKey.data); + console.log("convertKey: " + str); + } catch (err) { + console.error("[error] convertKey: " + err); + } +} + +export function testSymKeyGenerator() { + console.log(">>>>>>>>>>>>>>>>>>>> SymKeyGeneratorSync"); + testSymKeyGeneratorSync(); + console.log(">>>>>>>>>>>>>>>>>>>> SymKeyConvertKeySync"); + testSymKeyConvertKeySync(); +} diff --git a/frameworks/js/ani/test/test_utils.ets b/frameworks/js/ani/test/test_utils.ets index 38a123987e38e0f561b68e72c84d398494a03f61..2eff593112e95385d5bcc29f27e0e3086b80427c 100644 --- a/frameworks/js/ani/test/test_utils.ets +++ b/frameworks/js/ani/test/test_utils.ets @@ -41,11 +41,20 @@ export function uint8ArrayToHexStr(data: Uint8Array): string { // return buffer.from(data).toString('hex').toUpperCase(); let str = ''; for (let i = 0; i < data.length; i++) { - let num: Number = new Number(data[i]) + let num: Number = new Number(data[i]); str += num.toString(16).padStart(2, '0'); } return str; } + +export function uint8ArrayToString(data: Uint8Array): string { + // return buffer.from(data).toString('utf-8').toUpperCase(); + let str = ''; + for (let i = 0; i < data.length; i++) { + str += String.fromCharCode(data[i]); + } + return str; +} } // namespace utils export default utils;