How can I generate random alphanumeric strings?

后端 未结 30 3286
予麋鹿
予麋鹿 2020-11-22 03:17

How can I generate a random 8 character alphanumeric string in C#?

30条回答
  •  独厮守ぢ
    2020-11-22 04:05

    The code written by Eric J. is quite sloppy (it is quite clear that it is from 6 years ago... he probably wouldn't write that code today), and there are even some problems.

    Unlike some of the alternatives presented, this one is cryptographically sound.

    Untrue... There is a bias in the password (as written in a comment), bcdefgh are a little more probable than the others (the a isn't because by the GetNonZeroBytes it isn't generating bytes with a value of zero, so the bias for the a is balanced by it), so it isn't really cryptographically sound.

    This should correct all the problems.

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

提交回复
热议问题