1 /* 2 * Copyright 2020 Google LLC 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #ifndef FCP_SECAGG_SERVER_SSL_BIT_GEN_H_ 18 #define FCP_SECAGG_SERVER_SSL_BIT_GEN_H_ 19 20 #include <cstdint> 21 #include <limits> 22 23 namespace fcp { 24 namespace secagg { 25 26 // A secure BitGen class (analogous to absl::BitGen) for use with absl random 27 // APIs, which uses RAND_bytes as a source of randomness. This type satisfies 28 // the UniformRandomBitGenerator (URBG) concept: 29 // https://en.cppreference.com/w/cpp/named_req/UniformRandomBitGenerator 30 // 31 // For generating a large quantity of random bytes (e.g. a cryptographic key), 32 // it is more appropriate to use RAND_bytes directly. 33 // 34 // Thread safety: SslBitGen is thread safe. 35 // 36 // SslBitGen construction is free, and instances don't need to be 37 // reused. In addition, it's probably better to make it clear at the call site 38 // when a SslBitGen is being used, as opposed to a different URBG. So 39 // rather than storing the SslBitGen, if possible, prefer to create one 40 // at the time it is needed: 41 // 42 // int x = absl::Uniform(SslBitGen(), 0, 100); 43 // 44 class SslBitGen { 45 public: 46 using result_type = uint64_t; 47 48 SslBitGen() = default; 49 50 // SslBitGen cannot be copied or moved. This allows uses of it to easily be 51 // replaced with a stateful UniformRandomBitGenerator. 52 SslBitGen(const SslBitGen&) = delete; 53 SslBitGen& operator=(const SslBitGen&) = delete; 54 55 bool operator==(const SslBitGen&) const = delete; 56 bool operator!=(const SslBitGen&) const = delete; 57 58 // Returns a random number from a CSPRNG. 59 result_type operator()(); 60 min()61 static constexpr result_type min() { 62 return std::numeric_limits<result_type>::min(); 63 } max()64 static constexpr result_type max() { 65 return std::numeric_limits<result_type>::max(); 66 } 67 }; 68 69 } // namespace secagg 70 } // namespace fcp 71 72 #endif // FCP_SECAGG_SERVER_SSL_BIT_GEN_H_ 73