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