Flask-Bcrypt is a Flask extension that provides bcrypt hashing utilities for your application.

Overview

Flask-Bcrypt

Flask-Bcrypt is a Flask extension that provides bcrypt hashing utilities for your application.

Due to the recent increased prevelance of powerful hardware, such as modern GPUs, hashes have become increasingly easy to crack. A proactive solution to this is to use a hash that was designed to be "de-optimized". Bcrypt is such a hashing facility; unlike hashing algorithms such as MD5 and SHA1, which are optimized for speed, bcrypt is intentionally structured to be slow.

For sensitive data that must be protected, such as passwords, bcrypt is an advisable choice.

Installation

Install the extension with one of the following commands:

$ easy_install flask-bcrypt

or alternatively if you have pip installed:

$ pip install flask-bcrypt

Usage

To use the extension simply import the class wrapper and pass the Flask app object back to here. Do so like this:

from flask import Flask
from flask_bcrypt import Bcrypt

app = Flask(__name__)
bcrypt = Bcrypt(app)

Two primary hashing methods are now exposed by way of the bcrypt object. Use them like so:

pw_hash = bcrypt.generate_password_hash('hunter2')
bcrypt.check_password_hash(pw_hash, 'hunter2') # returns True

Documentation

The Sphinx-compiled documentation is available here: http://packages.python.org/Flask-Bcrypt/

