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_md.h"
17
18 using namespace taihe;
19 using namespace ohos::security::cryptoFramework::cryptoFramework;
20 using namespace ANI::CryptoFramework;
21
22 namespace ANI::CryptoFramework {
MdImpl()23 MdImpl::MdImpl() : mdObj(nullptr) {}
24
MdImpl(HcfMd * obj)25 MdImpl::MdImpl(HcfMd *obj) : mdObj(obj) {}
26
~MdImpl()27 MdImpl::~MdImpl() {}
28
UpdateSync(DataBlob const & input)29 void MdImpl::UpdateSync(DataBlob const& input)
30 {
31 if (mdObj == nullptr) {
32 ANI_LOGE_THROW(HCF_INVALID_PARAMS, "md obj is nullptr!");
33 return;
34 }
35 HcfBlob inBlob = { .data = input.data.data(), .len = input.data.size() };
36 HcfResult res = mdObj->update(mdObj, &inBlob);
37 if (res != HCF_SUCCESS) {
38 ANI_LOGE_THROW(res, "md update failed!");
39 return;
40 }
41 }
42
DigestSync()43 DataBlob MdImpl::DigestSync()
44 {
45 if (mdObj == nullptr) {
46 ANI_LOGE_THROW(HCF_INVALID_PARAMS, "md obj is nullptr!");
47 return { taihe::array<uint8_t>(nullptr, 0) };
48 }
49 HcfBlob outBlob = { .data = nullptr, .len = 0 };
50 HcfResult res = mdObj->doFinal(mdObj, &outBlob);
51 if (res != HCF_SUCCESS) {
52 ANI_LOGE_THROW(res, "md doFinal failed!");
53 return { taihe::array<uint8_t>(nullptr, 0) };
54 }
55 taihe::array<uint8_t> data(move_data_t{}, outBlob.data, outBlob.len);
56 HcfBlobDataClearAndFree(&outBlob);
57 return { data };
58 }
59
GetMdLength()60 int32_t MdImpl::GetMdLength()
61 {
62 if (mdObj == nullptr) {
63 ANI_LOGE_THROW(HCF_INVALID_PARAMS, "md obj is nullptr!");
64 return 0;
65 }
66 uint32_t length = mdObj->getMdLength(mdObj);
67 return static_cast<int32_t>(length);
68 }
69
GetAlgName()70 string MdImpl::GetAlgName()
71 {
72 if (mdObj == nullptr) {
73 return "";
74 }
75 const char *algName = mdObj->getAlgoName(mdObj);
76 return (algName == nullptr) ? "" : string(algName);
77 }
78
CreateMd(string_view algName)79 Md CreateMd(string_view algName)
80 {
81 HcfMd *mdObj = nullptr;
82 HcfResult res = HcfMdCreate(algName.c_str(), &mdObj);
83 if (res != HCF_SUCCESS) {
84 ANI_LOGE_THROW(res, "create C md obj failed.");
85 return make_holder<MdImpl, Md>(nullptr);
86 }
87 return make_holder<MdImpl, Md>(mdObj);
88 }
89 } // namespace ANI::CryptoFramework
90
91 TH_EXPORT_CPP_API_CreateMd(CreateMd);
92