zoukankan      html  css  js  c++  java
  • 可扩展的 “密码强度” 代码示例

    可扩展的 “密码强度” 代码示例

    场景

    在企业应用中,我们经常需要限制用户的密码强度。

    问题

    如何以可扩展的方式支持不同企业应用的密码强度要求?

    思路

      • 算法思路:密码强度 = 求和(每个规则的强度 * 权重)。
      • 可扩展思路:以聚合的形式管理各种规则,让用户可以扩展自定义规则。

    实现

    设计类图

    示例代码

    PasswordStrengthService

    复制代码
     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.Threading.Tasks;
     6 
     7 namespace PasswordStrengthStudy.Lib
     8 {
     9     public sealed class PasswordStrengthService
    10     {
    11         private readonly List<IPasswordStrengthRule> _rules = new List<IPasswordStrengthRule>();
    12 
    13         public PasswordStrengthService AddRule(IPasswordStrengthRule rule)
    14         {
    15             _rules.Add(rule);
    16 
    17             return this;
    18         }
    19 
    20         public int GetStreng(string password)
    21         {
    22             if (_rules.Count == 0)
    23             {
    24                 return 0;
    25             }
    26 
    27             return _rules.Sum(rule => rule.GetStreng(password) * rule.Weight / 100);
    28         }
    29     }
    30 }
    复制代码

    Program

    复制代码
     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.Threading.Tasks;
     6 
     7 using PasswordStrengthStudy.Lib;
     8 
     9 namespace PasswordStrengthStudy
    10 {
    11     class Program
    12     {
    13         static void Main(string[] args)
    14         {
    15             var service = new PasswordStrengthService();
    16 
    17             service.AddRule(new LengthPasswordStrengthRule(40));
    18             service.AddRule(new RegexPasswordStrengthRule(20, @".*[A-Z].*[A-Z].*"));
    19             service.AddRule(new RegexPasswordStrengthRule(20, @".*[a-z].*[a-z].*"));
    20             service.AddRule(new RegexPasswordStrengthRule(20, @".*\d.*\d.*"));
    21 
    22             Console.WriteLine(service.GetStreng("12345"));
    23             Console.WriteLine(service.GetStreng("woshishui"));
    24             Console.WriteLine(service.GetStreng("woshishuiGG"));
    25             Console.WriteLine(service.GetStreng("woshishuiGG2012"));
    26         }
    27     }
    28 }
    复制代码

    输出结果

    备注

    我目前还没有在项目中应用过密码强度,如果哪位朋友做过,请留下您的宝贵意见。

  • 相关阅读:
    IDEA @override处标红
    IntelliJ IDEA 出现" java: 程序包javax.servlet不存在、 java: 程序包javax.servlet.annotation"等错误
    IDEA中提示配置jdk1.8
    bootstrap datetimepicker 添加清空按钮
    JS中常用的Math方法
    JS数组常用方法总结
    JS字符串常用方法总结
    阻止a链接跳转方法总结
    node常见操作命令
    RAC升级后,一个节点无法连接数据库,报ORA-12537: TNS:connection closed
  • 原文地址:https://www.cnblogs.com/Leo_wl/p/3059305.html
Copyright © 2011-2022 走看看