• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 *
fake_implementation_name(void)28 fake_implementation_name(void) {
29   return "fake_random";
30 }
31 
32 static void
fake_random_buffer(void * const buf,const size_t size)33 fake_random_buffer(void * const buf, const size_t size) {
34   static unsigned char seed[randombytes_SEEDBYTES];
35   memset(seed, '0', randombytes_SEEDBYTES);
36 
37   size_t boundary = std::min((size_t) randombytes_SEEDBYTES, SEED_SIZE);
38   memcpy(&seed, SEED_DATA, boundary);
39 
40   randombytes_buf_deterministic(buf, size, seed);
41 }
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
setup_fake_random(const unsigned char * seed,const size_t seed_size)53 setup_fake_random(const unsigned char * seed, const size_t seed_size) {
54   SEED_DATA = seed;
55   SEED_SIZE = seed_size;
56 
57   int fake_random_set = randombytes_set_implementation(&fake_random);
58   assert(fake_random_set == 0);
59 
60   assert(strcmp(randombytes_implementation_name(), "fake_random") == 0);
61   int initialized = sodium_init();
62   assert(initialized >= 0);
63 }
64 
65 #endif // FAKE_RANDOM_H_
66