ورود

View Full Version : Password Generator



mjsoft
چهارشنبه 11 اسفند 1389, 10:53 صبح
/// <summary>
/// </summary>
/// <param name="length">Then length of password.</param>
/// <param name="numberOfNumeral">The minimum number of numeral.</param>
/// <param name="numberOfNonAlphanumericCharacters">The minimum number of non-alphanumeric characters.</param>
/// <returns></returns>
string GeneratePassword(int length, int numberOfNumeral, int numberOfNonAlphanumericCharacters)
{
//Make sure length and numberOfNonAlphanumericCharacters are valid....
if (((length < 1) || (length > 128)))
{
throw new ArgumentException("Membership_password_length_incorrect");
}
if (((numberOfNonAlphanumericCharacters > length) || (numberOfNonAlphanumericCharacters < 0)) | ((numberOfNumeral > length)
|| (numberOfNumeral < 0)) | numberOfNonAlphanumericCharacters + numberOfNumeral > length)
{
throw new ArgumentException("Membership_min_required_non_alphanumeric_character s_incorrect");
}
int i;
byte[] buffer1 = new byte[length];
//chPassword contains the password's characters as it's built up
char[] chPassword = new char[length];
char[] chPunctuations = "!@@$%^^*()_-+=[{]};:>|./?".ToCharArray();
char[] chNumeral = "1234567890".ToCharArray();
int nonANcount = 0;
int unmeralcount = 0;
Random rndNumber = new Random();
for (i = 0; i < numberOfNonAlphanumericCharacters; i++)
{
int passwordPos;
do
{
passwordPos = rndNumber.Next(0, length);
}
while ((int)chPassword[passwordPos] != 0);
chPassword[passwordPos] = chPunctuations[rndNumber.Next(0, chPunctuations.Length)];
}
for (i = 0; i < numberOfNumeral; i++)
{
int passwordPos;
do
{
passwordPos = rndNumber.Next(0, length);
}
while ((int)chPassword[passwordPos] != 0);
chPassword[passwordPos] = chNumeral[rndNumber.Next(0, chNumeral.Length)];
}
System.Security.Cryptography.RNGCryptoServiceProvi der rng = new System.Security.Cryptography.RNGCryptoServiceProvi der();
rng.GetBytes(buffer1);
for (i = 0; i < length; i++)
{
if ((int)chPassword[i] == 0)
{
int rndChr = (buffer1[i] % 87);
if ((rndChr < 10))
{
//numeral
chPassword[i] = Convert.ToChar(Convert.ToUInt16(48 + rndChr));
}
else
{
if ((rndChr < 36))
{
chPassword[i] = Convert.ToChar(Convert.ToUInt16((65 + rndChr) - 10));
}
else
{
if ((rndChr < 62))
{
chPassword[i] = Convert.ToChar(Convert.ToUInt16((97 + rndChr) - 36));
}
else
{
chPassword[i] = chPunctuations[rndChr - 62];
}
}
}
}
}
return new string(chPassword);
}