-3

Hi I have got this code for create random number it's working fine..returning the random number but I have a doubt It may be generate the same number some time.. Please any one give me your suggestion will have chance to generate same number???? if have give me a solution..This is the code set what I have used for create the random number

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();
}
Shakir Ahamed
  • 1,290
  • 3
  • 16
  • 39
  • 1
    @M.NasserJavaid The code in this question _literally_ comes from an [answer](http://stackoverflow.com/a/1344255/5147646) on that question. This question is asking about how to increase randomness (i.e. not a duplicate imo) – Alex Booker Aug 12 '15 at 06:12
  • 1
    Please don't claim to have written code that isn't your own. By the very definition of random it may well be possible to generate the same random number (or else it wouldn't be random) – Sayse Aug 12 '15 at 06:16
  • @Petrichor sry I couldn't comment there that's why I add new question to ask this problem actually I took that code from this link "http://stackoverflow.com/questions/1344221/how-can-i-generate-random-alphanumeric-strings-in-c#" but I have doubt may have chance to generate same random number..If there have chance like that please give me a solution – Shakir Ahamed Aug 12 '15 at 07:22
  • That code is **wrong**, **wrong**, **wrong**... and *sloppy*. It is biased for `bcdef`. They are more probable than the other characters. Plus it is calling the random method twice, creating useless arrays, ... – xanatos Aug 12 '15 at 07:25

1 Answers1

1

That example is totally wrong. As written in the comments on the original answer, that example is biased... plus it creates useless arrays just to overwrite them immediately... and calls the random number method twice. A better example should be:

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

There is some anti-bias code.

Now, for your question... clearly there is the possibility of generating twice the same key... If you have 62 possible symbols and a size of 6, the number of possible keys is 62^6 = 56800235584. Using the birthday paradox, if you generate around 238328 then you should have a 50% chance of generating one key twice.

xanatos
  • 109,618
  • 12
  • 197
  • 280
  • Thanks for your reply..... so that I have Idea to check that column have exist value every time is this correct way??? – Shakir Ahamed Aug 12 '15 at 08:16
  • 1
    @user3396216 If you need it to be unique yes. Note that by making the key longer, the possibility become smaller... for example with a totally random Guid (32x 'A-Z0-5' characters) the possibility of generating twice the same Guid is astronomically little, so normally you don't check it. – xanatos Aug 12 '15 at 08:21