Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

การสร้างตัวเลขสุ่มปลอดภัย (Secure Random Numbers) ใน C#

สำหรับการสร้างตัวเลขสุ่มที่ปลอดภัยทางเข้ารหัส (Cryptographically Secure) ใน C# ควรใช้คลาส RNGCryptoServiceProvider จากเนมสเปซ System.Security.Cryptography แทนคลาส Random ธรรมดา เพราะ Random ไม่เหมาะสำหรับการใช้งานด้านความปลอดภัย

วิธีการพื้นฐาน

using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider())
{
    byte[] val = new byte[6];
    crypto.GetBytes(val);
    int randomValue = BitConverter.ToInt32(val, 1);
}

ตัวอย่างสมบูรณ์: สร้างตัวเลขทศนิยมสุ่ม 0-1

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);
        }
        
        // สร้างสตริงตัวเลข 5 หลักจากค่าสุ่ม
        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

จุดสำคัญ

  • ใช้ using เพื่อให้แน่ใจว่าทรัพยากรถูกปล่อยอย่างถูกต้อง
  • GetBytes() เติมไบต์สุ่มที่ปลอดภัยทางเข้ารหัส
  • เหมาะสำหรับการสร้างคีย์เข้ารหัส, โทเค็น, หรือข้อมูลลับอื่นๆ
  • ใน .NET Core / .NET 5+ ควรใช้ RandomNumberGenerator แทน (เป็น Abstract Class)