Calculating password entropy in python

Okay, I recently decided to make a simple python class that could calculate password entropy. After reading the wikipedia article on the subject, I came up with this solution:

class PasswordStrength:
    def __init__(self):
        import re
        self.numeric=re.compile('\d')
        self.loweralpha=re.compile('[a-z]')
        self.upperalpha=re.compile('[A-Z]')
        self.symbols=re.compile('[-_.:,;<>?"#$%&/()!@~]')
        self.num_of_symbols=20 # adjust accordingly...

    def calculate_entropy(self,password=''):
        import re
        from math import log,pow
        charset = 0
        if self.numeric.search(password):
            charset += 10
        if self.loweralpha.search(password):
            charset += 26
        if self.upperalpha.search(password):
            charset += 26
        if self.symbols.search(password):
            charset += self.num_of_symbols
        entropy = log(pow(charset,len(password)),2)
        return entropy

That's it! Remember that the entropy is measured in bits and that entropy only applies when dealing with completely random passwords!


Written by Jannich Brendle man 01 august 2011 In Programming

tags: password strengthpythonsecurity

Related posts

social