Click here to Skip to main content
15,946,342 members
Articles / Programming Languages / C#
Tip/Trick

Secure Random Number Generator

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
17 Jul 2024CPOL 3.6K   4  
A quick and simple Secure Random Number Generator.
A simple way to implement a random number generator using System.Security.Cryptography.

Introduction

Today we will be discussing using the

C#
System.Security.Cryptograpghy

namespace to build a random number generator.

 

Background

v1. No additional background.

Using the code

 

C#
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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
I do not claim to be wrong! I just rarely ever write.

Comments and Discussions

 
-- There are no messages in this forum --