UltrafastSecp256k1 3.68.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(ESP_PLATFORM)
20# include <esp_random.h>
21#elif defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__)
22# include <sys/random.h>
23#else
24# include <cstdio>
25#endif
26
27namespace secp256k1::detail {
28
29inline void csprng_fill(unsigned char* buf, std::size_t len) noexcept {
30 if (len == 0) return;
31#if defined(_WIN32)
32 NTSTATUS const status = BCryptGenRandom(
33 nullptr, buf, static_cast<ULONG>(len), BCRYPT_USE_SYSTEM_PREFERRED_RNG);
34 if (status != 0) std::abort();
35#elif defined(__APPLE__)
36 if (SecRandomCopyBytes(kSecRandomDefault, len, buf) != errSecSuccess)
37 std::abort();
38#elif defined(__ANDROID__)
39 arc4random_buf(buf, len);
40#elif defined(ESP_PLATFORM)
41 esp_fill_random(buf, len);
42#elif defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__)
43 std::size_t filled = 0;
44 while (filled < len) {
45 ssize_t const r = getrandom(buf + filled, len - filled, 0);
46 if (r <= 0) std::abort();
47 filled += static_cast<std::size_t>(r);
48 }
49#else
50 FILE* f = std::fopen("/dev/urandom", "rb");
51 if (!f) std::abort();
52 if (std::fread(buf, 1, len, f) != len) { std::fclose(f); std::abort(); }
53 std::fclose(f);
54#endif
55}
56
57} // namespace secp256k1::detail
58
59#endif // SECP256K1_DETAIL_CSPRNG_HPP
void csprng_fill(unsigned char *buf, std::size_t len) noexcept
Definition csprng.hpp:29