What is the best way to check the strength of a password?

后端 未结 15 1285
孤独总比滥情好
孤独总比滥情好 2020-12-02 10:41

What is the best way of ensuring that a user supplied password is a strong password in a registration or change password form?

One idea I had (in python)

<         


        
15条回答
  •  情书的邮戳
    2020-12-02 11:11

    The object-oriented approach would be a set of rules. Assign a weight to each rule and iterate through them. In psuedo-code:

    abstract class Rule {
    
        float weight;
    
        float calculateScore( string password );
    
    }
    

    Calculating the total score:

    float getPasswordStrength( string password ) {     
    
        float totalWeight = 0.0f;
        float totalScore  = 0.0f;
    
        foreach ( rule in rules ) {
    
           totalWeight += weight;
           totalScore  += rule.calculateScore( password ) * rule.weight;
    
        }
    
        return (totalScore / totalWeight) / rules.count;
    
    }
    

    An example rule algorithm, based on number of character classes present:

    float calculateScore( string password ) {
    
        float score = 0.0f;
    
        // NUMBER_CLASS is a constant char array { '0', '1', '2', ... }
        if ( password.contains( NUMBER_CLASS ) )
            score += 1.0f;
    
        if ( password.contains( UPPERCASE_CLASS ) )
            score += 1.0f;
    
        if ( password.contains( LOWERCASE_CLASS ) )
            score += 1.0f;
    
        // Sub rule as private method
        if ( containsPunctuation( password ) )
            score += 1.0f;
    
        return score / 4.0f;
    
    }
    

提交回复
热议问题