65.9K
CodeProject is changing. Read more.
Home

Secure Random Number Generator

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Jul 17, 2024

CPOL
viewsIcon

5080

A quick and simple Secure Random Number Generator.

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