Jack He | 78b69d9 | 2018-11-16 02:59:43 -0800 | [diff] [blame] | 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 <algorithm> |
| 22 | |
| 23 | #include <base/logging.h> |
| 24 | #include <openssl/hmac.h> |
| 25 | |
| 26 | #include "bt_trace.h" |
| 27 | |
| 28 | namespace bluetooth { |
| 29 | namespace common { |
| 30 | |
| 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; }); |
| 34 | } |
| 35 | |
| 36 | void AddressObfuscator::Initialize(const Octet32& salt_256bit) { |
| 37 | std::lock_guard<std::recursive_mutex> lock(instance_mutex_); |
| 38 | salt_256bit_ = salt_256bit; |
| 39 | } |
| 40 | |
| 41 | bool AddressObfuscator::IsInitialized() { |
| 42 | std::lock_guard<std::recursive_mutex> lock(instance_mutex_); |
| 43 | return IsSaltValid(salt_256bit_); |
| 44 | } |
| 45 | |
| 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); |
| 56 | } |
| 57 | |
| 58 | } // namespace common |
| 59 | } // namespace bluetooth |