Comments
  • Python 3 support (another attempt) [all tests now passing!]

    Python 3 support (another attempt) [all tests now passing!]

    Hey there,

    My version of Python 3 support gets closer to passing all tests with one problem remaining; the test_check_hash_unicode_is_utf8 test fails on Python 3.3. Unfortunately, I think it may be literally impossible to get this to work across versions.

    The reason is that '\xe2\x98\x83' is interpreted as a pure string in Python 2.x and therefore the Bcrypt hashpw function treats it as such. On Python 3.x, it is treated as unicode and likely re-encoded by the hashpw function.

    You may see the different results generated by hashpw below on both versions:

    Python 2.7:

    Python 2.7.3 (default, Apr 10 2013, 06:20:15)
    [GCC 4.6.3] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import bcrypt
    >>> bcrypt.hashpw('\xe2\x98\x83', '$2a$12$43ZhLeQrxZJx6DGLrKOj0u')
    '$2a$12$43ZhLeQrxZJx6DGLrKOj0uHuLMhu4KxcqM5oYNlBfuJHaIyNHX2j6'
    >>>
    

    Python 3.3:

    Python 3.3.3 (default, Dec 27 2013, 19:27:19)
    [GCC 4.6.3] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import bcrypt
    >>> bcrypt.hashpw('\xe2\x98\x83', '$2a$12$43ZhLeQrxZJx6DGLrKOj0u')
    '$2a$12$43ZhLeQrxZJx6DGLrKOj0u1r.ztyYrn8eqOtMsAyx303JZwp0FkIG'
    >>>
    

    Please let me know your thoughts and whether or not you would be willing to remove this test and accept my proposed solution :smile:

    All the best Fotis

    opened by fgimian 22
  • pw_hash needs to be encoded in check_password_hash()

    pw_hash needs to be encoded in check_password_hash()

    The password hash needs to be encoded like the password in the check_password_hash() method. As is, the 0.7.0 version raises an error when using a unicode password hash. Python 2.7

    opened by maximebf 17
  • problems when install flask-bcrypt on windows 32 bits and python3.4

    problems when install flask-bcrypt on windows 32 bits and python3.4

    Hi dear friends,

    I'm using the flask-bcrypt after I've started to use flask-cookiecutter
    it is a good lib, but now I've have problems to install it on a windows 32 bits and with python 3.4.

    the python-bcrypt seems to be out dated.

    Do you have some recommendation to install flask-bcrypt on this environment?

    The python-bcrypt doesn't have any update since 2014-07-22 ... I saw other bcrypt implementation called bcrypt .. and that seems to be updated recently .. do you have some plan to migrate the bcrypt library?

    My best regards,

    opened by xmnlab 16
  • Release 1.0.0

    Release 1.0.0

    Closes #65

    To match source code and release I suggest using automatic releases

    pls add PYPI_PASSWORD to repo's secrets and create a new release, package be automatically deployed to pypi

    I suggest updating version to 1.0.0

    opened by mahenzon 15
  • use bcrypt instead of py-bcrypt for supporting Windows + python3

    use bcrypt instead of py-bcrypt for supporting Windows + python3

    I met msvc++ 10.0 error while developing on windows with python3 because of py-bcrypt package. To solve that problem, I found bcrypt pacakge that doesn't cause error and replace py-bcrypt to bcrypt.

    opened by toughrogrammer 9
  • fail when try to authenticate

    fail when try to authenticate

    Hi, I've realized that when I create a user with bcrypt password, the check password works just for that current day ... the next day .. the password doesn't match.

    What am I doing wrong?

    Thank you.

    opened by xmnlab 8
  • update documentation

    update documentation

    There's an error in your docs: https://pythonhosted.org/Flask-Bcrypt/#usage

    This:

    import flask
    from flaskext.bcrypt import Bcrypt
    
    app = Flask(__name__)
    bcrypt = Bcrypt(app)
    

    Should be:

    import flask
    from flask.ext.bcrypt import Bcrypt
    
    app = Flask(__name__)
    bcrypt = Bcrypt(app)
    

    (missing the "dot" -> flaskext.bcrypt import Bcrypt)

    opened by mjhea0 8
  • Broken with Bcrypt 2.0.0

    Broken with Bcrypt 2.0.0

    The "check_password_hash" method throws an error: TypeError: hashpw() argument 1 must be str, not bytes

    If you comment out lines 180 to 191 in "flask_bcrypt.py" it then works. I assume this is not the best approach or I would do a pull request.

    Thanks!

    opened by sphildreth 7
  • TypeError: Unicode-objects must be encoded before hashing

    TypeError: Unicode-objects must be encoded before hashing

    password = b'super secret password' hashpw= b'$2b$12$iyUDXZ.BX0jV2xfdZI7Ame4BB1lkIrZILNPe3Nax4gUMnqWU9lAv2'

      File "/home/ser/GIT/topitup/login_bp.py", line 82, in index
        if username and bcrypt_flask.check_password_hash(pwhash, password):
      File "/usr/lib/python3.4/site-packages/flask_bcrypt.py", line 180, in check_password_hash
        return safe_str_cmp(bcrypt.hashpw(password, pw_hash), pw_hash)
      File "/usr/lib/python3.4/site-packages/bcrypt/__init__.py", line 139, in hashpw
        raise TypeError("Unicode-objects must be encoded before hashing")
    TypeError: Unicode-objects must be encoded before hashing
    

    Python 3.4.3 (default, Mar 25 2015, 17:13:50)

    opened by ser 5
  • Docs hosted online

    Docs hosted online

    Hi. Can you update the online version of docs?

    If it is sounds hard or time-consuming to you, try readthedocs.org. http://readthedocs.org/docs/read-the-docs/en/latest/getting_started.html#import-your-docs It will take you 5 minutes to start using the site, but then updating docs will be mush easier.

    opened by alekzvik 5
  • Works in Python2 but not in Python (Invalid Salt)

    Works in Python2 but not in Python (Invalid Salt)

    Hey there,

    I am getting some odd behaviour in Python3.

    My code looks like this:

    default_user = User(name="John Doe")
    default_user.set_password("password")
    assert default_user.check_password("password") is True
    assert default_user.check_password("kldsjfsakdjf") is False
    

    set_password is defined as:

        def set_password(self, password):
            self.password = bcrypt.generate_password_hash(password)
    
        def check_password(self, value):
            # Users without password can't log in
            # we prevent to hash an empty string
            if not value and not self.password:
                return False
            return bcrypt.check_password_hash(self.password, value)
    

    This code works great in Python2. When I run the same code in Python3 I get the "Invalid Salt" error.

    Investigating it looks like instead of the hash being written to my db (Postgres) I get a different string.

    For example in Python 3 when I look at User.password in the db I see:

    \x24326224313324674b644e614e5570476d347143502e6539735063704f4e392e6a2e5956714b726a537575312e354e4c4971505761464e3771423843
    

    instead of

    b'$2b$13$gKdNaNUpGm4qCP.e9sPcpON9.j.YVqKrjSuu1.5NLIqPWaFN7qB8C'
    

    which is the value before I save the user and the one I should receive when I check it.

    This looks like some kind of encoding error but I can't pinpoint what it is doing it! Any suggestions would be greatly appreciated. 😄

    opened by Cabalist 4
  • Allow overriding _handle_long_passwords

    Allow overriding _handle_long_passwords

    This introduces an optional parameter for the generate_password_hash and check_password_hash member functions. It overrides the default set by BCRYPT_HANDLE_LONG_PASSWORDS. As mentioned in #45 it might introduce a bit more complexity, but there are reasonable use cases for this, e.g.:

    • If you did not allow long passwords in the past and want to transition to allowing it afterwards in your already deployed application.
    • If you want to support long passwords but want to reduce computational cost as most users don't use 72-byte passwords.

    Both cases require the option to use both methods in the same application which was currently not possible (or at least not in a simple way as it required two instances of flask_bcrypt.Bcrypt() and manually overriding the "protected" _handle_long_passwords variable on one of those).

    opened by bliepp 0
  • Flask-Bcrypt not working with latest version of Bcrypt

    Flask-Bcrypt not working with latest version of Bcrypt

    Bcrypt just release new version 4.0.0 https://pypi.org/project/bcrypt/#history on August 24th and your module will not work with this version. I think fixed bcrypt version at 3.2.0 or below 4.0.0 will prevent an error happens like we had.

    File "/usr/local/lib/python3.6/site-packages/flask_bcrypt.py", line 193, in check_password_hash
    return safe_str_cmp(bcrypt.hashpw(password, pw_hash), pw_hash)
    File "/usr/local/lib/python3.6/site-packages/bcrypt/__init__.py", line 84, in hashpw
    return _bcrypt.hashpass(password, salt)
    TypeError: argument 'salt': 'bytearray' object cannot be converted to 'PyBytes'
    opened by vinhliem 1
  • Inconsistency between readthedocs and Github Readme

    Inconsistency between readthedocs and Github Readme

    Hi,

    there is a small inconsistency between the README in this repo and the documentation on readthedocs.io. The compiled version for 1.0.1 includes the following section under "Usage", which is not found here:

    In Python 3, you need to use decode(‘utf-8’) on generate_password_hash(), like below: pw_hash = bcrypt.generate_password_hash(‘hunter2’).decode(‘utf-8’)

    opened by mohoyer 0
  • Python 3.10 support

    Python 3.10 support

    The latest versions of flask-bcrypt don't support python 3.10, though many of the flask extensions we use have. This causes a problem since the 0.7.1 release of flask-bcrypt isn't updated for the latest version of werkzeug, which causes the following import error on python 3.10 environments

    File "..env/lib/python3.9/site-packages/flask_bcrypt.py", line 21, in <module>
        from werkzeug.security import safe_str_cmp
    ImportError: cannot import name 'safe_str_cmp' from 'werkzeug.security'
    
    opened by JWKennington 2
  • ImportError: No module named bcrypt._bcrypt In GAE

    ImportError: No module named bcrypt._bcrypt In GAE

    bcrypt is required to use Flask-Bcrypt ERROR 2016-11-10 09:07:35,749 wsgi.py:263] Traceback (most recent call last): File "/home/emu/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 240, in Handle handler = _config_handle.add_wsgi_middleware(self._LoadHandler()) File "/home/emu/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler handler, path, err = LoadObject(self._handler) File "/home/emu/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 85, in LoadObject obj = import(path[0]) File "/home/emu/GCP/gcp-bcrypt/main.py", line 5, in from flask.ext.bcrypt import Bcrypt File "/home/emu/GCP/gcp-bcrypt/lib/flask/exthook.py", line 81, in load_module reraise(exc_type, exc_value, tb.tb_next) File "/home/emu/GCP/gcp-bcrypt/lib/flask_bcrypt.py", line 27, in raise e ImportError: No module named bcrypt._bcrypt

    I've create a Google App Engine project. And add Flask-Bcrypt in my requirements.txt file. Then install the dependencies in my project lib folder. When I run the project this gives me above error. But my Flask module which is also a 3rd party library works fine. What's the solution? I'm using Python 2.7

    opened by imtiaz-emu 4
