QUICHE team | fd50a40 | 2018-12-07 22:54:05 -0500 | [diff] [blame^] | 1 | #include "net/third_party/quiche/src/http2/test_tools/http2_random.h" |
| 2 | |
| 3 | #include "base/logging.h" |
| 4 | #include "net/third_party/quiche/src/http2/platform/api/http2_string_utils.h" |
| 5 | #include "third_party/boringssl/src/include/openssl/chacha.h" |
| 6 | #include "third_party/boringssl/src/include/openssl/rand.h" |
| 7 | |
| 8 | static const uint8_t kZeroNonce[12] = {0}; |
| 9 | |
| 10 | namespace http2 { |
| 11 | namespace test { |
| 12 | |
| 13 | Http2Random::Http2Random() { |
| 14 | RAND_bytes(key_, sizeof(key_)); |
| 15 | |
| 16 | LOG(INFO) << "Initialized test RNG with the following key: " << Key(); |
| 17 | } |
| 18 | |
| 19 | Http2Random::Http2Random(Http2StringPiece key) { |
| 20 | Http2String decoded_key = Http2HexDecode(key); |
| 21 | CHECK_EQ(sizeof(key_), decoded_key.size()); |
| 22 | memcpy(key_, decoded_key.data(), sizeof(key_)); |
| 23 | } |
| 24 | |
| 25 | Http2String Http2Random::Key() const { |
| 26 | return Http2HexEncode(key_, sizeof(key_)); |
| 27 | } |
| 28 | |
| 29 | void 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 | |
| 36 | Http2String Http2Random::RandString(int length) { |
| 37 | Http2String result; |
| 38 | result.resize(length); |
| 39 | FillRandom(&result[0], length); |
| 40 | return result; |
| 41 | } |
| 42 | |
| 43 | uint64_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 | |
| 52 | double 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 | |
| 61 | Http2String Http2Random::RandStringWithAlphabet(int length, |
| 62 | Http2StringPiece alphabet) { |
| 63 | Http2String result; |
| 64 | 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 |