我不能居功,因爲我偷了這個從here
using System.Text;
using System.Text.RegularExpressions;
public enum PasswordScore
{
Blank = 0,
VeryWeak = 1,
Weak = 2,
Medium = 3,
Strong = 4,
VeryStrong = 5
}
public class PasswordAdvisor
{
public static PasswordScore CheckStrength(string password)
{
int score = 0;
if (password.Length < 1)
return PasswordScore.Blank;
if (password.Length < 4)
return PasswordScore.VeryWeak;
if (password.Length >= 8)
score++;
if (password.Length >= 12)
score++;
if (Regex.Match(password, @"/\d+/", RegexOptions.ECMAScript).Success)
score++;
if (Regex.Match(password, @"/[a-z]/", RegexOptions.ECMAScript).Success &&
Regex.Match(password, @"/[A-Z]/", RegexOptions.ECMAScript).Success)
score++;
if (Regex.Match(password, @"/.[!,@,#,$,%,^,&,*,?,_,~,-,£,(,)]/", RegexOptions.ECMAScript).Success)
score++;
return (PasswordScore)score;
}
}
注意使用正則表達式的用於檢查大寫字符。 這似乎是一個體面的方法,因爲它會檢查長度,使用大寫和小寫字符,數字和特殊字符。
** **更新
我知道現在的問題是封閉的,但我可以添加更多的解釋VoidKing瞭解一些概念。
PasswordScore從CheckStrength方法返回,它可以作爲您的代碼中下一步操作的條件。
以下是如何上面的代碼可以使用一種未經試驗的演示:
String password = "MyDummy_Password"; // Substitute with the user input string
PasswordScore passwordStrengthScore = PasswordAdvisor.CheckStrength(password);
switch (passwordStrengthScore) {
case PasswordScore.Blank:
case PasswordScore.VeryWeak:
case PasswordScore.Weak:
// Show an error message to the user
break;
case PasswordScore.Medium:
case PasswordScore.Strong:
case PasswordScore.VeryStrong:
// Password deemed strong enough, allow user to be added to database etc
break;
}
枚舉在這種情況下使用作爲密碼的強度分類爲人類可讀的基團的一種手段。保持代碼清潔,並明確代碼中發生了什麼。
關於正則表達式的使用,如果您不熟悉它們的概念以及如何以及何時使用它們,我建議您做一些研究,因爲它們可以用於檢查字符串中的模式的許多不同場景。也許開始here。
這不是一個答案,但一定要明白http://xkcd.com/936/和http://xkcd.com/792/我也推薦閱讀http://www.codinghorror.com /blog/2010/12/the-dirty-truth-about-web-passwords.html並在Jeff的網站上搜索其他相關文章。然後查看正則表達式以驗證適當的長度/複雜性。 – David
您可能想要通過正則表達式運行密碼,而不是一系列'if ... then'子句。看看這個[SO回答](http://stackoverflow.com/questions/3131025/strong-password-regex)。我認爲它提供了可以幫助你的正則表達式。 –
@DarinDimitrov 嘿,謝謝你,我沒有看到這個鏈接,因爲我不知道要搜索正則表達式(儘管我猜它很明顯)。我的道歉,thnx的鏈接! – VoidKing