blob: 8f9014efd17e46d6e3be08fcb1421d55aeaec580 [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
bnc3bf526d2021-04-19 05:01:31 -07003#include "absl/strings/escaping.h"
QUICHE team5be974e2020-12-29 18:35:24 -05004#include "http2/platform/api/http2_logging.h"
5#include "http2/platform/api/http2_string_utils.h"
QUICHE teamfd50a402018-12-07 22:54:05 -05006#include "third_party/boringssl/src/include/openssl/chacha.h"
7#include "third_party/boringssl/src/include/openssl/rand.h"
8
9static const uint8_t kZeroNonce[12] = {0};
10
11namespace http2 {
12namespace test {
13
14Http2Random::Http2Random() {
15 RAND_bytes(key_, sizeof(key_));
16
QUICHE team61940b42019-03-07 23:32:27 -050017 HTTP2_LOG(INFO) << "Initialized test RNG with the following key: " << Key();
QUICHE teamfd50a402018-12-07 22:54:05 -050018}
19
vasilvv015e16a2020-10-12 23:51:06 -070020Http2Random::Http2Random(absl::string_view key) {
bnc3bf526d2021-04-19 05:01:31 -070021 std::string decoded_key = absl::HexStringToBytes(key);
vasilvvafcc3172021-02-02 12:01:07 -080022 QUICHE_CHECK_EQ(sizeof(key_), decoded_key.size());
QUICHE teamfd50a402018-12-07 22:54:05 -050023 memcpy(key_, decoded_key.data(), sizeof(key_));
24}
25
bnc47904002019-08-16 11:49:48 -070026std::string Http2Random::Key() const {
bnc3bf526d2021-04-19 05:01:31 -070027 return absl::BytesToHexString(
28 absl::string_view(reinterpret_cast<const char*>(key_), sizeof(key_)));
QUICHE teamfd50a402018-12-07 22:54:05 -050029}
30
31void Http2Random::FillRandom(void* buffer, size_t buffer_size) {
32 memset(buffer, 0, buffer_size);
33 uint8_t* buffer_u8 = reinterpret_cast<uint8_t*>(buffer);
34 CRYPTO_chacha_20(buffer_u8, buffer_u8, buffer_size, key_, kZeroNonce,
35 counter_++);
36}
37
bnc47904002019-08-16 11:49:48 -070038std::string Http2Random::RandString(int length) {
39 std::string result;
QUICHE teamfd50a402018-12-07 22:54:05 -050040 result.resize(length);
41 FillRandom(&result[0], length);
42 return result;
43}
44
45uint64_t Http2Random::Rand64() {
46 union {
47 uint64_t number;
48 uint8_t bytes[sizeof(uint64_t)];
49 } result;
50 FillRandom(result.bytes, sizeof(result.bytes));
51 return result.number;
52}
53
54double Http2Random::RandDouble() {
55 union {
56 double f;
57 uint64_t i;
58 } value;
59 value.i = (1023ull << 52ull) | (Rand64() & 0xfffffffffffffu);
60 return value.f - 1.0;
61}
62
vasilvv015e16a2020-10-12 23:51:06 -070063std::string Http2Random::RandStringWithAlphabet(int length,
64 absl::string_view alphabet) {
bnc47904002019-08-16 11:49:48 -070065 std::string result;
QUICHE teamfd50a402018-12-07 22:54:05 -050066 result.resize(length);
67 for (int i = 0; i < length; i++) {
68 result[i] = alphabet[Uniform(alphabet.size())];
69 }
70 return result;
71}
72
73} // namespace test
74} // namespace http2