using System.Text.RegularExpressions; public class checkpwd { /// <summary> /// 計算密碼強度 /// </summary> /// <param name="password">密碼字符串</param> /// <returns></returns> /// public class Chkrslt { public bool RSL { set; get; } public string MSG { set; get; } } public static Chkrslt PasswordStrength(string password) { if (password.Length < 8 || password.Length > 16) { return new Chkrslt() { RSL = false, MSG = "密碼長度不符合,密碼長度:8-16" }; } Regex rgx = new Regex(@"^[0-9a-zA-Z\x21-\x7e]{8,16}$"); if (!rgx.IsMatch(password)) { return new Chkrslt() { RSL = false, MSG = "密碼只能包含數字,字母和字符" }; } //字符統計 int iNum = 0, iLtt = 0, iSym = 0; foreach (char c in password) { if (c >= '0' && c <= '9') iNum++; else if (c >= 'a' && c <= 'z') iLtt++; else if (c >= 'A' && c <= 'Z') iLtt++; else iSym++; } if (iLtt == 0 && iSym == 0) return new Chkrslt() { RSL = false, MSG = "純數字密碼,請加入字符和字母" }; //純數字密碼 if (iNum == 0 && iLtt == 0) return new Chkrslt() { RSL = false, MSG = "純符號密碼,請加入數字和字母" }; //純符號密碼 if (iNum == 0 && iSym == 0) return new Chkrslt() { RSL = false, MSG = "純字母密碼,請加入字符和數字" }; //純字母密碼 if (iLtt == 0) return new Chkrslt() { RSL = false, MSG = "數字和符號構成的密碼,請加入字母" }; ; //數字和符號構成的密碼 if (iSym == 0) return new Chkrslt() { RSL = false, MSG = "數字和字母構成的密碼,請加入字符" }; ; //數字和字母構成的密碼 if (iNum == 0) return new Chkrslt() { RSL = false, MSG = "字母和符號構成的密碼,請加入數字" }; //字母和符號構成的密碼 return new Chkrslt() { RSL = true, MSG = "密碼符合" }; } }