ক্রিপ্টোগ্রাফিকভাবে সিকিউর র্যান্ডম নম্বর জেনারেট করতে RNGCryptoServiceProvider ক্লাস ব্যবহার করা হয়। এটি System.Security.Cryptography نیمস্পেসে থাকে। সাধারণ Random ক্লাস প্রিডিক্টেবল, কিন্তু এটি ক্রিপ্টোগ্রাফিক্যালি স্ট্রং র্যান্ডমনেস প্রদান করে।
উদাহরণ
using System;
using System.Security.Cryptography;
public class Demo
{
public static void Main(string[] args)
{
for (int i = 0; i <= 5; i++)
{
Console.WriteLine(RandomFunc());
}
}
private static double RandomFunc()
{
string n = "";
int randomValue;
double n2;
using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider())
{
byte[] val = new byte[6];
crypto.GetBytes(val);
randomValue = BitConverter.ToInt32(val, 1);
}
n += randomValue.ToString().Substring(1, 1)[0];
n += randomValue.ToString().Substring(2, 1)[0];
n += randomValue.ToString().Substring(3, 1)[0];
n += randomValue.ToString().Substring(4, 1)[0];
n += randomValue.ToString().Substring(5, 1)[0];
double.TryParse(n, out n2);
n2 = n2 / 100000;
return n2;
}
}
আউটপুট
0.13559 0.0465 0.18058 0.26494 0.52231 0.78927
GetBytes() মেথড বাইট অ্যারেতে র্যান্ডম বাইট পূরণ করে। BitConverter.ToInt32 দিয়ে ইন্টিজারে কনভার্ট করা হয়। নোট: আধুনিক .NET-এ RandomNumberGenerator ব্যবহার করা উচিত কারণ RNGCryptoServiceProvider অবলościত।