#include "test_util.hh" #include #include #include #include "../testing/support/public/simulated_environment.hh" #include "crypto_core.h" namespace { using ::testing::Each; using ::testing::Eq; using tox::test::SimulatedEnvironment; TEST(CryptoCoreTestUtil, RandomBytesDoesNotTouchZeroSizeArray) { SimulatedEnvironment env; auto c_rng = env.fake_random().get_c_random(); std::array bytes{}; for (uint32_t i = 0; i < 100; ++i) { random_bytes(&c_rng, bytes.data(), 0); ASSERT_THAT(bytes, Each(Eq(0x00))); } } TEST(CryptoCoreTestUtil, RandomBytesFillsEntireArray) { SimulatedEnvironment env; auto c_rng = env.fake_random().get_c_random(); std::array bytes{}; for (uint32_t size = 1; size < bytes.size(); ++size) { bool const success = [&]() { // Try a few times. There ought to be a non-zero byte in our randomness at // some point. for (uint32_t i = 0; i < 100; ++i) { random_bytes(&c_rng, bytes.data(), bytes.size()); if (bytes[size - 1] != 0x00) { return true; } } return false; }(); ASSERT_TRUE(success); } } TEST(CryptoCoreTestUtil, RandomBytesDoesNotBufferOverrun) { SimulatedEnvironment env; auto c_rng = env.fake_random().get_c_random(); std::array bytes{}; // Try a few times. It should never overrun. for (uint32_t i = 0; i < 100; ++i) { for (uint32_t diff = 1; diff < sizeof(uint64_t); ++diff) { bytes = {}; random_bytes(&c_rng, bytes.data(), bytes.size() - diff); // All bytes not in the range we want to write should be 0. ASSERT_THAT(std::vector(bytes.begin() + (bytes.size() - diff), bytes.end()), Each(Eq(0x00))); } } } } // namespace