• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /******************************************************************************
2  *
3  *  Copyright 2018 Google, Inc.
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at:
8  *
9  *  http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  ******************************************************************************/
18 
19 #include "address_obfuscator.h"
20 
21 #include <base/logging.h>
22 #include <openssl/hmac.h>
23 
24 #include <algorithm>
25 
26 #include "bt_trace.h"
27 #include "types/raw_address.h"
28 
29 namespace bluetooth {
30 namespace common {
31 
IsSaltValid(const Octet32 & salt_256bit)32 bool AddressObfuscator::IsSaltValid(const Octet32& salt_256bit) {
33   return !std::all_of(salt_256bit.begin(), salt_256bit.end(),
34                       [](uint8_t i) { return i == 0; });
35 }
36 
Initialize(const Octet32 & salt_256bit)37 void AddressObfuscator::Initialize(const Octet32& salt_256bit) {
38   std::lock_guard<std::recursive_mutex> lock(instance_mutex_);
39   salt_256bit_ = salt_256bit;
40 }
41 
IsInitialized()42 bool AddressObfuscator::IsInitialized() {
43   std::lock_guard<std::recursive_mutex> lock(instance_mutex_);
44   return IsSaltValid(salt_256bit_);
45 }
46 
Obfuscate(const RawAddress & address)47 std::string AddressObfuscator::Obfuscate(const RawAddress& address) {
48   std::lock_guard<std::recursive_mutex> lock(instance_mutex_);
49   CHECK(IsInitialized());
50   std::array<uint8_t, EVP_MAX_MD_SIZE> result = {};
51   unsigned int out_len = 0;
52   CHECK(::HMAC(EVP_sha256(), salt_256bit_.data(), salt_256bit_.size(),
53                address.address, address.kLength, result.data(),
54                &out_len) != nullptr);
55   CHECK_EQ(out_len, static_cast<unsigned int>(kOctet32Length));
56   return std::string(reinterpret_cast<const char*>(result.data()), out_len);
57 }
58 
59 }  // namespace common
60 }  // namespace bluetooth
61