Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

random password generator

Status
Not open for further replies.

nicklieb

Programmer
Oct 17, 2002
383
GB
I found this code

Code:
    public static string CreateRandomPassword(int PasswordLength)
    {
        string _allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!@$?";
        Byte[] randomBytes = new Byte[PasswordLength];
        char[] chars = new char[PasswordLength];
        int allowedCharCount = _allowedChars.Length;

        for (int i = 0; i < PasswordLength; i++)
        {
            chars[i] = _allowedChars[(int)randomBytes[i] % allowedCharCount];
        }

        return new string(chars);
    }

but for reason it keeps returning aaaaaaa.

The bit that I don't understand is :

Code:
chars[i] = _allowedChars[(int)randomBytes[i] % allowedCharCount];

now the modulus will change on each iteration, but why is it still returning the frist letting of the string?

thanks in advance
 
I believe (int)randomBytes will always be 0.
0 mod n = 0.
Marty
 
Yes, there's nothing in that code to create random anything.

Take a look at the System.Security.Cryptography namespace. There's a class in there call RNGCryptoServiceProvider, which is a strong random-number generator. You'd use it like this:
Code:
byte[] randomBytes = new byte[100];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(randomBytes);

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top