Raymond Lewallen

Sponsors

The Lounge

Advertisement

Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
Random Password Generators and sourcecode
These are probably the simplest of random password generators you can come up with in C# or VB.Net. The T-Sql is a little bit fancier, with actually two different random strings being procuded from two choices of "character arrays". Its pretty easy to see whats going on there and pick and choose which way you would want to use. I also programmatically loaded the alphanumeric characters in T-Sql rather than typing them in. Also, the T-Sql isn't in UDF format or SP format, so you will have to make a few minor changes (basically just creating an OUTPUT parameter for the @password variable) to make it work outside of Query Analyzer.
Update:Changed the C# code per Gerd's comment.

Update: Get the lastest and greatest Random Password Generator in T-Sql for Sql Server here.

C#

using System;
using System.Text;

public class PasswordGenerator
{
private char[] characterArray;
private Int32 passwordLength = 10;
Random randNum = new Random();

public PasswordGenerator()
{
characterArray = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".ToCharArray();
}

private char GetRandomCharacter()
{
return this.characterArray[(int)((this.characterArray.GetUpperBound(0) + 1) * randNum.NextDouble() )];
}

public string Generate()
{
StringBuilder sb = new StringBuilder();
sb.Capacity = passwordLength;
for (int count = 0; count <= passwordLength - 1; count++)
{
sb.Append(GetRandomCharacter());
}
if ((sb != null))
{
return sb.ToString();
}
return string.Empty;
}
}

VB.Net

Imports System
Imports System.Text

Public Class PasswordGenerator

Private characterArray() As Char Private passwordLength As Int32 = 10

Public Sub New()
characterArray = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".ToCharArray
End Sub Private Function GetRandomCharacter() As Char Randomize()
Dim location As Int32 = -1
While Not (location >= 0 AndAlso location <= Me.characterArray.GetUpperBound(0))
location = Convert.ToInt32(Me.characterArray.GetUpperBound(0) * Rnd() + 1)
End While Return Me.characterArray(location)
End Function Public Function Generate() As String Dim count As Int32
Dim sb As New StringBuilder

sb.Capacity = passwordLength

For count = 0 To passwordLength - 1
sb.Append(GetRandomCharacter())
Next count

If (Not sb Is Nothing) Then Return sb.ToString
End If Return String.Empty End Function End Class

T-Sql

declare @string varchar(10)
declare @string2 varchar(10)
declare @choices varchar(100)
declare @count int

set @choices = ''

-- load up numbers 0 - 9
set @count = 48
while @count <=57
begin
    set @choices = @choices + Cast(CHAR(@count) as char(1))
    set @count = @count + 1
end

-- load up uppercase letters A - Z
set @count = 65
while @count <=90
begin
    set @choices = @choices + Cast(CHAR(@count) as char(1))
    set @count = @count + 1
end

-- load up lowercase letters a - z
set @count = 97
while @count <=122
begin
    set @choices = @choices + Cast(CHAR(@count) as char(1))
    set @count = @count + 1
end

declare @whatever varchar(100)
set @whatever = 'JackAndJillWentUpTheHillToFetchAPailOfH20'
set @whatever = @whatever + 'PittsburghWinsTheSuperBowl'

set @count = 0
set @string = ''
set @string2 = ''

while @count <= 10
begin
    set @string = @string + SUBSTRING(@choices,CAST(ABS(CHECKSUM(NEWID()))*RAND(@count) as int)%LEN(@choices)+1,1)
    set @string2 = @string2 + SUBSTRING(@whatever,CAST(ABS(CHECKSUM(NEWID()))*RAND(@count) as int)%LEN(@whatever)+1,1)
    set @count = @count + 1
end
print @string
print @string2



Posted 01-13-2005 10:21 AM by Raymond Lewallen

[Advertisement]

Comments

Jake Good wrote re: Random Password Generators and sourcecode
on 01-13-2005 5:59 AM
I know you said simplest... so here's a tip

If you had wanted more real random generated passwords you would use the RNGCryptoServiceProvider to generate random sequences of data that is more purely random than using Random.

Just my $0.02...
Nice little post! ... since I'm not big into T-SQL, it provided me with more knowledge :)
Raymond Lewallen wrote re: Random Password Generators and sourcecode
on 01-13-2005 6:32 AM
Jake,

I actually have a password generator that uses RNGCryptoServiceProvider and is also simple. Just add the following (with some minor alterations) to your code where you GetRandomCharacter (note: i didn't go back and look this up cause I can't remember where I put it, so I'm not 100% positive this is all correct and will compile as is if you plug it in):

int intA = this.characterArray.GetUpperBound(0);
int intB = this.characterArray.GetLowerBound(0);

rcsp = new RNGCryptoServiceProvider();
byte[] randomnumbers = new Byte[4];
do
{
rcsp.GetBytes(randomnumbers);
unit uNumber = System.BitConverter.ToUInt32(randomnumbers,0);
} while (uNumber >= (uint.MaxValue - (uint.MaxValue%(uint)(intA-intB))));
return (int)(uNumber % (intA-IntB)) + intB;
Gerd Orfey wrote re: Random Password Generators and sourcecode
on 01-13-2005 1:08 PM
In order to make sure, that the whole range of characters is used for the passworts, for c#, instead of <br> <code> return this.characterArray[(int)(this.characterArray.GetUpperBound(0) * randNum.NextDouble() <b>+ 1</b>)];</code>
I would write <br>
<code>
return this.characterArray[(int)((this.characterArray.GetUpperBound(0) <br>+1</br>) * randNum.NextDouble() )];</code>
<br>

In you version the character 'a' never shows up.

Regards

Raymond Lewallen wrote re: Random Password Generators and sourcecode
on 01-13-2005 1:19 PM
Nice catch Gerd. I overlooked that in the C# code. I'll update the example above to reflect your change.
TrackBack wrote YooHoo, I'm over here now!
on 02-02-2005 6:11 AM
David Neal wrote re: Random Password Generators and sourcecode
on 02-11-2005 1:05 PM
I wrote something very similar to this a while back in C#, but the SQL code should come in handy. Very nice :)
Odhran McConnell wrote re: Random Password Generators and sourcecode
on 05-03-2007 5:19 AM

LOL @ lesbians!

Anyway, thanks for the t-sql example. Perfect for my needs.

nkkc wrote re: Random Password Generators and sourcecode
on 11-07-2007 3:47 AM

thanks! this code realy useful!

Add a Comment

(required)  
(optional)
(required)  
Remember Me?