Computer >> Máy Tính >  >> Lập trình >> C#

Chương trình C # để tạo các số ngẫu nhiên an toàn

Đối với các số ngẫu nhiên an toàn, hãy sử dụng Lớp RNGCryptoServiceProvider. Nó triển khai một Trình tạo số ngẫu nhiên mật mã.

Sử dụng cùng một lớp, chúng tôi đã tìm thấy một số giá trị ngẫu nhiên bằng cách sử dụng như sau -

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

Để tạo các số an toàn ngẫu nhiên, bạn có thể thử chạy mã sau.

Ví dụ

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
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;
   }
}

Đầu ra

0.13559
0.0465
0.18058
0.26494
0.52231
0.78927