1 /*
2 * Copyright (c) 2025-2025 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "ani_rand.h"
17
18 using namespace taihe;
19 using namespace ohos::security::cryptoFramework::cryptoFramework;
20 using namespace ANI::CryptoFramework;
21
22 namespace ANI::CryptoFramework {
RandomImpl()23 RandomImpl::RandomImpl() : randObj(nullptr) {}
24
RandomImpl(HcfRand * obj)25 RandomImpl::RandomImpl(HcfRand *obj) : randObj(obj) {}
26
~RandomImpl()27 RandomImpl::~RandomImpl()
28 {
29 HcfObjDestroy(randObj);
30 randObj = nullptr;
31 }
32
GenerateRandomSync(int32_t len)33 DataBlob RandomImpl::GenerateRandomSync(int32_t len)
34 {
35 if (randObj == nullptr) {
36 ANI_LOGE_THROW(HCF_INVALID_PARAMS, "rand obj is nullptr!");
37 return { taihe::array<uint8_t>(nullptr, 0) };
38 }
39 HcfBlob outBlob = { .data = nullptr, .len = 0 };
40 HcfResult res = randObj->generateRandom(randObj, len, &outBlob);
41 if (res != HCF_SUCCESS) {
42 ANI_LOGE_THROW(res, "generateRandom failed!");
43 return { taihe::array<uint8_t>(nullptr, 0) };
44 }
45 taihe::array<uint8_t> data(move_data_t{}, outBlob.data, outBlob.len);
46 HcfBlobDataClearAndFree(&outBlob);
47 return { data };
48 }
49
SetSeed(DataBlob const & seed)50 void RandomImpl::SetSeed(DataBlob const& seed)
51 {
52 if (randObj == nullptr) {
53 ANI_LOGE_THROW(HCF_INVALID_PARAMS, "rand obj is nullptr!");
54 return;
55 }
56 HcfBlob seedBlob = { .data = seed.data.data(), .len = seed.data.size() };
57 HcfResult res = randObj->setSeed(randObj, &seedBlob);
58 if (res != HCF_SUCCESS) {
59 ANI_LOGE_THROW(res, "set seed failed.");
60 return;
61 }
62 }
63
GetAlgName()64 string RandomImpl::GetAlgName()
65 {
66 if (randObj == nullptr) {
67 return "";
68 }
69 const char *algName = randObj->getAlgoName(randObj);
70 return (algName == nullptr) ? "" : string(algName);
71 }
72
CreateRandom()73 Random CreateRandom()
74 {
75 HcfRand *randObj = nullptr;
76 HcfResult res = HcfRandCreate(&randObj);
77 if (res != HCF_SUCCESS) {
78 ANI_LOGE_THROW(res, "create C rand obj failed.");
79 return make_holder<RandomImpl, Random>(nullptr);
80 }
81 return make_holder<RandomImpl, Random>(randObj);
82 }
83 } // namespace ANI::CryptoFramework
84
85 TH_EXPORT_CPP_API_CreateRandom(CreateRandom);
86