1 /* 2 * Copyright (c) 2021 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 #ifndef VALUE_HASH_CALC_H 17 #define VALUE_HASH_CALC_H 18 19 #include <vector> 20 21 #include <openssl/sha.h> 22 23 #include "db_types.h" 24 #include "db_errno.h" 25 #include "log_print.h" 26 27 namespace DistributedDB { 28 class ValueHashCalc { 29 public: ValueHashCalc()30 ValueHashCalc() {}; ~ValueHashCalc()31 ~ValueHashCalc() 32 { 33 if (context_ != nullptr) { 34 delete context_; 35 context_ = nullptr; 36 } 37 } 38 Initialize()39 int Initialize() 40 { 41 context_ = new (std::nothrow) SHA256_CTX; 42 if (context_ == nullptr) { 43 return -E_OUT_OF_MEMORY; 44 } 45 46 int errCode = SHA256_Init(context_); 47 if (errCode == 0) { 48 LOGE("sha init failed:%d", errCode); 49 return -E_CALC_HASH; 50 } 51 return E_OK; 52 } 53 Update(const std::vector<uint8_t> & value)54 int Update(const std::vector<uint8_t> &value) 55 { 56 if (context_ == nullptr) { 57 return -E_CALC_HASH; 58 } 59 int errCode = SHA256_Update(context_, value.data(), value.size()); 60 if (errCode == 0) { 61 LOGE("sha update failed:%d", errCode); 62 return -E_CALC_HASH; 63 } 64 return E_OK; 65 } 66 GetResult(std::vector<uint8_t> & value)67 int GetResult(std::vector<uint8_t> &value) 68 { 69 if (context_ == nullptr) { 70 return -E_CALC_HASH; 71 } 72 73 value.resize(SHA256_DIGEST_LENGTH); 74 int errCode = SHA256_Final(value.data(), context_); 75 if (errCode == 0) { 76 LOGE("sha get result failed:%d", errCode); 77 return -E_CALC_HASH; 78 } 79 80 return E_OK; 81 } 82 83 private: 84 SHA256_CTX *context_ = nullptr; 85 }; 86 } 87 88 #endif // VALUE_HASH_CALC_H 89