MOTION  0.01
Framework for mixed-protocol multi-party computation
random.h
Go to the documentation of this file.
1 // MIT License
2 //
3 // Copyright (c) 2019 Oleksandr Tkachenko
4 // Cryptography and Privacy Engineering Group (ENCRYPTO)
5 // TU Darmstadt, Germany
6 //
7 // Permission is hereby granted, free of charge, to any person obtaining a copy
8 // of this software and associated documentation files (the "Software"), to deal
9 // in the Software without restriction, including without limitation the rights
10 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 // copies of the Software, and to permit persons to whom the Software is
12 // furnished to do so, subject to the following conditions:
13 //
14 // The above copyright notice and this permission notice shall be included in all
15 // copies or substantial portions of the Software.
16 //
17 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 // SOFTWARE.
24 
25 #pragma once
26 
27 #include <random>
28 #include <vector>
29 
30 #include "utility/typedefs.h"
31 
32 namespace encrypto::motion {
33 
34 inline std::vector<std::uint8_t> RandomVector(std::size_t size_in_bytes) {
35  std::vector<std::uint8_t> buffer(size_in_bytes);
36  std::random_device random_device("/dev/urandom"); // use real randomness to create seeds
37  for (auto i = 0u; i < buffer.size();) {
38  try {
39  // if we can write a std::uint32_t to the buffer directly
40  if (i + sizeof(std::uint32_t) <= buffer.size()) {
41  auto u32_ptr = reinterpret_cast<std::uint32_t*>(buffer.data());
42  u32_ptr[i / sizeof(std::uint32_t)] = random_device();
43  } else { // if we need less bytes than sizeof(std::uint32_t)
44  auto r = random_device();
45  auto bytes_left = buffer.size() - i;
46  assert(bytes_left < sizeof(std::uint32_t));
47  std::copy(&r, &r + bytes_left, buffer.data() + i);
48  }
49  i += sizeof(std::uint32_t);
50  } catch (std::exception& e) {
51  // could not get enough randomness from random device, try again
52  }
53  }
54  return buffer;
55 }
56 
57 } // namespace encrypto::motion
encrypto::motion::RandomVector
std::vector< UnsignedIntegralType > RandomVector(std::size_t length)
Returns a vector of length random unsigned integral values.
Definition: helpers.h:42
encrypto::motion
Definition: algorithm_description.cpp:35
typedefs.h