A buffered and thread-safe wrapper around the cryptographic random number generator for .NET and Fable. Compatible with the System.Random interface, plus additional convenience methods.
Because the cryptographic provider can be slower than the standard RNG, this library improves performance by using an internal buffer to serve multiple requests, only refilling from the cryptographic provider when necessary.
Add the NuGet package to your project:
dotnet add package Zanaptak.BufferedCryptoRandom
using Zanaptak.BufferedCryptoRandom;
var random = new BufferedCryptoRandom();
var randomValue = random.Next();
var diceRoll = random.Next(1, 7);
var coinFlip = random.NextBoolean();
Console.WriteLine($"{randomValue}, {diceRoll}, {coinFlip}");
open Zanaptak.BufferedCryptoRandom
let random = BufferedCryptoRandom()
let randomValue = random.Next()
let diceRoll = random.Next(1, 7)
let coinFlip = random.NextBoolean()
printfn $"{randomValue}, {diceRoll}, {coinFlip}"
- For .NET,
Cryptography.RandomNumberGenerator
is used. - For Fable,
window.crypto.getRandomValues
is used if available in the runtime environment. If not, then by default an exception is thrown, but thefableAllowNonCrypto
option can be used to fall back toMath.random
in that case.- When compiling a Node.js app with Fable, the
ZANAPTAK_NODEJS_CRYPTO
compilation symbol can be defined to enable use ofcrypto.randomFillSync
(e.g. for Fable 3:dotnet fable --define ZANAPTAK_NODEJS_CRYPTO
). This mechanism is used to hide the Node.js import during the default compilation to avoid interfering with web bundlers while still allowing the same codebase to work in both environments.
- When compiling a Node.js app with Fable, the
By default, the library uses exclusive locking when accessing the internal buffer for thread safety. The threadSafe
option can be set to false to disable this for additional performance at the expense of safety.
See the API documentation.
See the benchmark project.