flask_bcrypt.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. '''
  2. flaskext.bcrypt
  3. ---------------
  4. A Flask extension providing bcrypt hasing and comparison facilities.
  5. :copyright: (c) 2011 by Max Countryman.
  6. :license: BSD, see LICENSE for more details.
  7. '''
  8. from __future__ import absolute_import
  9. from __future__ import print_function
  10. __version_info__ = ('0', '7', '1')
  11. __version__ = '.'.join(__version_info__)
  12. __author__ = 'Max Countryman'
  13. __license__ = 'BSD'
  14. __copyright__ = '(c) 2011 by Max Countryman'
  15. __all__ = ['Bcrypt', 'check_password_hash', 'generate_password_hash']
  16. from werkzeug.security import safe_str_cmp
  17. try:
  18. import bcrypt
  19. except ImportError as e:
  20. print('bcrypt is required to use Flask-Bcrypt')
  21. raise e
  22. from sys import version_info
  23. PY3 = version_info[0] >= 3
  24. def generate_password_hash(password, rounds=None):
  25. '''This helper function wraps the eponymous method of :class:`Bcrypt`. It
  26. is intended to be used as a helper function at the expense of the
  27. configuration variable provided when passing back the app object. In other
  28. words this shortcut does not make use of the app object at all.
  29. To this this function, simple import it from the module and use it in a
  30. similar fashion as the method would be used. Here is a quick example::
  31. from flask.ext.bcrypt import generate_password_hash
  32. pw_hash = generate_password_hash('hunter2', 10)
  33. :param password: The password to be hashed.
  34. :param rounds: The optional number of rounds.
  35. '''
  36. return Bcrypt().generate_password_hash(password, rounds)
  37. def check_password_hash(pw_hash, password):
  38. '''This helper function wraps the eponymous method of :class:`Bcrypt.` It
  39. is intended to be used as a helper function at the expense of the
  40. configuration variable provided when passing back the app object. In other
  41. words this shortcut does not make use of the app object at all.
  42. To this this function, simple import it from the module and use it in a
  43. similar fashion as the method would be used. Here is a quick example::
  44. from flask.ext.bcrypt import check_password_hash
  45. check_password_hash(pw_hash, 'hunter2') # returns True
  46. :param pw_hash: The hash to be compared against.
  47. :param password: The password to compare.
  48. '''
  49. return Bcrypt().check_password_hash(pw_hash, password)
  50. class Bcrypt(object):
  51. '''Bcrypt class container for password hashing and checking logic using
  52. bcrypt, of course. This class may be used to intialize your Flask app
  53. object. The purpose is to provide a simple interface for overriding
  54. Werkzeug's built-in password hashing utilities.
  55. Although such methods are not actually overriden, the API is intentionally
  56. made similar so that existing applications which make use of the previous
  57. hashing functions might be easily adapted to the stronger facility of
  58. bcrypt.
  59. To get started you will wrap your application's app object something like
  60. this::
  61. app = Flask(__name__)
  62. bcrypt = Bcrypt(app)
  63. Now the two primary utility methods are exposed via this object, `bcrypt`.
  64. So in the context of the application, important data, such as passwords,
  65. could be hashed using this syntax::
  66. password = 'hunter2'
  67. pw_hash = bcrypt.generate_password_hash(password)
  68. Once hashed, the value is irreversible. However in the case of validating
  69. logins a simple hashing of candidate password and subsequent comparison.
  70. Importantly a comparison should be done in constant time. This helps
  71. prevent timing attacks. A simple utility method is provided for this::
  72. candidate = 'secret'
  73. bcrypt.check_password_hash(pw_hash, candidate)
  74. If both the candidate and the existing password hash are a match
  75. `check_password_hash` returns True. Otherwise, it returns False.
  76. .. admonition:: Namespacing Issues
  77. It's worth noting that if you use the format, `bcrypt = Bcrypt(app)`
  78. you are effectively overriding the bcrypt module. Though it's unlikely
  79. you would need to access the module outside of the scope of the
  80. extension be aware that it's overriden.
  81. Alternatively consider using a different name, such as `flask_bcrypt
  82. = Bcrypt(app)` to prevent naming collisions.
  83. Additionally a configuration value for `BCRYPT_LOG_ROUNDS` may be set in
  84. the configuration of the Flask app. If none is provided this will
  85. internally be assigned to 12. (This value is used in determining the
  86. complexity of the encryption, see bcrypt for more details.)
  87. :param app: The Flask application object. Defaults to None.
  88. '''
  89. _log_rounds = 12
  90. def __init__(self, app=None):
  91. if app is not None:
  92. self.init_app(app)
  93. def init_app(self, app):
  94. '''Initalizes the application with the extension.
  95. :param app: The Flask application object.
  96. '''
  97. self._log_rounds = app.config.get('BCRYPT_LOG_ROUNDS', 12)
  98. def generate_password_hash(self, password, rounds=None):
  99. '''Generates a password hash using bcrypt. Specifying `rounds`
  100. sets the log_rounds parameter of `bcrypt.gensalt()` which determines
  101. the complexity of the salt. 12 is the default value.
  102. Example usage of :class:`generate_password_hash` might look something
  103. like this::
  104. pw_hash = bcrypt.generate_password_hash('secret', 10)
  105. :param password: The password to be hashed.
  106. :param rounds: The optional number of rounds.
  107. '''
  108. if not password:
  109. raise ValueError('Password must be non-empty.')
  110. if rounds is None:
  111. rounds = self._log_rounds
  112. # Python 3 unicode strings must be encoded as bytes before hashing.
  113. if PY3 and isinstance(password, str):
  114. password = bytes(password, 'utf-8')
  115. if not PY3 and isinstance(password, unicode):
  116. password = password.encode('utf-8')
  117. return bcrypt.hashpw(password, bcrypt.gensalt(rounds))
  118. def check_password_hash(self, pw_hash, password):
  119. '''Tests a password hash against a candidate password. The candidate
  120. password is first hashed and then subsequently compared in constant
  121. time to the existing hash. This will either return `True` or `False`.
  122. Example usage of :class:`check_password_hash` would look something
  123. like this::
  124. pw_hash = bcrypt.generate_password_hash('secret', 10)
  125. bcrypt.check_password_hash(pw_hash, 'secret') # returns True
  126. :param pw_hash: The hash to be compared against.
  127. :param password: The password to compare.
  128. '''
  129. # Python 3 unicode strings must be encoded as bytes before hashing.
  130. if PY3 and isinstance(pw_hash, str):
  131. pw_hash = bytes(pw_hash, 'utf-8')
  132. if PY3 and isinstance(password, str):
  133. password = bytes(password, 'utf-8')
  134. if not PY3 and isinstance(pw_hash, unicode):
  135. pw_hash = pw_hash.encode('utf-8')
  136. if not PY3 and isinstance(password, unicode):
  137. password = password.encode('utf-8')
  138. return safe_str_cmp(bcrypt.hashpw(password, pw_hash), pw_hash)