Owner
Max Countryman
Distributed systems, functional programming, cloud computing.
Max Countryman
flask extension for integration with the awesome pydantic package

flask extension for integration with the awesome pydantic package

null 249 Jan 6, 2023
Adds GraphQL support to your Flask application.

Flask-GraphQL Adds GraphQL support to your Flask application. Usage Just use the GraphQLView view from flask_graphql from flask import Flask from flas

GraphQL Python 1.3k Dec 31, 2022
Opinionated set of utilities on top of FastAPI

FastAPI Contrib Opinionated set of utilities on top of FastAPI Free software: MIT license Documentation: https://fastapi-contrib.readthedocs.io. Featu

identix.one 543 Jan 5, 2023
Reusable utilities for FastAPI

Reusable utilities for FastAPI Documentation: https://fastapi-utils.davidmontague.xyz Source Code: https://github.com/dmontagu/fastapi-utils FastAPI i

David Montague 1.3k Jan 4, 2023
Opinionated set of utilities on top of FastAPI

FastAPI Contrib Opinionated set of utilities on top of FastAPI Free software: MIT license Documentation: https://fastapi-contrib.readthedocs.io. Featu

identix.one 281 Feb 15, 2021
Reusable utilities for FastAPI

Reusable utilities for FastAPI Documentation: https://fastapi-utils.davidmontague.xyz Source Code: https://github.com/dmontagu/fastapi-utils FastAPI i

