(转)使用 .NET 的 RNGCryptoServiceProvider 生成随机数

1. [代码]一个简单的方法,但不够可靠     跳至 [1] [2] [全屏预览]

1
2
3
4
5
6
7
8
9
10
11
static void Main(string[] args)
{
    // code from DevCurry.com
    byte[] randomBytes = new byte[4];
    Random rando = new Random();
    rando.NextBytes(randomBytes);
    foreach (byte byteValue in randomBytes)
        Console.Write("{0, 4}", byteValue);
 
    Console.ReadLine();
}

2. [代码]可靠的方法     

1
2
3
4
5
6
7
8
9
10
11
12
13
14
static void Main(string[] args)
{
    // code from DevCurry.com
    byte[] randomBytes = new byte[4];
    RNGCryptoServiceProvider rngCrypto =
    new RNGCryptoServiceProvider();
 
    rngCrypto.GetBytes(randomBytes);
    Int32 rngNum = BitConverter.ToInt32(randomBytes, 0);
 
    Console.WriteLine(rngNum);
 
    Console.ReadLine();
}
posted @ 2014-12-21 16:09  wanshutao  阅读(329)  评论(0编辑  收藏  举报