Code for password generator
Solution 1
I wrote a simple Data generation library ages ago to mock up some data we needed, you could take a look at that to get some ideas. You provide it with a pattern which you want to generate and it will create random data to match that pattern.
The pattern is as follows:
- * - An upper-case or lower-case letter or number.
- L - An upper-case Letter.
- l - A lower-case letter.
- V - An upper-case Vowel.
- v - A lower-case vowel.
- C - An upper-case Consonant.
- c - A lower-case consonant.
- X - Any number, 0-9.
- x - Any number, 1-9.
Its not exactly what you are looking for but you should be able to modify it to suit your needs.
This is the main logic
EDIT: Reading through your requirements again I think you should be able to alter my code to get it to work. You would need to create a pattern that matches the minimum character/number requirements for a valid password, add logic to vary the length of the generated password by adding in random characters, and perhaps add some random sort logic at the end to mix the characters up so that they are not always in the same pattern.
EDIT(2): Moved the code to GitHub, updated links.
EDIT(3): Linked to main Github repo instead.
Solution 2
you can use this method and modify according to your need
private static string CreateRandomPassword(int passwordLength)
{
string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!@$?_-";
char[] chars = new char[passwordLength];
Random rd = new Random();
for (int i = 0; i < passwordLength; i++)
{
chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
}
return new string(chars);
}
Solution 3
Have you had a look at the codeproject example?
http://www.codeproject.com/KB/cs/pwdgen.aspx
Solution 4
namespace WorkingCode.CodeProject.PwdGen
{
using System;
using System.Security.Cryptography;
using System.Text;
public class PasswordGenerator
{
public PasswordGenerator()
{
this.Minimum = DefaultMinimum;
this.Maximum = DefaultMaximum;
this.ConsecutiveCharacters = false;
this.RepeatCharacters = true;
this.ExcludeSymbols = false;
this.Exclusions = null;
rng = new RNGCryptoServiceProvider();
}
protected int GetCryptographicRandomNumber(int lBound, int uBound)
{
// Assumes lBound >= 0 && lBound < uBound
// returns an int >= lBound and < uBound
uint urndnum;
byte[] rndnum = new Byte[4];
if (lBound == uBound-1)
{
// test for degenerate case where only lBound can be returned
return lBound;
}
uint xcludeRndBase = (uint.MaxValue -
(uint.MaxValue%(uint)(uBound-lBound)));
do
{
rng.GetBytes(rndnum);
urndnum = System.BitConverter.ToUInt32(rndnum,0);
} while (urndnum >= xcludeRndBase);
return (int)(urndnum % (uBound-lBound)) + lBound;
}
protected char GetRandomCharacter()
{
int upperBound = pwdCharArray.GetUpperBound(0);
if ( true == this.ExcludeSymbols )
{
upperBound = PasswordGenerator.UBoundDigit;
}
int randomCharPosition = GetCryptographicRandomNumber(
pwdCharArray.GetLowerBound(0), upperBound);
char randomChar = pwdCharArray[randomCharPosition];
return randomChar;
}
public string Generate()
{
// Pick random length between minimum and maximum
int pwdLength = GetCryptographicRandomNumber(this.Minimum,
this.Maximum);
StringBuilder pwdBuffer = new StringBuilder();
pwdBuffer.Capacity = this.Maximum;
// Generate random characters
char lastCharacter, nextCharacter;
// Initial dummy character flag
lastCharacter = nextCharacter = '\n';
for ( int i = 0; i < pwdLength; i++ )
{
nextCharacter = GetRandomCharacter();
if ( false == this.ConsecutiveCharacters )
{
while ( lastCharacter == nextCharacter )
{
nextCharacter = GetRandomCharacter();
}
}
if ( false == this.RepeatCharacters )
{
string temp = pwdBuffer.ToString();
int duplicateIndex = temp.IndexOf(nextCharacter);
while ( -1 != duplicateIndex )
{
nextCharacter = GetRandomCharacter();
duplicateIndex = temp.IndexOf(nextCharacter);
}
}
if ( ( null != this.Exclusions ) )
{
while ( -1 != this.Exclusions.IndexOf(nextCharacter) )
{
nextCharacter = GetRandomCharacter();
}
}
pwdBuffer.Append(nextCharacter);
lastCharacter = nextCharacter;
}
if ( null != pwdBuffer )
{
return pwdBuffer.ToString();
}
else
{
return String.Empty;
}
}
public string Exclusions
{
get { return this.exclusionSet; }
set { this.exclusionSet = value; }
}
public int Minimum
{
get { return this.minSize; }
set
{
this.minSize = value;
if ( PasswordGenerator.DefaultMinimum > this.minSize )
{
this.minSize = PasswordGenerator.DefaultMinimum;
}
}
}
public int Maximum
{
get { return this.maxSize; }
set
{
this.maxSize = value;
if ( this.minSize >= this.maxSize )
{
this.maxSize = PasswordGenerator.DefaultMaximum;
}
}
}
public bool ExcludeSymbols
{
get { return this.hasSymbols; }
set { this.hasSymbols = value;}
}
public bool RepeatCharacters
{
get { return this.hasRepeating; }
set { this.hasRepeating = value;}
}
public bool ConsecutiveCharacters
{
get { return this.hasConsecutive; }
set { this.hasConsecutive = value;}
}
private const int DefaultMinimum = 6;
private const int DefaultMaximum = 10;
private const int UBoundDigit = 61;
private RNGCryptoServiceProvider rng;
private int minSize;
private int maxSize;
private bool hasRepeating;
private bool hasConsecutive;
private bool hasSymbols;
private string exclusionSet;
private char[] pwdCharArray = "abcdefghijklmnopqrstuvwxyzABCDEFG" +
"HIJKLMNOPQRSTUVWXYZ0123456789`~!@#$%^&*()-_=+[]{}\\|;:'\",<" +
".>/?".ToCharArray();
}
}
I found also
http://www.codeproject.com/KB/cs/password-generator.aspx
http://www.codesnipr.com/snippet/504/c-Random-password-generator
http://www.yetanotherchris.me/home/2009/3/15/c-pronounceable-password-generator.html
Solution 5
does this help? you could have found it with google yourself .) C# Password Generator
Related videos on Youtube
Allan Simonsen
Im a programmer with a small software company in Denmark. I have been programming for over 20 year, starting with an Amstrad.
Updated on July 09, 2022Comments
-
Allan Simonsen almost 2 years
I'm working on a C# project where I need to generate random passwords.
Can anyone provide some code or a high-level approach for password generation?
It should be possible to specify the following:
- Minimum password length
- Maximum password length
- Valid uppercase characters
- Minimum number of uppercase chars
- Valid lowercase chars
- Minimum number of lowercase chars
- Valid numeric chars
- Minimum number of numeric chars
- Valid alfanum chars.
- Minimum number of alfanum chars
-
Shiv Kumar about 13 yearsthe more you try and specify the less "random" the password will be. Ideally you just want a set of characters and use a random generator like (RNGCryptoServiceProvider) to assist in picking the random set of valid chars.
-
Allan Simonsen about 13 yearsThanks. Its simple, but it only satisfies requirement 1 and 2.
-
Allan Simonsen about 13 yearsThanks it gave me some ideas for adding more flexibility to a password generator, but it doe not fulfill requirements 3 - 10.
-
Allan Simonsen about 13 yearsThank you! It looks very promissing. I will certainly try it out.
-
aruno about 11 yearslooks great. pain downloading from google cos I had to download each file and couldn't find a zip including source.
-
SecretDeveloper about 11 years@Simon_Weaver Ill take a look and see if I can move it to github.
-
Corequatro over 10 yearsRandom is not cryptographically secure
-
gigi2 about 7 yearsthen can we just replace Random with SecureRandom there?