Line | Count | Source (jump to first uncovered line) |
1 | | // Copyright 2018 Google Inc. |
2 | | // |
3 | | // Licensed under the Apache License, Version 2.0 (the "License"); |
4 | | // you may not use this file except in compliance with the License. |
5 | | // You may obtain a copy of the License at |
6 | | // |
7 | | // http://www.apache.org/licenses/LICENSE-2.0 |
8 | | // |
9 | | // Unless required by applicable law or agreed to in writing, software |
10 | | // distributed under the License is distributed on an "AS IS" BASIS, |
11 | | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
12 | | // See the License for the specific language governing permissions and |
13 | | // limitations under the License. |
14 | | |
15 | | #ifndef FAKE_RANDOM_H_ |
16 | | #define FAKE_RANDOM_H_ |
17 | | |
18 | | #include <sodium.h> |
19 | | #include <assert.h> |
20 | | #include <stdint.h> |
21 | | #include <string.h> |
22 | | #include <algorithm> |
23 | | |
24 | | static const unsigned char * SEED_DATA; |
25 | | static size_t SEED_SIZE; |
26 | | |
27 | | static const char * |
28 | 319 | fake_implementation_name(void) { |
29 | 319 | return "fake_random"; |
30 | 319 | } |
31 | | |
32 | | static void |
33 | 638 | fake_random_buffer(void * const buf, const size_t size) { |
34 | 638 | static unsigned char seed[randombytes_SEEDBYTES]; |
35 | 638 | memset(seed, '0', randombytes_SEEDBYTES); |
36 | | |
37 | 638 | size_t boundary = std::min((size_t) randombytes_SEEDBYTES, SEED_SIZE); |
38 | 638 | memcpy(&seed, SEED_DATA, boundary); |
39 | | |
40 | 638 | randombytes_buf_deterministic(buf, size, seed); |
41 | 638 | } |
42 | | |
43 | | struct randombytes_implementation fake_random = { |
44 | | .implementation_name = fake_implementation_name, |
45 | | .random = NULL, |
46 | | .stir = NULL, |
47 | | .uniform = NULL, |
48 | | .buf = fake_random_buffer, |
49 | | .close = NULL |
50 | | }; |
51 | | |
52 | | void |
53 | 319 | setup_fake_random(const unsigned char * seed, const size_t seed_size) { |
54 | 319 | SEED_DATA = seed; |
55 | 319 | SEED_SIZE = seed_size; |
56 | | |
57 | 319 | int fake_random_set = randombytes_set_implementation(&fake_random); |
58 | 319 | assert(fake_random_set == 0); |
59 | | |
60 | 0 | assert(strcmp(randombytes_implementation_name(), "fake_random") == 0); |
61 | 0 | int initialized = sodium_init(); |
62 | 319 | assert(initialized >= 0); |
63 | 319 | } |
64 | | |
65 | | #endif // FAKE_RANDOM_H_ |