1 /*
2 * Copyright (c) 2024-2024 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 #include "fs_digest_utils.h"
16 #include "securec.h"
17
AddData(const std::string & data)18 void DigestUtils::AddData(const std::string &data)
19 {
20 AddData(data.data(), (int)data.size());
21 }
22
AddData(const char * data,int length)23 void DigestUtils::AddData(const char* data, int length)
24 {
25 int ret = EVP_DigestUpdate(m_ctx, data, length);
26 if (ret < 1) {
27 printf("Update DigestFunc failed!\n");
28 }
29 }
30
Result(DigestUtils::Type type)31 std::string DigestUtils::Result(DigestUtils::Type type)
32 {
33 unsigned int len = 0;
34
35 const std::map<HashType, int> hashLength = {
36 {HASH_SHA256, SHA256_DIGEST_LENGTH},
37 {HASH_SHA384, SHA384_DIGEST_LENGTH},
38 };
39
40 unsigned char* md = reinterpret_cast<unsigned char*>(new char[hashLength.at(m_type)]);
41 int ret = EVP_DigestFinal_ex(m_ctx, md, &len);
42 if (ret < 1) {
43 printf("Failed to Calculate Hash Relsult\n");
44 }
45 int temporaryVariableFirst = 2;
46 if (type == Type::HEX) {
47 int temporaryVariableSecond = 3;
48 char* res = new char[len * temporaryVariableFirst + 1];
49 for (unsigned int i = 0; i < len; i++) {
50 snprintf_s(&res[i * temporaryVariableFirst], temporaryVariableSecond,
51 temporaryVariableFirst, "%02x", md[i]);
52 }
53 std::string st{res, len * temporaryVariableFirst};
54 delete[]md;
55 delete[]res;
56 return st;
57 }
58 std::string st{reinterpret_cast<char*>(md), len};
59 delete[]md;
60 return st;
61 }
62
DigestUtils(HashType type)63 DigestUtils::DigestUtils(HashType type)
64 {
65 m_type = type;
66 m_ctx = EVP_MD_CTX_new();
67
68 const std::map<HashType, hashFunc> hashMethods = {
69 {HASH_SHA256, EVP_sha256},
70 {HASH_SHA384, EVP_sha384}
71 };
72
73 int ret = EVP_DigestInit_ex(m_ctx, hashMethods.at(type)(), nullptr);
74 if (ret < 1) {
75 printf("Init DigestFunc failed!\n");
76 }
77 }
78
~DigestUtils()79 DigestUtils::~DigestUtils()
80 {
81 if (m_ctx != nullptr) {
82 EVP_MD_CTX_free(m_ctx);
83 }
84 }