How to generate random password (VB.Net/C#[ASP.Net]/PHP)
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)
- Only “A-F”. But it doesn’t really matter to me.
- 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?
Post Rating:
Related entries:

No comments yet.