Files

75 lines
1.8 KiB
C++
Raw Permalink Normal View History

#ifndef ANSCSPRNG_H
#define ANSCSPRNG_H
#pragma once
// ANSCsprng — random bytes from the operating system, for keys, salts and
// nonces.
//
// TAKEN FROM ANSMINDCORE (src/core/csprng.hpp). NOT std::random_device or a
// seeded generator: fine for an id that only needs to be distinct, and wrong
// for anything a guesser must not predict. The OS generator is the only
// source used for key material here.
//
// Windows BCryptGenRandom with the system-preferred RNG (bcrypt.lib)
// Linux getrandom(2), looping over short reads and EINTR
// macOS arc4random_buf, which cannot fail
//
// Returns false when the OS refused — callers treat that as "cannot seal",
// never as "seal with whatever was in the buffer".
#include <cstddef>
#include <cstdint>
#if defined(_WIN32)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <bcrypt.h>
#if defined(_MSC_VER)
#pragma comment(lib, "bcrypt.lib")
#endif
#elif defined(__APPLE__)
#include <stdlib.h>
#else
#include <cerrno>
#include <sys/random.h>
#endif
namespace ANSCENTER {
inline bool randomBytes(uint8_t* out, size_t n) {
if (n == 0) return true;
if (!out) return false;
#if defined(_WIN32)
while (n > 0) {
const ULONG chunk = n > 0x7fffffffu ? 0x7fffffffu : ULONG(n);
if (BCryptGenRandom(nullptr, out, chunk, BCRYPT_USE_SYSTEM_PREFERRED_RNG) != 0)
return false;
out += chunk;
n -= chunk;
}
return true;
#elif defined(__APPLE__)
arc4random_buf(out, n);
return true;
#else
while (n > 0) {
const ssize_t got = getrandom(out, n, 0);
if (got < 0) {
if (errno == EINTR) continue;
return false;
}
out += size_t(got);
n -= size_t(got);
}
return true;
#endif
}
} // namespace ANSCENTER
#endif // ANSCSPRNG_H