1 /******************************************************************************
3 * Copyright 2018 Google, Inc.
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:
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 ******************************************************************************/
19 #include "address_obfuscator.h"
23 #include <base/logging.h>
24 #include <openssl/hmac.h>
31 bool AddressObfuscator::IsSaltValid(const Octet32& salt_256bit) {
32 return !std::all_of(salt_256bit.begin(), salt_256bit.end(),
33 [](uint8_t i) { return i == 0; });
36 void AddressObfuscator::Initialize(const Octet32& salt_256bit) {
37 std::lock_guard<std::recursive_mutex> lock(instance_mutex_);
38 salt_256bit_ = salt_256bit;
41 bool AddressObfuscator::IsInitialized() {
42 std::lock_guard<std::recursive_mutex> lock(instance_mutex_);
43 return IsSaltValid(salt_256bit_);
46 std::string AddressObfuscator::Obfuscate(const RawAddress& address) {
47 std::lock_guard<std::recursive_mutex> lock(instance_mutex_);
48 CHECK(IsInitialized());
49 std::array<uint8_t, EVP_MAX_MD_SIZE> result = {};
50 unsigned int out_len = 0;
51 CHECK(::HMAC(EVP_sha256(), salt_256bit_.data(), salt_256bit_.size(),
52 address.address, address.kLength, result.data(),
53 &out_len) != nullptr);
54 CHECK_EQ(out_len, static_cast<unsigned int>(kOctet32Length));
55 return std::string(reinterpret_cast<const char*>(result.data()), out_len);
59 } // namespace bluetooth