Ticket #3604: hashlib.diff
File hashlib.diff, 2.7 KB (added by , 18 years ago) |
---|
-
django/contrib/auth/models.py
5 5 from django.utils.translation import gettext_lazy as _ 6 6 import datetime 7 7 8 def get_hexdigest(algorithm, plaintext): 9 """ 10 Returns a string of the hexdigest of the given plaintext 11 using the given algorithm. 12 """ 13 try: 14 # Python 2.5 has moved to using hashlib for hashing functions 15 import hashlib 16 if algorithm == 'md5': 17 return hashlib.md5(plaintext).hexdigest() 18 elif algorithm == 'sha1': 19 return hashlib.sha1(plaintext).hexdigest() 20 raise ValueError, "Got unknown password algorithm type in password." 21 22 except ImportError: 23 if algorithm == 'md5': 24 import md5 25 return md5.new(plaintext).hexdigest() 26 elif algorithm == 'sha1': 27 import sha 28 return sha.new(plaintext).hexdigest() 29 raise ValueError, "Got unknown password algorithm type in password." 30 8 31 def check_password(raw_password, enc_password): 9 32 """ 10 33 Returns a boolean of whether the raw_password was correct. Handles 11 34 encryption formats behind the scenes. 12 35 """ 13 36 algo, salt, hsh = enc_password.split('$') 14 if algo == 'md5': 15 import md5 16 return hsh == md5.new(salt+raw_password).hexdigest() 17 elif algo == 'sha1': 18 import sha 19 return hsh == sha.new(salt+raw_password).hexdigest() 20 raise ValueError, "Got unknown password algorithm type in password." 37 return (hsh == get_hexdigest(algo, salt+raw_password)) 21 38 22 39 class SiteProfileNotAvailable(Exception): 23 40 pass … … 138 155 return full_name.strip() 139 156 140 157 def set_password(self, raw_password): 141 import sha,random158 import random 142 159 algo = 'sha1' 143 salt = sha.new(str(random.random())).hexdigest()[:5]144 hsh = sha.new(salt+raw_password).hexdigest()160 salt = get_hexdigest(algo, str(random.random()))[:5] 161 hsh = get_hexdigest(algo, salt+raw_password) 145 162 self.password = '%s$%s$%s' % (algo, salt, hsh) 146 163 147 164 def check_password(self, raw_password): … … 152 169 # Backwards-compatibility check. Older passwords won't include the 153 170 # algorithm or salt. 154 171 if '$' not in self.password: 155 import md5 156 is_correct = (self.password == md5.new(raw_password).hexdigest()) 172 is_correct = (self.password == get_hexdigest('md5', raw_password)) 157 173 if is_correct: 158 174 # Convert the password to the new, more secure format. 159 175 self.set_password(raw_password)