Code

Ticket #13969: better_salting.diff

File better_salting.diff, 1.5 KB (added by cyounkins, 4 years ago)
Line 
1Index: django/contrib/auth/models.py
2===================================================================
3--- django/contrib/auth/models.py       (revision 13448)
4+++ django/contrib/auth/models.py       (working copy)
5@@ -32,6 +32,28 @@
6         return sha_constructor(salt + raw_password).hexdigest()
7     raise ValueError("Got unknown password algorithm type in password.")
8 
9+def gen_salt(length=12):
10+    """
11+    Returns a random string of length characters from the set of a-z, A-Z, 0-9
12+    for use as a salt.
13+   
14+    The default length of 12 with the a-z, A-Z, 0-9 character set returns a
15+    71-bit salt. log_2((26+26+10)^12) =~ 71 bits
16+    """
17+    allowed_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
18+   
19+    import random
20+    try:
21+        random = random.SystemRandom()
22+    except NotImplementedError:
23+        import random
24+   
25+    ret = []
26+    for i in xrange(length):
27+        ret.append(random.choice(allowed_chars))
28+   
29+    return ''.join(ret)
30+
31 def check_password(raw_password, enc_password):
32     """
33     Returns a boolean of whether the raw_password was correct. Handles
34@@ -238,9 +260,8 @@
35         return full_name.strip()
36 
37     def set_password(self, raw_password):
38-        import random
39         algo = 'sha1'
40-        salt = get_hexdigest(algo, str(random.random()), str(random.random()))[:5]
41+        salt = gen_salt()
42         hsh = get_hexdigest(algo, salt, raw_password)
43         self.password = '%s$%s$%s' % (algo, salt, hsh)
44