可扩展的 “密码强度” 代码示例
可扩展的 “密码强度” 代码示例
场景
在企业应用中,我们经常需要限制用户的密码强度。
问题
如何以可扩展的方式支持不同企业应用的密码强度要求?
思路 算法思路:密码强度 = 求和(每个规则的强度 * 权重)。 可扩展思路:以聚合的形式管理各种规则,让用户可以扩展自定义规则。
实现
设计类图
示例代码
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 }
输出结果
备注
我目前还没有在项目中应用过密码强度,如果哪位朋友做过,请留下您的宝贵意见。
作者: Leo_wl
出处: http://www.cnblogs.com/Leo_wl/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
版权信息查看更多关于可扩展的 “密码强度” 代码示例的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did45886