Navigation Bar

Tuesday, August 4, 2009

Get Ramdom Password

public enum PasswordType { Pass, Specified, Random };
private enum NameField { Separate, Union };
private const string ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private const string NUMBER = "0123456789";
private const string SYMBOL = "!\"#$%&'()-=^~\\|[{@`]}:*;+_/?.>,<";


private static string GenRandomPassword()
{
StringBuilder ret = new StringBuilder();
Random rnd = new Random();
while (true)
{
ret = new StringBuilder();
bool haveAlpha = false;
bool haveNumber = false;
bool haveSymbol = false;
for (int i = 0; i < 10; i++)
{
int t = rnd.Next(3);
if (t == 0)
{
haveAlpha = true;
ret.Append(ALPHABET[rnd.Next(ALPHABET.Length)]);
}
else if (t == 1)
{
haveNumber = true;
ret.Append(NUMBER[rnd.Next(NUMBER.Length)]);
}
else
{
haveSymbol = true;
ret.Append(SYMBOL[rnd.Next(SYMBOL.Length)]);
}
}
if (haveAlpha && haveNumber && haveSymbol) { break; }
}
return ret.ToString();
}


// To check Invalid Password
if
(specPassword.IndexOfAny(NUMBER.ToCharArray()) == -1 || specPassword.IndexOfAny(SYMBOL.ToCharArray()) == -1)
{
throw new Exception("Invalid password ( password should contain at least one number and symbol )");
}

No comments:

Post a Comment