| 228 | } |
| 229 | |
| 230 | int32_t AesEncryptor::AesEncryptorImpl::GcmEncrypt(std::span<const uint8_t> plaintext, |
| 231 | std::span<const uint8_t> key, |
| 232 | std::span<const uint8_t> nonce, |
| 233 | std::span<const uint8_t> aad, |
| 234 | std::span<uint8_t> ciphertext) { |
| 235 | int len; |
| 236 | int32_t ciphertext_len; |
| 237 | |
| 238 | std::array<uint8_t, kGcmTagLength> tag{}; |
| 239 | |
| 240 | if (nonce.size() != static_cast<size_t>(kNonceLength)) { |
| 241 | std::stringstream ss; |
| 242 | ss << "Invalid nonce size " << nonce.size() << ", expected " << kNonceLength; |
| 243 | throw ParquetException(ss.str()); |
| 244 | } |
| 245 | |
| 246 | auto ctx = MakeCipherContext(); |
| 247 | |
| 248 | // Setting key and IV (nonce) |
| 249 | if (1 != EVP_EncryptInit_ex(ctx.get(), nullptr, nullptr, key.data(), nonce.data())) { |
| 250 | throw ParquetException("Couldn't set key and nonce"); |
| 251 | } |
| 252 | |
| 253 | // Setting additional authenticated data |
| 254 | if (aad.size() > static_cast<size_t>(std::numeric_limits<int>::max())) { |
| 255 | std::stringstream ss; |
| 256 | ss << "AAD size " << aad.size() << " overflows int"; |
| 257 | throw ParquetException(ss.str()); |
| 258 | } |
| 259 | if ((!aad.empty()) && (1 != EVP_EncryptUpdate(ctx.get(), nullptr, &len, aad.data(), |
| 260 | static_cast<int>(aad.size())))) { |
| 261 | throw ParquetException("Couldn't set AAD"); |
| 262 | } |
| 263 | |
| 264 | // Encryption |
| 265 | if (plaintext.size() > static_cast<size_t>(std::numeric_limits<int>::max())) { |
| 266 | std::stringstream ss; |
| 267 | ss << "Plaintext size " << plaintext.size() << " overflows int"; |
| 268 | throw ParquetException(ss.str()); |
| 269 | } |
| 270 | if (1 != EVP_EncryptUpdate( |
| 271 | ctx.get(), ciphertext.data() + length_buffer_length_ + kNonceLength, &len, |
| 272 | plaintext.data(), static_cast<int>(plaintext.size()))) { |
| 273 | throw ParquetException("Failed encryption update"); |
| 274 | } |
| 275 | |
| 276 | ciphertext_len = len; |
| 277 | |
| 278 | // Finalization |
| 279 | if (1 != EVP_EncryptFinal_ex( |
| 280 | ctx.get(), ciphertext.data() + length_buffer_length_ + kNonceLength + len, |
| 281 | &len)) { |
| 282 | throw ParquetException("Failed encryption finalization"); |
| 283 | } |
| 284 | |
| 285 | ciphertext_len += len; |
| 286 | |
| 287 | // Getting the tag |