生成安全隨機數的 C# 程式


對於安全的隨機數,使用 RNGCryptoServiceProvider 類。它實現了一個加密隨機數生成器。

使用相同的類,我們發現了一些使用以下內容的隨機值 -

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

要生成隨機安全數,可以嘗試執行以下程式碼。

示例

 線上演示

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;
   }
}

輸出

0.13559
0.0465
0.18058
0.26494
0.52231
0.78927

更新於: 2020-06-23

2000+ 瀏覽量

開啟你的職業生涯

完成本課程獲得認證

開始學習
廣告