A simple way to implement a random number generator using System.Security.Cryptography.
Introduction
Today we will be discussing using the
System.Security.Cryptograpghy
namespace to build a random number generator.
Background
v1. No additional background.
Using the code
using System.Security.Cryptography;
public sealed class SecureRandomNumberGenerator(byte[] password, byte[] salt)
{
public int Iterations { get; set; } = 1000;
public int Pbkdf2_Size { get; set; } = password.Length + salt.Length;
public HashAlgorithmName HashAlgorithmName { get; set; } =
Environment.Is64BitOperatingSystem ?
new("SHA512") : new("SHA256");
public byte[] GetPbkdf2() => Rfc2898DeriveBytes.Pbkdf2(password, salt,
Iterations, HashAlgorithmName, Pbkdf2_Size);
public int Next()
{
using PasswordDeriveBytes deriveBytes = new(password,
GetPbkdf2(), HashAlgorithmName.Name, Iterations);
return BitConverter.ToInt32(deriveBytes.GetBytes(4), 0);
}
}
Points of Interest
?
History
v1 : 07/17/2024