UltrafastSecp256k1 3.50.0
Ultra high-performance secp256k1 elliptic curve cryptography library
Loading...
Searching...
No Matches
csprng.hpp
Go to the documentation of this file.
1#ifndef SECP256K1_DETAIL_CSPRNG_HPP
2#define SECP256K1_DETAIL_CSPRNG_HPP
3
4// -- OS-level cryptographic random number generation, fail-closed ------------
5// Single canonical implementation used by ecies, ellswift, bip324, musig2.
6// All callers must #include this header; do NOT define a local csprng_fill().
7
8#include <cstddef>
9#include <cstdlib>
10
11#if defined(_WIN32)
12# include <windows.h>
13# include <bcrypt.h>
14# pragma comment(lib, "bcrypt.lib")
15#elif defined(__APPLE__)
16# include <Security/SecRandom.h>
17#elif defined(__ANDROID__)
18# include <stdlib.h> // arc4random_buf (Android API 12+)
19#elif defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__)
20# include <sys/random.h>
21#else
22# include <cstdio>
23#endif
24
25namespace secp256k1::detail {
26
27inline void csprng_fill(unsigned char* buf, std::size_t len) noexcept {
28 if (len == 0) return;
29#if defined(_WIN32)
30 NTSTATUS const status = BCryptGenRandom(
31 nullptr, buf, static_cast<ULONG>(len), BCRYPT_USE_SYSTEM_PREFERRED_RNG);
32 if (status != 0) std::abort();
33#elif defined(__APPLE__)
34 if (SecRandomCopyBytes(kSecRandomDefault, len, buf) != errSecSuccess)
35 std::abort();
36#elif defined(__ANDROID__)
37 arc4random_buf(buf, len);
38#elif defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__)
39 std::size_t filled = 0;
40 while (filled < len) {
41 ssize_t const r = getrandom(buf + filled, len - filled, 0);
42 if (r <= 0) std::abort();
43 filled += static_cast<std::size_t>(r);
44 }
45#else
46 FILE* f = std::fopen("/dev/urandom", "rb");
47 if (!f) std::abort();
48 if (std::fread(buf, 1, len, f) != len) { std::fclose(f); std::abort(); }
49 std::fclose(f);
50#endif
51}
52
53} // namespace secp256k1::detail
54
55#endif // SECP256K1_DETAIL_CSPRNG_HPP
void csprng_fill(unsigned char *buf, std::size_t len) noexcept
Definition csprng.hpp:27