• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023 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 "dm_crypto.h"
16 
17 #include <iostream>
18 #include <random>
19 #include <sstream>
20 
21 #include "openssl/sha.h"
22 
23 namespace OHOS {
24 namespace DistributedHardware {
25 
26 namespace {
27 constexpr int32_t HEX_TO_UINT8 = 2;
28 constexpr int WIDTH = 4;
29 constexpr unsigned char MASK = 0x0F;
30 } // namespace
31 
Sha256(const std::string & text,bool isUpper)32 std::string Crypto::Sha256(const std::string &text, bool isUpper)
33 {
34     return Sha256(text.data(), text.size(), isUpper);
35 }
36 
Sha256(const void * data,size_t size,bool isUpper)37 std::string Crypto::Sha256(const void *data, size_t size, bool isUpper)
38 {
39     unsigned char hash[SHA256_DIGEST_LENGTH * HEX_TO_UINT8 + 1] = "";
40     SHA256_CTX ctx;
41     SHA256_Init(&ctx);
42     SHA256_Update(&ctx, data, size);
43     SHA256_Final(&hash[SHA256_DIGEST_LENGTH], &ctx);
44     // here we translate sha256 hash to hexadecimal. each 8-bit char will be presented by two characters([0-9a-f])
45     const char* hexCode = isUpper ? "0123456789ABCDEF" : "0123456789abcdef";
46     for (int32_t i = 0; i < SHA256_DIGEST_LENGTH; ++i) {
47         unsigned char value = hash[SHA256_DIGEST_LENGTH + i];
48         // uint8_t is 2 digits in hexadecimal.
49         hash[i * HEX_TO_UINT8] = hexCode[(value >> WIDTH) & MASK];
50         hash[i * HEX_TO_UINT8 + 1] = hexCode[value & MASK];
51     }
52     hash[SHA256_DIGEST_LENGTH * HEX_TO_UINT8] = 0;
53     std::stringstream ss;
54     ss << hash;
55     return ss.str();
56 }
57 } // namespace DistributedHardware
58 } // namespace OHOS
59