1 /* 2 * Copyright (C) 2020 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 <optional> 22 #include <vector> 23 24 #include <openssl/aead.h> 25 26 namespace adb { 27 namespace pairing { 28 29 class Aes128Gcm { 30 public: 31 explicit Aes128Gcm(const uint8_t* key_material, size_t key_material_len); 32 33 // Encrypt a block of data in |in| of length |in_len|, this consumes all data 34 // in |in| and places the encrypted data in |out| if |out_len| indicates that 35 // there is enough space. The data contains information needed for 36 // decryption that is specific to this implementation and is therefore only 37 // suitable for decryption with this class. 38 // The method returns the number of bytes placed in |out| on success and a 39 // negative value if an error occurs. 40 std::optional<size_t> Encrypt(const uint8_t* in, size_t in_len, uint8_t* out, size_t out_len); 41 // Decrypt a block of data in |in| of length |in_len|, this consumes all data 42 // in |in_len| bytes of data. The decrypted output is placed in the |out| 43 // buffer of length |out_len|. On successful decryption the number of bytes in 44 // |out| will be placed in |out_len|. 45 // The method returns the number of bytes consumed from the |in| buffer. If 46 // there is not enough data available in |in| the method returns zero. If 47 // an error occurs the method returns a negative value. 48 std::optional<size_t> Decrypt(const uint8_t* in, size_t in_len, uint8_t* out, size_t out_len); 49 50 // Return a safe amount of buffer storage needed to encrypt |size| bytes. 51 size_t EncryptedSize(size_t size); 52 // Return a safe amount of buffer storage needed to decrypt |size| bytes. 53 size_t DecryptedSize(size_t size); 54 55 private: 56 bssl::ScopedEVP_AEAD_CTX context_; 57 // Sequence numbers to use as nonces in the encryption scheme 58 uint64_t dec_sequence_ = 0; 59 uint64_t enc_sequence_ = 0; 60 }; 61 62 } // namespace pairing 63 } // namespace adb 64