数字只有密码强度

时间:2016-02-26 13:04:29

标签: c# .net regex security passwords

在我的组织中,用户必须仅使用数字生成密码(键盘用于访问),最小长度为8个数字。如何确保用户生成的密码不是太弱(使用服务器上的c#密码更改请求),应用以下规则:

  • 以下3个数字(甚至是密码的一部分)不是连续的或重复的(945 123 8401或543 555 784)

2 个答案:

答案 0 :(得分:1)

正则表达式为:

^((?!(?<ch>.)\k<ch>\k<ch>)(?!012|123|234|345|456|567|678|789|890)[0-9]){8,}$

(?!(?<ch>.)\k<ch>\k<ch>)将检查重复三次相同的字符。请注意,对于各种连续序列,我必须将它们放在可能序列列表中(?!012|123|234|345|456|567|678|789|890)[0-9]是将被接受为有效的字符。 {8,}是最小长度。

答案 1 :(得分:0)

如果你想要一个通用的方法,告诉你重复,升序和降序的数字:

static void checkStrength(string text, out int maxRepeats, out int maxAscending, out int maxDescending)
{ 
    maxRepeats     = 0;
    maxAscending   = 0;
    maxDescending  = 0;

    int currRepeats    = 0;
    int currAscending  = 0;
    int currDescending = 0;

    for (int i = 1; i < text.Length; ++i)
    {
        char curr = text[i];
        char prev = text[i-1];

        if (curr - prev == -1)
            maxDescending = Math.Max(maxDescending, ++currDescending);
        else
            currDescending = 1;

        if (curr - prev == 1)
            maxAscending = Math.Max(maxAscending, ++currAscending);
        else
            currAscending = 1;

        if (curr == prev)
            maxRepeats = Math.Max(maxRepeats, ++currRepeats);
        else
            currRepeats = 1;
    }
}

你必须调用它,然后用结果做你想做的事情:

int maxRepeats, maxAscending, maxDescending;
checkStrength(text, out maxRepeats, out maxAscending, out maxDescending);

if (maxRepeats > REPEAT_LIMIT || maxAscending > ASCENDING_LIMIT || maxDescending > DESCENDING_LIMIT)
{
    // ... report error or whatever
}

如果您不需要改变允许的重复或升序数字,那么xanatos的正则表达式显然是迄今为止最短的代码。只有在运行时需要改变允许的计数时才需要此代码。