Generate strong Passwords or Codes in C#

Posted by Andrea on 2010-10-19 08:08

Two methods that I wrote a few years ago while learning C# (so please don't be mad at me!).
They work just fine when you find yourself playing "quick & dirty"...

public object GetPassword()
{
    string password = string.Empty;
    int i = 0;
    Random rnd = new Random();

    while (!CheckPassword(password)) {
        password = string.Empty;
        for (i = 1; i <= 8; i++)
            switch (rnd.Next(1, 4))
            {
                case 1:
                    password += Convert.ToChar(rnd.Next(35, 43));
                    break;
                case 2:
                    password += Convert.ToChar(rnd.Next(65, 90));
                    break;
                case 3:
                    password += Convert.ToChar(rnd.Next(97, 122));
                    break;
                case 4:
                    password += Convert.ToChar(rnd.Next(48, 57)); 
                    break;
            }
    }
    
    return password.Replace("'", string.Empty);
}

This performs a basilar check against complexity:

public bool CheckPassword(string password)
{
	int i = 0;
	string c = string.Empty;
	int matches = 0;

	for (i = 0; i <= password.Length - 1; i++)
		switch(Convert.ToInt32(password[i]))
		{
			case 65:
			case 48:
			case 49:
			case 50:
			case 51:
			case 52:
			case 53:
			case 54:
			case 55:
			case 56:
			case 57:
			case 33:
			case 97:
			matches = matches + 1;
			break;
		}

	return (matches > 3);
}

Please note: the CLR optimizes calls and somehow when mass generating... it may results in having the same password returned twice or even more! To avoid this behaviour I used to put a Thread.Sleep between each generation call. :(