| 307 | } |
| 308 | |
| 309 | int32_t AesEncryptor::AesEncryptorImpl::CtrEncrypt(std::span<const uint8_t> plaintext, |
| 310 | std::span<const uint8_t> key, |
| 311 | std::span<const uint8_t> nonce, |
| 312 | std::span<uint8_t> ciphertext) { |
| 313 | int len; |
| 314 | int32_t ciphertext_len; |
| 315 | |
| 316 | if (nonce.size() != static_cast<size_t>(kNonceLength)) { |
| 317 | std::stringstream ss; |
| 318 | ss << "Invalid nonce size " << nonce.size() << ", expected " << kNonceLength; |
| 319 | throw ParquetException(ss.str()); |
| 320 | } |
| 321 | |
| 322 | // Parquet CTR IVs are comprised of a 12-byte nonce and a 4-byte initial |
| 323 | // counter field. |
| 324 | // The first 31 bits of the initial counter field are set to 0, the last bit |
| 325 | // is set to 1. |
| 326 | std::array<uint8_t, kCtrIvLength> iv{}; |
| 327 | std::copy(nonce.begin(), nonce.begin() + kNonceLength, iv.begin()); |
| 328 | iv[kCtrIvLength - 1] = 1; |
| 329 | |
| 330 | auto ctx = MakeCipherContext(); |
| 331 | |
| 332 | // Setting key and IV |
| 333 | if (1 != EVP_EncryptInit_ex(ctx.get(), nullptr, nullptr, key.data(), iv.data())) { |
| 334 | throw ParquetException("Couldn't set key and IV"); |
| 335 | } |
| 336 | |
| 337 | // Encryption |
| 338 | if (plaintext.size() > static_cast<size_t>(std::numeric_limits<int>::max())) { |
| 339 | std::stringstream ss; |
| 340 | ss << "Plaintext size " << plaintext.size() << " overflows int"; |
| 341 | throw ParquetException(ss.str()); |
| 342 | } |
| 343 | if (1 != EVP_EncryptUpdate( |
| 344 | ctx.get(), ciphertext.data() + length_buffer_length_ + kNonceLength, &len, |
| 345 | plaintext.data(), static_cast<int>(plaintext.size()))) { |
| 346 | throw ParquetException("Failed encryption update"); |
| 347 | } |
| 348 | |
| 349 | ciphertext_len = len; |
| 350 | |
| 351 | // Finalization |
| 352 | if (1 != EVP_EncryptFinal_ex( |
| 353 | ctx.get(), ciphertext.data() + length_buffer_length_ + kNonceLength + len, |
| 354 | &len)) { |
| 355 | throw ParquetException("Failed encryption finalization"); |
| 356 | } |
| 357 | |
| 358 | ciphertext_len += len; |
| 359 | |
| 360 | // Copying the buffer size and nonce to ciphertext |
| 361 | int32_t buffer_size = kNonceLength + ciphertext_len; |
| 362 | if (length_buffer_length_ > 0) { |
| 363 | ciphertext[3] = static_cast<uint8_t>(0xff & (buffer_size >> 24)); |
| 364 | ciphertext[2] = static_cast<uint8_t>(0xff & (buffer_size >> 16)); |
| 365 | ciphertext[1] = static_cast<uint8_t>(0xff & (buffer_size >> 8)); |
| 366 | ciphertext[0] = static_cast<uint8_t>(0xff & (buffer_size)); |