生成安全的随机数(高斯密钥)RollDice

//http://msdn.microsoft.com/zh-cn/library/system.security.cryptography.rngcryptoserviceprovider(VS.80).aspx
    /// <summary>
    /// 生成安全的随机数(高斯密钥)RollDice
    /// </summary>
    /// <param name="num">个数</param>
    /// <returns>随机数</returns>
    public static string RandNumber(int num)
    {
        string str = "";
        // Create a byte array to hold the random value.
        byte[] randomNumber = new byte[1];

        // Create a new instance of the RNGCryptoServiceProvider.
        RNGCryptoServiceProvider Gen = new RNGCryptoServiceProvider();
        for (int x = 0; x < num; x++)
        {
            // Fill the array with a random value.
            Gen.GetBytes(randomNumber);

            // Convert the byte to an integer value to make the modulus operation easier.
            int rand = Convert.ToInt32(randomNumber[0]);

            // Return the random number mod the number
            // of sides.  The possible values are zero-
            // based, so we add one.
            str += rand % 10;
        }
        return str;
    }

posted @ 2009-11-19 11:39  94cool  阅读(211)  评论(0)    收藏  举报