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 #include "ble_utils.h"
17
18 #include <ctime>
19 #include <random>
20 #include <sstream>
21
22 #include "securec.h"
23
24 namespace OHOS {
25 namespace bluetooth {
IntToHexString(uint8_t value)26 std::string BleUtils::IntToHexString(uint8_t value)
27 {
28 std::stringstream strStream;
29 char token[HEX_FORMAT_SIZE] = {0};
30 (void)sprintf_s(token, HEX_FORMAT_SIZE, "%02X", value);
31 strStream << token;
32 return strStream.str();
33 }
34
ConvertIntToHexString(const std::vector<uint8_t> & key)35 std::string BleUtils::ConvertIntToHexString(const std::vector<uint8_t> &key)
36 {
37 std::string strs;
38 for (auto iter = key.begin(); iter != key.end(); iter++) {
39 uint8_t temp = *iter;
40 strs += IntToHexString(temp);
41 }
42 return strs;
43 }
44
ConvertHexStringToInt(const std::string & str,std::vector<uint8_t> & key)45 void BleUtils::ConvertHexStringToInt(const std::string &str, std::vector<uint8_t> &key)
46 {
47 for (size_t i = 0; i < str.size(); i = i + 2) { // 2 is the length of str to be truncated
48 long k = std::stol(str.substr(i, 2), nullptr, HEX);
49 key.push_back(k);
50 }
51 }
52
Rand16hex(std::vector<uint8_t> & key)53 void BleUtils::Rand16hex(std::vector<uint8_t> &key)
54 {
55 uint8_t result = 0;
56 uint8_t n3 = 0;
57
58 std::random_device rd;
59 std::default_random_engine re(rd());
60 std::uniform_int_distribution<int> random_value(0, (((unsigned int)(-1)) >> 1));
61
62 for (int i = 0; i < BLE_IRK_HEX_ELN; i++) {
63 if (n3 == 0) {
64 result = random_value(re);
65 n3 = BLE_IRK_RAND_HEX_LEN;
66 }
67 key.push_back(result & BLE_IRK_RAND_ELN);
68 result >>= BLE_IRK_RAND_LEFT_SHIFT;
69 --n3;
70 }
71 }
72
GetRandomAddress(std::vector<uint8_t> & addr,bool isNonResPriAddr)73 void BleUtils::GetRandomAddress(std::vector<uint8_t> &addr, bool isNonResPriAddr)
74 {
75 std::random_device rd;
76 std::default_random_engine re(rd());
77 std::uniform_int_distribution<uint8_t> random_value(0, BLE_STATIC_PRI_ADDR);
78
79 for (int i = 0; i < BT_ADDRESS_SIZE - 1; ++i) {
80 addr.push_back(random_value(re) & 0xff);
81 }
82
83 if (isNonResPriAddr) {
84 addr.push_back(random_value(re) & BLE_NON_RES_PRI_ADDR);
85 } else {
86 addr.push_back((random_value(re) & 0xff) | BLE_STATIC_PRI_ADDR);
87 }
88
89 return;
90 }
91 } // namespace bluetooth
92 } // namespace OHOS