Tianjie Xu | a0a12cf | 2019-12-05 21:50:22 -0800 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2019 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | #pragma once |
| 18 | |
| 19 | #include <stdint.h> |
| 20 | |
| 21 | #include <bitset> |
| 22 | #include <queue> |
| 23 | #include <utility> |
| 24 | #include <vector> |
| 25 | |
| 26 | namespace aidl { |
| 27 | namespace android { |
| 28 | namespace hardware { |
| 29 | namespace rebootescrow { |
| 30 | namespace hadamard { |
| 31 | |
| 32 | constexpr uint32_t CODE_K = 15; |
| 33 | constexpr uint32_t ENCODE_LENGTH = 1u << CODE_K; |
| 34 | constexpr auto KEY_SIZE_IN_BYTES = 32u; |
| 35 | |
| 36 | // Encodes a 2 bytes word with hadamard code. The encoding expands a word of k+1 bits to a 2^k |
| 37 | // bitset. Returns the encoded bitset. |
| 38 | std::bitset<ENCODE_LENGTH> EncodeWord(uint16_t word); |
| 39 | |
| 40 | // Decodes the input bitset, and returns a sorted list of pair with (score, value). The value with |
| 41 | // a higher score indicates a greater likehood. |
| 42 | std::priority_queue<std::pair<int32_t, uint16_t>> DecodeWord( |
| 43 | const std::bitset<ENCODE_LENGTH>& encoded); |
| 44 | |
| 45 | // Encodes a key that has a size of KEY_SIZE_IN_BYTES. Returns a byte array representation of the |
| 46 | // encoded bitset. So a 32 bytes key will expand to 16*(2^15) bits = 64KiB. |
| 47 | std::vector<uint8_t> EncodeKey(const std::vector<uint8_t>& input); |
| 48 | |
| 49 | // Given a byte array representation of the encoded keys, decodes it and return the result. |
| 50 | std::vector<uint8_t> DecodeKey(const std::vector<uint8_t>& encoded); |
| 51 | |
| 52 | // Converts a bitset of length |ENCODE_LENGTH| to a byte array. |
| 53 | std::vector<uint8_t> BitsetToBytes(const std::bitset<ENCODE_LENGTH>& encoded_bits); |
| 54 | |
| 55 | // Converts a byte array of encoded words back to the bitset. |
| 56 | std::bitset<ENCODE_LENGTH> BytesToBitset(const std::vector<uint8_t>& encoded); |
| 57 | |
| 58 | } // namespace hadamard |
| 59 | } // namespace rebootescrow |
| 60 | } // namespace hardware |
| 61 | } // namespace android |
| 62 | } // namespace aidl |