8de67d14bcca20084892fe468dedacdc494a5e04
[mediagoblin.git] / mediagoblin / auth / lib.py
1 # GNU Mediagoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011 Free Software Foundation, Inc
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Affero General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU Affero General Public License for more details.
13 #
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 import os
18
19 import bcrypt
20
21
22 def bcrypt_check_password(raw_pass, stored_hash, extra_salt=None):
23 """
24 Check to see if this password matches.
25
26 Args:
27 - raw_pass: user submitted password to check for authenticity.
28 - stored_hash: The hash of the raw password (and possibly extra
29 salt) to check against
30 - extra_salt: (optional) If this password is with stored with a
31 non-database extra salt (probably in the config file) for extra
32 security, factor this into the check.
33
34 Returns:
35 True or False depending on success.
36 """
37 if extra_salt:
38 raw_pass = u"%s:%s" % (extra_salt, raw_pass)
39
40 hashed_pass = bcrypt.hashpw(raw_pass, stored_hash)
41
42 # Reduce risk of timing attacks by hashing again with a random
43 # number (thx to zooko on this advice, which I hopefully
44 # incorporated right.)
45 #
46 # See also:
47 rand_salt = bcrypt.gensalt(5)
48 randplus_stored_hash = bcrypt.hashpw(stored_hash, rand_salt)
49 randplus_hashed_pass = bcrypt.hashpw(hashed_pass, rand_salt)
50
51 return randplus_stored_hash == randplus_hashed_pass
52
53
54 def bcrypt_gen_password_hash(raw_pass, extra_salt=None):
55 """
56 Generate a salt for this new password.
57
58 Args:
59 - raw_pass: user submitted password
60 - extra_salt: (optional) If this password is with stored with a
61 non-database extra salt
62 """
63 if extra_salt:
64 raw_pass = u"%s:%s" % (extra_salt, raw_pass)
65
66 return unicode(bcrypt.hashpw(raw_pass, bcrypt.gensalt()))