使用Alpha数值

时间:2015-08-12 06:10:37

标签: c# random

您好我有这个代码创建随机数它工作正常..返回随机数但我怀疑它可能会产生相同的数字一段时间..请任何人给我你的建议将有机会生成相同的号码????如果给我一个解决方案..这是我用来创建随机数的代码集

public string GetUniqueKey()
{
        int maxSize = 6;
        char[] chars = new char[62];
        chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
        byte[] data = new byte[1];
        using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider())
        {
            crypto.GetNonZeroBytes(data);
            data = new byte[maxSize];
            crypto.GetNonZeroBytes(data);
        }
        StringBuilder result = new StringBuilder(maxSize);
        foreach (byte b in data)
        {
            result.Append(chars[b % (chars.Length)]);
        }
        return result.ToString();
}

1 个答案:

答案 0 :(得分:1)

这个例子完全错了。正如在原始答案的评论中所写,该示例是有偏见的...加上它创建无用的数组只是为了立即覆盖它们......并且调用随机数方法两次。一个更好的例子应该是:

public static string GetUniqueKey(int size = 6, string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890")
{
    using (var crypto = new RNGCryptoServiceProvider())
    {
        var data = new byte[size];

        // If chars.Length isn't a power of 2 then there is a bias if
        // we simply use the modulus operator. The first characters of
        // chars will be more probable than the last ones.

        // buffer used if we encounter an unusable random byte. We will
        // regenerate it in this buffer
        byte[] smallBuffer = null;

        // Maximum random number that can be used without introducing a
        // bias
        int maxRandom = byte.MaxValue - ((byte.MaxValue + 1) % chars.Length);

        crypto.GetBytes(data);

        var result = new char[size];

        for (int i = 0; i < size; i++)
        {
            byte v = data[i];

            while (v > maxRandom)
            {
                if (smallBuffer == null)
                {
                    smallBuffer = new byte[1];
                }

                crypto.GetBytes(smallBuffer);
                v = smallBuffer[0];
            }

            result[i] = chars[v % chars.Length];
        }

        return new string(result);
    }
}

有一些反偏见代码。

现在,对于你的问题......显然有可能产生两次相同的密钥...如果你有62个可能的符号和6的大小,可能的密钥数是62 ^ 6 = 56800235584。生日悖论,如果你产生大约238328,那么你应该有50%的几率生成一个密钥两次。