How to check whether a given password is strong, medium, or weak in C#

1 Answer

0 votes
using System;

// You can set your own rules

public class PasswordStrengthChecker_CSharp
{

	public static string checkPasswordStrength(string password)
	{
		int length = password.Length;
		bool hasLower = false, hasUpper = false;
		bool hasDigit = false, specialChar = false;

		string lowuppdig = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";

		for (int i = 0; i < length; i++) {
			if (char.IsLower(password[i])) {
				hasLower = true;
			}
			if (char.IsUpper(password[i])) {
				hasUpper = true;
			}
			if (char.IsDigit(password[i])) {
				hasDigit = true;
			}
			if (lowuppdig.IndexOf(password[i]) == -1) {
				specialChar = true;
			}
		}

		if (hasLower && hasUpper && hasDigit && specialChar && length >= 10) {
			return "Strong";
		}
		else if ((hasLower || hasUpper) && specialChar && length >= 8) {
			return "Medium";
		}

		return "Weak";
	}

	public static void Main(string[] args)
	{
		string password = "aq1o@p9$XM";

		Console.WriteLine(checkPasswordStrength(password));
		Console.WriteLine(checkPasswordStrength("asW!W)(o"));
		Console.WriteLine(checkPasswordStrength("WSDFK!#Q"));
		Console.WriteLine(checkPasswordStrength("n*djskq*"));
		Console.WriteLine(checkPasswordStrength("WE3q#$"));
	}
}



/*
run:
  
Strong
Medium
Medium
Medium
Weak
  
*/


 



answered Oct 22, 2024 by avibootz
...