blob: ce1b93b13f66a7db927a4d78762e18d7a65fa7ab [file] [log] [blame]
QUICHE team5be974e2020-12-29 18:35:24 -05001#include "http2/test_tools/http2_random.h"
QUICHE teamfd50a402018-12-07 22:54:05 -05002
QUICHE team5be974e2020-12-29 18:35:24 -05003#include "http2/platform/api/http2_logging.h"
4#include "http2/platform/api/http2_string_utils.h"
QUICHE teamfd50a402018-12-07 22:54:05 -05005#include "third_party/boringssl/src/include/openssl/chacha.h"
6#include "third_party/boringssl/src/include/openssl/rand.h"
7
8static const uint8_t kZeroNonce[12] = {0};
9
10namespace http2 {
11namespace test {
12
13Http2Random::Http2Random() {
14 RAND_bytes(key_, sizeof(key_));
15
QUICHE team61940b42019-03-07 23:32:27 -050016 HTTP2_LOG(INFO) << "Initialized test RNG with the following key: " << Key();
QUICHE teamfd50a402018-12-07 22:54:05 -050017}
18
vasilvv015e16a2020-10-12 23:51:06 -070019Http2Random::Http2Random(absl::string_view key) {
bnc47904002019-08-16 11:49:48 -070020 std::string decoded_key = Http2HexDecode(key);
QUICHE teamfd50a402018-12-07 22:54:05 -050021 CHECK_EQ(sizeof(key_), decoded_key.size());
22 memcpy(key_, decoded_key.data(), sizeof(key_));
23}
24
bnc47904002019-08-16 11:49:48 -070025std::string Http2Random::Key() const {
QUICHE teamfd50a402018-12-07 22:54:05 -050026 return Http2HexEncode(key_, sizeof(key_));
27}
28
29void Http2Random::FillRandom(void* buffer, size_t buffer_size) {
30 memset(buffer, 0, buffer_size);
31 uint8_t* buffer_u8 = reinterpret_cast<uint8_t*>(buffer);
32 CRYPTO_chacha_20(buffer_u8, buffer_u8, buffer_size, key_, kZeroNonce,
33 counter_++);
34}
35
bnc47904002019-08-16 11:49:48 -070036std::string Http2Random::RandString(int length) {
37 std::string result;
QUICHE teamfd50a402018-12-07 22:54:05 -050038 result.resize(length);
39 FillRandom(&result[0], length);
40 return result;
41}
42
43uint64_t Http2Random::Rand64() {
44 union {
45 uint64_t number;
46 uint8_t bytes[sizeof(uint64_t)];
47 } result;
48 FillRandom(result.bytes, sizeof(result.bytes));
49 return result.number;
50}
51
52double Http2Random::RandDouble() {
53 union {
54 double f;
55 uint64_t i;
56 } value;
57 value.i = (1023ull << 52ull) | (Rand64() & 0xfffffffffffffu);
58 return value.f - 1.0;
59}
60
vasilvv015e16a2020-10-12 23:51:06 -070061std::string Http2Random::RandStringWithAlphabet(int length,
62 absl::string_view alphabet) {
bnc47904002019-08-16 11:49:48 -070063 std::string result;
QUICHE teamfd50a402018-12-07 22:54:05 -050064 result.resize(length);
65 for (int i = 0; i < length; i++) {
66 result[i] = alphabet[Uniform(alphabet.size())];
67 }
68 return result;
69}
70
71} // namespace test
72} // namespace http2