Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# : How to generate unique passwords with the length of 7 or 8 characters

Tags:

c#

I need to repeated generate unique password many times, Ensure that every time the generated passwords are unique, Please help me.

Thanks!

like image 292
guaike Avatar asked Apr 07 '11 04:04

guaike


2 Answers

So here is another method which generates cryptedRandom password and a thread safe...

    private string CryptedRandomString()
    {
        lock (this)
        {
            int rand = 0;

            byte[] randomNumber = new byte[5];

            RNGCryptoServiceProvider Gen = new RNGCryptoServiceProvider();
            Gen.GetBytes(randomNumber);

            rand = Math.Abs(BitConverter.ToInt32(randomNumber, 0));

            return ConvertIntToStr(rand);
        }
    }

    private string ConvertIntToStr(int input)
    {
        lock (this)
        {
            string output = "";
            while (input > 0)
            {
                int current = input % 10;
                input /= 10;

                if (current == 0)
                    current = 10;

                output = (char)((char)'A' + (current - 1)) + output;
            }
            return output;
        }

    }

Now you can call this method like this: -

string GeneratedPassword = "";

GeneratedPassword = CryptedRandomString() + CryptedRandomString();

Console.WriteLine(GeneratedPassword.Substring(0,8));

Now you all must be wondering why GeneratedPassword = CryptedRandomString() + CryptedRandomString(); , the reason I called CryptedRamdomString() method twice is just to make sure it returns more then 10 digits so as it will be easier to get eight character passwords otherwise if it is called once then sometimes it will generate less then eight character password.

Well you must consider one thing before using this method that generating random numbers using "RNGCryptoServiceProvider " is bit time consuming then Random.Next. But "RNGCryptoServiceProvider " is much more secure then "Random.Next" .

like image 130
Anil Purswani Avatar answered Sep 30 '22 00:09

Anil Purswani


If you want to generate uniq password every time than

take CurrentTIME and CurrrentDATE in account because by this you can able to create new password.

have look to this resolve your problem : generating a batch of random passwords

like image 34
Pranay Rana Avatar answered Sep 29 '22 23:09

Pranay Rana