C# code snippet: test whether a password is strong or weak
Posted: (EET/GMT+2)
Here's a quick C# code sample for today. Use this simple method to test whether a password string is strong enough for a password. This routine used the .NET RegEx class.
Here's the code:
using System.Text.RegularExpressions;
...
/// <summary>
/// A function to test whether the given password string is strong enough.
/// The password is considered strong if it contains at least one uppercase
/// letter A..Z, one lowercase letter a..z, one number 0..9 and one special
/// character from the set "! # & % / =", and is at least 8 characters long.
/// </summary>
/// <param name="password">The password to be tested</param>
/// <returns>True if the password matches the strong password criteria, false otherwise.</returns>
private bool PasswordIsStrongEnough(string password)
{
const string regEx = "^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!#&%/=]).{8,}$";
bool isMatch = Regex.IsMatch(password, regEx);
return isMatch;
}
I'm using XML comments to document this routine, as it's likely to be used as a utility/toolbox routine in your code. To use the code, you could simply say something like:
string password = textBox1.Text;
if (PasswordIsStrongEnough(password))
{
MessageBox.Show("Password is strong enough");
}
else
{
MessageBox.Show("Password is too weak!");
}
Safer hacking!