By Felix Ker on March 29, 2008

Lately I was googling for the shortest and simplest way of generating some random passwords. So here we go. I’ll share with you what I found and how I applied them.

VB.Net

Public Function GenerateRandomPassword(ByVal length as Integer) as String
Dim strGuid as String = System.Guid.NewGuid().ToString()
strGuid= strGuid.Replace(“-”, String.Empty)
Return strGuid.Substring(0, length)
End Function

C#

public string GenerateRandomPassword(int length)
{
string strGuid = System.Guid.NewGuid().ToString();
strGuid = strGuid.Replace(“-”, string.Empty);
return guidResult.Substring(0, length);
}

Explanation (for VB.Net and C#)

For C# and VB.Net, they both utilise .Net’s System.Guid class. (Correct me if I’m wrong) NewGuid().ToString() returns a string of 32 hexadecimals (excluding the “-”).

Although its only 0-9 and A-F, I like it as it’s a very simple way to generate the password of my desired length.

Now, let’s move on to PHP. For PHP, it can be very simple too!

PHP

function createRandomPassword($length) {
return substr(md5(date(“D dS M,Y h:i:s a”)),0,$length);
}

Did you see how short things can be?

Explanation (for PHP)

Firstly, I’m generating a string from Datetime with a simple format. Next, I’ll md5 it. You can choose to sha1 it, which is the same. And finally to choose a length of password. Thats all.

Disadvantages for my way of generating (for C#, VB.Net and PHP)

  1. Only “A-F”. But it doesn’t really matter to me.
  2. Maximum length of 32. You can ofcourse re-generate, but who will need such a long password?

Generating passwords can be simple, right? What other ways can you share with me?

Category: .NET, Programming

Tagged: , , , , , , , , ,

Related entries:

  1. PHP – What did I learn?
  2. 7 Random Facts about Me
  3. Random news 29/03
  4. Siyu
  5. Something random

6 Responses to “How to generate random password (VB.Net/C#[ASP.Net]/PHP)”

  1. Adi says:

    it is very good and simple.
    Thanks man.

  2. G says:

    Thanks man – its simple and does the job..

  3. Use:

    Dim strGuid as String = System.Guid.NewGuid().ToString("N")

    Instead of:

    Dim strGuid as String = System.Guid.NewGuid().ToString()
    strGuid= strGuid.Replace(“-”, String.Empty)

  4. Terrence says:

    amazing!! short enough and excellent!

  5. Tim says:

    Thank you very much for your code – such an easy way to generate a random password and works really well.

  6. Matt says:

    Nice. Very useful. Thanks.

Leave a Reply