David Montague 543 Feb 17, 2021
fastapi-mqtt is extension for MQTT protocol

fastapi-mqtt MQTT is a lightweight publish/subscribe messaging protocol designed for M2M (machine to machine) telemetry in low bandwidth environments.

Sabuhi 144 Dec 28, 2022
fastapi-mqtt is extension for MQTT protocol

fastapi-mqtt MQTT is a lightweight publish/subscribe messaging protocol designed for M2M (machine to machine) telemetry in low bandwidth environments.

Sabuhi 23 Feb 11, 2021
FastAPI native extension, easy and simple JWT auth

fastapi-jwt FastAPI native extension, easy and simple JWT auth

Konstantin Chernyshev 19 Dec 12, 2022
An extension library for FastAPI framework

FastLab An extension library for FastAPI framework Features Logging Models Utils Routers Installation use pip to install the package: pip install fast

Tezign Lab 10 Jul 11, 2022
FastAPI Server Session is a dependency-based extension for FastAPI that adds support for server-sided session management

FastAPI Server-sided Session FastAPI Server Session is a dependency-based extension for FastAPI that adds support for server-sided session management.

DevGuyAhnaf 5 Dec 23, 2022
Flask-vs-FastAPI - Understanding Flask vs FastAPI Web Framework. A comparison of two different RestAPI frameworks.

Flask-vs-FastAPI Understanding Flask vs FastAPI Web Framework. A comparison of two different RestAPI frameworks. IntroductionIn Flask is a popular mic

Mithlesh Navlakhe 1 Jan 1, 2022
A basic JSON-RPC implementation for your Flask-powered sites

Flask JSON-RPC A basic JSON-RPC implementation for your Flask-powered sites. Some reasons you might want to use: Simple, powerful, flexible and python

Cenobit Technologies 273 Dec 1, 2022
Run your jupyter notebooks as a REST API endpoint. This isn't a jupyter server but rather just a way to run your notebooks as a REST API Endpoint.

Jupter Notebook REST API Run your jupyter notebooks as a REST API endpoint. This isn't a jupyter server but rather just a way to run your notebooks as

Invictify 54 Nov 4, 2022
FastAPI application and service structure for a more maintainable codebase

Abstracting FastAPI Services See this article for more information: https://camillovisini.com/article/abstracting-fastapi-services/ Poetry poetry inst

Camillo Visini 309 Jan 4, 2023
Full stack, modern web application generator. Using FastAPI, PostgreSQL as database, Docker, automatic HTTPS and more.

Full Stack FastAPI and PostgreSQL - Base Project Generator Generate a backend and frontend stack using Python, including interactive API documentation

Sebastián Ramírez 10.8k Jan 8, 2023
A FastAPI WebSocket application that makes use of ncellapp package by @hemantapkh

ncellFastAPI author: @awebisam Used FastAPI to create WS application. Ncellapp module by @hemantapkh NOTE: Not following best practices and, needs ref

Aashish Bhandari 7 Oct 1, 2021
Learn to deploy a FastAPI application into production DigitalOcean App Platform

Learn to deploy a FastAPI application into production DigitalOcean App Platform. This is a microservice for our Try Django 3.2 project. The goal is to extract any and all text from images using a technique called OCR.

Coding For Entrepreneurs 59 Nov 29, 2022
Sample project showing reliable data ingestion application using FastAPI and dramatiq

Create and deploy a reliable data ingestion service with FastAPI, SQLModel and Dramatiq This is the source code for the data ingestion service explain

François Voron 31 Nov 30, 2022