[Level 3] How to implement unix password encryption with sha512 in Ubuntu.
#!/usr/bin/env python import crypt import re class shadowPassword: def __init__(self, shadow_file = '/etc/shadow'): self.shadowFile = shadow_file def getPasswordField(self, user): fd = open(self.shadowFile, 'r') for line in fd.readlines(): line = line.rstrip() match = re.match('^%s:([^:]*):.*$' % user, line) if match: return match.group(1) fd.close() return '' def setPasswordField(self, user): self.password_field = self.getPasswordField(user) def getPasswordEncryptType(self, password_field=''): if self.password_field: password_field = self.password_field return password_field.split('$')[1] def getPasswordSalt(self, password_field=''): if self.password_field: password_field = self.password_field return password_field.split('$')[2] def getEncryptPassword(self, password_field=''): if self.password_field: password_field = self.password_field return password_field.split('$')[3] class unixPasswordEncryptor: def __init__(self, password, type, salt): self.password = password self.type = type self.salt = salt pass def getPasswordField(self): return '$'.join(['', self.getPasswordEncryptType(), self.getPasswordSalt(), self.getEncryptPassword()]) def getPasswordEncryptType(self): return self.type def getPasswordSalt(self): return self.salt def getEncryptPassword(self): return crypt.crypt(self.password, '$%s$%s' % (self.type, self.salt)).split('$')[3] if __name__ == '__main__': sp = shadowPassword() user = 'root' password = 'pass' sp.setPasswordField(user) print 'sp='+sp.getPasswordField(user) up = unixPasswordEncryptor(password, sp.getPasswordEncryptType(), sp.getPasswordSalt()) print 'up='+up.getPasswordField()
output:
sp=$6$.VxhMQ3h$IEjv8jCdueUBLdlz5GPKFSR9YnkYHd2lTSlA5c3ydtN4VeAjFnI0u7jkjtjAk7kPnwKME/skMkELXC35n5Acr0 up=$6$.VxhMQ3h$IEjv8jCdueUBLdlz5GPKFSR9YnkYHd2lTSlA5c3ydtN4VeAjFnI0u7jkjtjAk7kPnwKME/skMkELXC35n5Acr0Wish this helps.
regards,
Stanley Huang
Comments
Post a Comment