Skip to content

Instantly share code, notes, and snippets.

@DreamVB
Created August 17, 2018 20:35
Show Gist options
  • Select an option

  • Save DreamVB/29d606c01d1eec13c43fd01c4245dbd3 to your computer and use it in GitHub Desktop.

Select an option

Save DreamVB/29d606c01d1eec13c43fd01c4245dbd3 to your computer and use it in GitHub Desktop.
Random password class in C#
/* Random Password Class
* This example shows how to create a list of random passwords.
* By DreamVB on 21:28 17/08/2018
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PasswordGenerator;
namespace PasswordGenerator
{
class TPassGen
{
private const string pws_Upper = "ABCDEFGHIJKLMNOPQRSTUVWXTZ";
private const string pws_Lower = "abcdefghiklmnopqrstuvwxyz";
private const string pws_Digits = "0123456789";
private const string pws_Special = "!?#$&*@%()+-=[]{}|~.,";
private bool pwsUpper = true;
private bool PwsLower = true;
private bool PwsDigits = true;
private bool PwsSymbol = false;
private int PwsLength = 8;
private Random rnd = new Random();
//Class properties.
public bool Uppercase
{
get
{
return this.pwsUpper;
}
set
{
pwsUpper = value;
}
}
public bool Lowercase
{
get
{
return this.PwsLower;
}
set
{
pwsUpper = value;
}
}
public bool Digits
{
get
{
return this.PwsDigits;
}
set
{
PwsDigits = value;
}
}
public bool Symbols
{
get
{
return this.PwsSymbol;
}
set
{
PwsSymbol = value;
}
}
public int Length
{
get
{
return this.PwsLength;
}
set
{
PwsLength = value;
}
}
public string Password
{
get
{
int x = 0;
string pwsMask = string.Empty;
string pws = string.Empty;
int r = 0;
//Check if using uppercase chars.
if (this.pwsUpper)
{
pwsMask += pws_Upper;
}
//Check if using lowercase chars.
if (this.PwsLower)
{
pwsMask += pws_Lower;
}
//Check if using digits
if (this.PwsDigits)
{
pwsMask += pws_Digits;
}
//Check if using symbols.
if (this.PwsSymbol)
{
pwsMask += pws_Special;
}
//Generate the random password.
for (x = 0; x < Length;x++ )
{
//Get random number based on pwsMask length.
r = rnd.Next() % pwsMask.Length;
//Build the random password.
pws += pwsMask[r];
}
//Return random Password.
return pws;
}
}
}
}
namespace PwsGen
{
class Program
{
static void Main(string[] args)
{
//Declare the random password class.
TPassGen Pws = new TPassGen();
//Length of password to create
Pws.Length = 8;
//Show symbols in password.
Pws.Symbols = true;
//Print out 16 random passwords.
for (int i = 1; i <= 16; i++)
{
//Write random password.
Console.WriteLine("Password[" + i.ToString() + "] " + Pws.Password);
//INC counter.
}
Console.Read();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment