Strong password generator c#
Hey, Today I am going to show you how you can generate a strong passwords with special characters in c#. Here we are taking a console application to do thatStrong password generator c# |
using System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
namespace
Random_password
{
class Program
{
static string
alphaCaps = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static string
alphaLow = "abcdefghijklmnopqrstuvwxyz";
static string
numerics = "1234567890";
static string special
= "@#$-=/";
string allChars =
alphaCaps + alphaLow + numerics + special;
Random r = new Random();
public string GenerateRandomStrongPassword(int length)
{
String
generatedPassword = "";
if (length < 4)
throw new Exception("Number
of characters should be greater than 4.");
int lowerpass,
upperpass, numpass, specialchar;
string posarray = "0123456789";
if (length < posarray.Length)
posarray = posarray.Substring(0,
length);
lowerpass = getRandomPosition(ref
posarray);
upperpass = getRandomPosition(ref
posarray);
numpass = getRandomPosition(ref
posarray);
specialchar = getRandomPosition(ref
posarray);
for (int i = 0;
i < length; i++)
{
if (i ==
lowerpass)
generatedPassword +=
getRandomChar(alphaCaps);
else if (i ==
upperpass)
generatedPassword +=
getRandomChar(alphaLow);
else if (i ==
numpass)
generatedPassword += getRandomChar(numerics);
else if (i ==
specialchar)
generatedPassword +=
getRandomChar(special);
else
generatedPassword +=
getRandomChar(allChars);
}
return generatedPassword;
}
private string
getRandomChar(string fullString)
{
return
fullString.ToCharArray()[(int)Math.Floor(r.NextDouble() *
fullString.Length)].ToString();
}
private int
getRandomPosition(ref string posArray)
{
int pos;
string randomChar =
posArray.ToCharArray()[(int)Math.Floor(r.NextDouble()*
posArray.Length)].ToString();
pos = int.Parse(randomChar);
posArray =
posArray.Replace(randomChar, "");
return pos;
}
static void Main(string[]
args) //Main Method
{
Program p = new Program();
string rs =
p.GenerateRandomStrongPassword(8);
Console.WriteLine(rs);
}
}
}
Post a Comment