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 #pragma once
20 
21 #include <array>
22 #include <mutex>
23 #include <string>
24 
25 #include "raw_address.h"
26 
27 namespace bluetooth {
28 namespace common {
29 
30 class AddressObfuscator {
31  public:
32   static constexpr unsigned int kOctet32Length = 32;
33   using Octet32 = std::array<uint8_t, kOctet32Length>;
GetInstance()34   static AddressObfuscator* GetInstance() {
35     static auto instance = new AddressObfuscator();
36     return instance;
37   }
38 
39   /**
40    * Return true if the input salt is valid
41    * Criteria:
42    * - Salt must be non-zero
43    *
44    * @param salt_256bit
45    * @return true if the salt is valid
46    */
47   static bool IsSaltValid(const Octet32& salt_256bit);
48 
49   /**
50    * Initialize this obfuscator with necessary parameters
51    *
52    * @param salt_256bit a 256 bit salt used to hash the fixed length address
53    */
54   void Initialize(const Octet32& salt_256bit);
55 
56   /**
57    * Return true if Initialize() was called earlier
58    */
59   bool IsInitialized();
60 
61   /**
62    * Obfuscate Bluetooth MAC address into an anonymous ID string
63    *
64    * @param address Bluetooth MAC address to be obfuscated
65    * @return the obfuscated MAC address in 256 bit
66    */
67   std::string Obfuscate(const RawAddress& address);
68 
69  private:
AddressObfuscator()70   AddressObfuscator() : salt_256bit_({0}) {}
71   Octet32 salt_256bit_;
72   std::recursive_mutex instance_mutex_;
73 };
74 
75 }  // namespace common
76 }  // namespace bluetooth