.NET:可擴展的 “密碼強度” 代碼示例


場景

在企業應用中,我們經常需要限制用戶的密碼強度。

問題

如何以可擴展的方式支持不同企業應用的密碼強度要求?

思路

    • 算法思路:密碼強度 = 求和(每個規則的強度 * 權重)。
    • 可擴展思路:以聚合的形式管理各種規則,讓用戶可以擴展自定義規則。

實現

設計類圖

示例代碼

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 }

輸出結果

備注

我目前還沒有在項目中應用過密碼強度,如果哪位朋友做過,請留下您的寶貴意見。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM