}
/* Parts of this code come from arc4random_uniform */
-unsigned int dns_random(unsigned int upper_bound) {
+uint32_t dns_random(uint32_t upper_bound) {
if (chosen_rng == RNG_UNINITIALIZED)
dns_random_setup();
throw std::runtime_error("Unreachable at " __FILE__ ":" + boost::lexical_cast<std::string>(__LINE__)); // cannot be reached
case RNG_SODIUM:
#if defined(HAVE_RANDOMBYTES_STIR) && !defined(USE_URANDOM_ONLY)
- return static_cast<unsigned int>(randombytes_uniform(static_cast<uint32_t>(upper_bound)));
+ return randombytes_uniform(upper_bound);
#else
throw std::runtime_error("Unreachable at " __FILE__ ":" + boost::lexical_cast<std::string>(__LINE__)); // cannot be reached
#endif /* RND_SODIUM */
}
case RNG_ARC4RANDOM:
#if defined(HAVE_ARC4RANDOM) && !defined(USE_URANDOM_ONLY)
- return static_cast<unsigned int>(arc4random_uniform(static_cast<uint32_t>(upper_bound)));
+ return arc4random_uniform(upper_bound);
#else
throw std::runtime_error("Unreachable at " __FILE__ ":" + boost::lexical_cast<std::string>(__LINE__)); // cannot be reached
#endif
*/
#ifndef PDNS_DNS_RANDOM
#define PDNS_DNS_RANDOM
+#include <cstdint>
void dns_random_init(const std::string& data = "", bool force_reinit = false);
-unsigned int dns_random(unsigned int n);
+uint32_t dns_random(uint32_t n);
#endif
klen = 32;
}
- char tmpkey[64];
- for (size_t i = 0; i < klen; i += 4) {
- unsigned int t = dns_random(0xffffffff);
- memcpy(tmpkey + i, &t, 4);
+ string tmpkey;
+ tmpkey.resize(klen);
+
+ for (size_t i = 0; i < klen; i += sizeof(uint32_t)) {
+ unsigned int t = dns_random(std::numeric_limits<uint32_t>::max());
+ memcpy(&tmpkey.at(i), &t, sizeof(uint32_t));
+ if (i + sizeof(uint32_t) > klen) {
+ size_t needed_bytes = klen - i;
+ for (size_t j = 0; j < needed_bytes; j++) {
+ uint8_t v = dns_random(0xff);
+ memcpy(&tmpkey.at(i + j), &v, sizeof(uint8_t));
+ }
+ }
}
- return Base64Encode(std::string(tmpkey, klen));
+ return Base64Encode(tmpkey);
}