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