c#验证密码强度

 

 

 

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 = "密码符合" };
        }

    }

 

posted @ 2020-10-30 12:48  JinweiChang  阅读(1210)  评论(0编辑  收藏  举报