Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a work around bcrypt maximum password length #45

Merged
merged 2 commits into from
Feb 4, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 43 additions & 20 deletions flask_bcrypt.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
print('bcrypt is required to use Flask-Bcrypt')
raise e

import hashlib

from sys import version_info

PY3 = version_info[0] >= 3
Expand Down Expand Up @@ -121,11 +123,23 @@ class Bcrypt(object):
the configuration of the Flask app. If not set, this will default to `2b`.
(See bcrypt for more details)

By default, the bcrypt algorithm has a maximum password length of 72 bytes
and ignores any bytes beyond that. A common workaround is to hash the
given password using a cryptographic hash (such as `sha256`), take its
hexdigest to prevent NULL byte problems, and hash the result with bcrypt.
If the `BCRYPT_HANDLE_LONG_PASSWORDS` configuration value is set to `True`,
the workaround described above will be enabled.
**Warning: do not enable this option on a project that is already using
Flask-Bcrypt, or you will break password checking.**
**Warning: if this option is enabled on an existing project, disabling it
will break password checking.**

:param app: The Flask application object. Defaults to None.
'''

_log_rounds = 12
_prefix = '2b'
_handle_long_passwords = False

def __init__(self, app=None):
if app is not None:
Expand All @@ -138,6 +152,24 @@ def init_app(self, app):
'''
self._log_rounds = app.config.get('BCRYPT_LOG_ROUNDS', 12)
self._prefix = app.config.get('BCRYPT_HASH_PREFIX', '2b')
self._handle_long_passwords = app.config.get(
'BCRYPT_HANDLE_LONG_PASSWORDS', False)

def _unicode_to_bytes(self, unicode_string):
'''Converts a unicode string to a bytes object.

:param unicode_string: The unicode string to convert.'''
if PY3:
if isinstance(unicode_string, str):
bytes_object = bytes(unicode_string, 'utf-8')
else:
bytes_object = unicode_string
else:
if isinstance(unicode_string, unicode):
bytes_object = unicode_string.encode('utf-8')
else:
bytes_object = unicode_string
return bytes_object

def generate_password_hash(self, password, rounds=None, prefix=None):
'''Generates a password hash using bcrypt. Specifying `rounds`
Expand Down Expand Up @@ -165,16 +197,12 @@ def generate_password_hash(self, password, rounds=None, prefix=None):
prefix = self._prefix

# Python 3 unicode strings must be encoded as bytes before hashing.
if PY3:
if isinstance(password, str):
password = bytes(password, 'utf-8')
if isinstance(prefix, str):
prefix = bytes(prefix, 'utf-8')
else:
if isinstance(password, unicode):
password = password.encode('utf-8')
if isinstance(prefix, unicode):
prefix = prefix.encode('utf-8')
password = self._unicode_to_bytes(password)
prefix = self._unicode_to_bytes(prefix)

if self._handle_long_passwords:
password = hashlib.sha256(password).hexdigest()
password = self._unicode_to_bytes(password)

salt = bcrypt.gensalt(rounds=rounds, prefix=prefix)
return bcrypt.hashpw(password, salt)
Expand All @@ -195,16 +223,11 @@ def check_password_hash(self, pw_hash, password):
'''

# Python 3 unicode strings must be encoded as bytes before hashing.
if PY3 and isinstance(pw_hash, str):
pw_hash = bytes(pw_hash, 'utf-8')

if PY3 and isinstance(password, str):
password = bytes(password, 'utf-8')

if not PY3 and isinstance(pw_hash, unicode):
pw_hash = pw_hash.encode('utf-8')
pw_hash = self._unicode_to_bytes(pw_hash)
password = self._unicode_to_bytes(password)

if not PY3 and isinstance(password, unicode):
password = password.encode('utf-8')
if self._handle_long_passwords:
password = hashlib.sha256(password).hexdigest()
password = self._unicode_to_bytes(password)

return safe_str_cmp(bcrypt.hashpw(password, pw_hash), pw_hash)
32 changes: 32 additions & 0 deletions test_bcrypt.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ def setUp(self):
app = flask.Flask(__name__)
app.config['BCRYPT_LOG_ROUNDS'] = 6
app.config['BCRYPT_HASH_IDENT'] = '2b'
app.config['BCRYPT_HANDLE_LONG_PASSWORDS'] = False
self.bcrypt = Bcrypt(app)

def test_is_string(self):
Expand Down Expand Up @@ -55,6 +56,37 @@ def test_unicode_hash(self):
h = generate_password_hash(password).decode('utf-8')
self.assertTrue(check_password_hash(h, password))

def test_long_password(self):
"""Test bcrypt maximum password length.

The bcrypt algorithm has a maximum password length of 72 bytes, and
ignores any bytes beyond that."""

# Create a password with a 72 bytes length
password = 'A' * 72
pw_hash = self.bcrypt.generate_password_hash(password)
# Ensure that a longer password yields the same hash
self.assertTrue(self.bcrypt.check_password_hash(pw_hash, 'A' * 80))


class LongPasswordsTestCase(BasicTestCase):

def setUp(self):
app = flask.Flask(__name__)
app.config['BCRYPT_LOG_ROUNDS'] = 6
app.config['BCRYPT_HASH_IDENT'] = '2b'
app.config['BCRYPT_HANDLE_LONG_PASSWORDS'] = True
self.bcrypt = Bcrypt(app)

def test_long_password(self):
"""Test the work around bcrypt maximum password length."""

# Create a password with a 72 bytes length
password = 'A' * 72
pw_hash = self.bcrypt.generate_password_hash(password)
# Ensure that a longer password **do not** yield the same hash
self.assertFalse(self.bcrypt.check_password_hash(pw_hash, 'A' * 80))


if __name__ == '__main__':
unittest.main()