| 89 | } |
| 90 | |
| 91 | void TestEncryptionDecryption(const int64_t buffer_size) { |
| 92 | vector<uint8_t> original(buffer_size); |
| 93 | // Scratch buffer for in-place encryption. |
| 94 | vector<uint8_t> scratch(buffer_size + AES_BLOCK_SIZE); |
| 95 | if (buffer_size % 8 == 0) { |
| 96 | GenerateRandomData(original.data(), buffer_size); |
| 97 | } else { |
| 98 | GenerateRandomBytes(original.data(), buffer_size); |
| 99 | } |
| 100 | |
| 101 | // Check all the modes |
| 102 | AES_CIPHER_MODE modes[] = { |
| 103 | AES_CIPHER_MODE::AES_256_GCM, |
| 104 | AES_CIPHER_MODE::AES_256_CTR, |
| 105 | AES_CIPHER_MODE::AES_256_CFB, |
| 106 | AES_CIPHER_MODE::AES_256_ECB, |
| 107 | AES_CIPHER_MODE::AES_128_GCM, |
| 108 | AES_CIPHER_MODE::AES_128_ECB, |
| 109 | }; |
| 110 | for (auto m : modes) { |
| 111 | memcpy(scratch.data(), original.data(), buffer_size); |
| 112 | |
| 113 | EncryptionKey key; |
| 114 | ASSERT_OK(key.InitializeRandom(AES_BLOCK_SIZE, m)); |
| 115 | |
| 116 | int64_t encrypted_length; |
| 117 | if (key.IsEcbMode() && buffer_size > numeric_limits<int>::max() - AES_BLOCK_SIZE) { |
| 118 | ASSERT_ERROR_MSG(key.Encrypt(scratch.data(),buffer_size, scratch.data()), |
| 119 | "Input buffer length exceeds the supported length for ECB mode."); |
| 120 | continue; |
| 121 | } |
| 122 | ASSERT_OK(key.Encrypt(scratch.data(), buffer_size, scratch.data(), |
| 123 | &encrypted_length)); |
| 124 | |
| 125 | // Check that encryption did something |
| 126 | ASSERT_NE(0, memcmp(original.data(), scratch.data(), buffer_size)); |
| 127 | ASSERT_OK(key.Decrypt(scratch.data(), encrypted_length, scratch.data())); |
| 128 | // Check that we get the original data back. |
| 129 | ASSERT_EQ(0, memcmp(original.data(), scratch.data(), buffer_size)); |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | mt19937_64 rng_; |
| 134 | }; |