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 DISTRIBUTEDDATAMGR_VALUE_HASH_H
17 #define DISTRIBUTEDDATAMGR_VALUE_HASH_H
18 
19 #include <vector>
20 #include <openssl/sha.h>
21 
22 namespace OHOS {
23 namespace DistributedDataDfx {
24 class ValueHash {
25 public:
ValueHash()26     ValueHash() {}
~ValueHash()27     ~ValueHash() {}
28 
CalcValueHash(const std::string & input,std::string & res)29     bool CalcValueHash(const std::string &input, std::string &res)
30     {
31         SHA256_CTX context;
32         std::vector<uint8_t> value(input.begin(), input.end());
33         if (!SHA256_Init(&context)) {
34             return false;
35         }
36         if (!SHA256_Update(&context, value.data(), value.size())) {
37             return false;
38         }
39 
40         std::vector<uint8_t> result;
41         result.resize(SHA256_DIGEST_LENGTH);
42         if (!SHA256_Final(result.data(), &context)) {
43             return false;
44         }
45         if (result.size() < LEN) {
46             res = std::string(result.begin(), result.end());
47             return true;
48         }
49         res = std::string(result.end() - LEN, result.end());
50         return true;
51     }
52 
53 private:
54     static constexpr int LEN = 8; // 8 is the substring length
55 };
56 }  // namespace DistributedDataDfx
57 }  // namespace OHOS
58 #endif // DISTRIBUTEDDATAMGR_VALUE_HASH_H
59