pax_global_header00006660000000000000000000000064142227371600014516gustar00rootroot0000000000000052 comment=d9064521998846a59a98f311e3bd135e1dfe082c flask-bcrypt-1.0.1/000077500000000000000000000000001422273716000141165ustar00rootroot00000000000000flask-bcrypt-1.0.1/.github/000077500000000000000000000000001422273716000154565ustar00rootroot00000000000000flask-bcrypt-1.0.1/.github/dependabot.yml000066400000000000000000000002171422273716000203060ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: pip directory: "/" schedule: interval: daily time: "13:00" open-pull-requests-limit: 10 flask-bcrypt-1.0.1/.github/workflows/000077500000000000000000000000001422273716000175135ustar00rootroot00000000000000flask-bcrypt-1.0.1/.github/workflows/publish-release.yml000066400000000000000000000011471422273716000233250ustar00rootroot00000000000000name: Publish Release on: push: tags: - "[0-9]+.[0-9]+.[0-9]+" jobs: build: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v2 - name: Setup Python uses: actions/setup-python@v2 with: python-version: "3.8" - name: Prepare Env run: | python -m pip install --upgrade pip pip install setuptools wheel - name: Build run: python setup.py sdist bdist_wheel - name: Publish uses: pypa/gh-action-pypi-publish@v1.4.1 with: user: __token__ password: ${{ secrets.PYPI_API_TOKEN }}flask-bcrypt-1.0.1/.github/workflows/tests.yml000066400000000000000000000011771422273716000214060ustar00rootroot00000000000000name: Tests on: pull_request: push: branches: - master jobs: tests: runs-on: ubuntu-latest strategy: matrix: python-version: ['3.7', '3.8', '3.9'] name: Run Tests with Python ${{ matrix.python-version }} steps: - name: Checkout uses: actions/checkout@v3 - name: Set up Python uses: actions/setup-python@v3 with: python-version: ${{ matrix.python-version }} architecture: x64 - name: Install Dependencies run: pip install flask nose - name: Unit tests run: python setup.py test flask-bcrypt-1.0.1/.gitignore000066400000000000000000000005231422273716000161060ustar00rootroot00000000000000*.py[cod] # C extensions *.so # Packages *.egg *.egg-info dist bin/* build/* eggs parts bin var sdist develop-eggs .installed.cfg lib lib64 # Installer logs pip-log.txt # Unit test / coverage reports .coverage .tox nosetests.xml # Translations *.mo # Mr Developer .mr.developer.cfg .project .pydevproject virtualenv venv .DS_Store flask-bcrypt-1.0.1/.readthedocs.yml000066400000000000000000000002371422273716000172060ustar00rootroot00000000000000version: 2 sphinx: configuration: docs/conf.py python: version: 3.8 install: - requirements: docs/requirements.txt - path: . method: pip flask-bcrypt-1.0.1/LICENSE000066400000000000000000000026601422273716000151270ustar00rootroot00000000000000Copyright (c) 2011 by Max Countryman. Some rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * The names of the contributors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.flask-bcrypt-1.0.1/MANIFEST.in000066400000000000000000000000401422273716000156460ustar00rootroot00000000000000include README.markdown LICENSE flask-bcrypt-1.0.1/README.markdown000066400000000000000000000033061422273716000166210ustar00rootroot00000000000000[![Tests](https://img.shields.io/github/workflow/status/maxcountryman/flask-bcrypt/Tests/master?label=tests)](https://github.com/maxcountryman/flask-bcrypt/actions) [![Version](https://img.shields.io/pypi/v/Flask-Bcrypt.svg)](https://pypi.python.org/pypi/Flask-Bcrypt) [![Supported Python Versions](https://img.shields.io/pypi/pyversions/Flask-Bcrypt.svg)](https://pypi.python.org/pypi/Flask-Bcrypt) # Flask-Bcrypt Flask-Bcrypt is a Flask extension that provides bcrypt hashing utilities for your application. Due to the recent increased prevalence 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: https://flask-bcrypt.readthedocs.io/ flask-bcrypt-1.0.1/docs/000077500000000000000000000000001422273716000150465ustar00rootroot00000000000000flask-bcrypt-1.0.1/docs/Makefile000066400000000000000000000110061422273716000165040ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Flask-Bcrypt.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Flask-Bcrypt.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/Flask-Bcrypt" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Flask-Bcrypt" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." make -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." flask-bcrypt-1.0.1/docs/_templates/000077500000000000000000000000001422273716000172035ustar00rootroot00000000000000flask-bcrypt-1.0.1/docs/_templates/layout.html000066400000000000000000000004731422273716000214120ustar00rootroot00000000000000{% extends '!layout.html' %} {% block document %} {{super()}} Fork me on GitHub {% endblock %} flask-bcrypt-1.0.1/docs/conf.py000066400000000000000000000167751422273716000163650ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # Flask-Bcrypt documentation build configuration file, created by # sphinx-quickstart on Wed Dec 14 21:28:26 2011. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import os import sys # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('..')) sys.path.append(os.path.join(os.path.dirname(__file__), '_themes')) module_path = os.path.join(os.path.dirname(__file__), '../flask_bcrypt.py') with open(module_path) as module: for line in module: if line.startswith('__version_info__'): package_version = '.'.join(eval(line.split('__version_info__ = ')[-1])) break # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'pallets_sphinx_themes', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Flask-Bcrypt' copyright = u'2011, Max Countryman' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = package_version # The full version, including alpha/beta/rc tags. release = package_version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # html_theme_options = {'github_fork': 'maxcountryman/flask-bcrypt', 'index_logo': False} # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'flask' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = ['_themes'] # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'Flask-Bcryptdoc' # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'Flask-Bcrypt.tex', u'Flask-Bcrypt Documentation', u'Max Countryman', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'flask-bcrypt', u'Flask-Bcrypt Documentation', [u'Max Countryman'], 1) ] flask-bcrypt-1.0.1/docs/index.rst000066400000000000000000000037641422273716000167210ustar00rootroot00000000000000Flask-Bcrypt ============= .. module:: flask_bcrypt Flask-Bcrypt is a Flask extension that provides bcrypt hashing utilities for your application. Due to the recent increased prevalence 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. .. _Flask-Bcrypt: http://github.com/maxcountryman/flask-bcrypt .. _Flask: http://flask.pocoo.org/ 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 .. note:: You need Python Development Headers to install py-bcrypt package, needed as a dependency. If you are on Mac OS or Windows, you probably have it already installed. Otherwise look for python-dev package for Debian-based distributives and for python-devel package for RedHat-based. 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. In Python 2, use them like so:: pw_hash = bcrypt.generate_password_hash('hunter2') bcrypt.check_password_hash(pw_hash, 'hunter2') # returns True 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') API ___ .. autoclass:: flask_bcrypt.Bcrypt :members: .. autofunction:: flask_bcrypt.generate_password_hash .. autofunction:: flask_bcrypt.check_password_hash flask-bcrypt-1.0.1/docs/requirements.txt000066400000000000000000000000401422273716000203240ustar00rootroot00000000000000Sphinx>=4 Pallets-Sphinx-Themes flask-bcrypt-1.0.1/flask_bcrypt.py000066400000000000000000000212301422273716000171510ustar00rootroot00000000000000''' flaskext.bcrypt --------------- A Flask extension providing bcrypt hashing and comparison facilities. :copyright: (c) 2011 by Max Countryman. :license: BSD, see LICENSE for more details. ''' from __future__ import absolute_import from __future__ import print_function __version_info__ = ('1', '0', '1') __version__ = '.'.join(__version_info__) __author__ = 'Max Countryman' __license__ = 'BSD' __copyright__ = '(c) 2011 by Max Countryman' __all__ = ['Bcrypt', 'check_password_hash', 'generate_password_hash'] import hmac try: import bcrypt except ImportError as e: print('bcrypt is required to use Flask-Bcrypt') raise e import hashlib def generate_password_hash(password, rounds=None): '''This helper function wraps the eponymous method of :class:`Bcrypt`. It is intended to be used as a helper function at the expense of the configuration variable provided when passing back the app object. In other words this shortcut does not make use of the app object at all. To use this function, simply import it from the module and use it in a similar fashion as the original method would be used. Here is a quick example:: from flask_bcrypt import generate_password_hash pw_hash = generate_password_hash('hunter2', 10) :param password: The password to be hashed. :param rounds: The optional number of rounds. ''' return Bcrypt().generate_password_hash(password, rounds) def check_password_hash(pw_hash, password): '''This helper function wraps the eponymous method of :class:`Bcrypt.` It is intended to be used as a helper function at the expense of the configuration variable provided when passing back the app object. In other words this shortcut does not make use of the app object at all. To use this function, simply import it from the module and use it in a similar fashion as the original method would be used. Here is a quick example:: from flask_bcrypt import check_password_hash check_password_hash(pw_hash, 'hunter2') # returns True :param pw_hash: The hash to be compared against. :param password: The password to compare. ''' return Bcrypt().check_password_hash(pw_hash, password) class Bcrypt(object): '''Bcrypt class container for password hashing and checking logic using bcrypt, of course. This class may be used to intialize your Flask app object. The purpose is to provide a simple interface for overriding Werkzeug's built-in password hashing utilities. Although such methods are not actually overriden, the API is intentionally made similar so that existing applications which make use of the previous hashing functions might be easily adapted to the stronger facility of bcrypt. To get started you will wrap your application's app object something like this:: app = Flask(__name__) bcrypt = Bcrypt(app) Now the two primary utility methods are exposed via this object, `bcrypt`. So in the context of the application, important data, such as passwords, could be hashed using this syntax:: password = 'hunter2' pw_hash = bcrypt.generate_password_hash(password) Once hashed, the value is irreversible. However in the case of validating logins a simple hashing of candidate password and subsequent comparison. Importantly a comparison should be done in constant time. This helps prevent timing attacks. A simple utility method is provided for this:: candidate = 'secret' bcrypt.check_password_hash(pw_hash, candidate) If both the candidate and the existing password hash are a match `check_password_hash` returns True. Otherwise, it returns False. .. admonition:: Namespacing Issues It's worth noting that if you use the format, `bcrypt = Bcrypt(app)` you are effectively overriding the bcrypt module. Though it's unlikely you would need to access the module outside of the scope of the extension be aware that it's overriden. Alternatively consider using a different name, such as `flask_bcrypt = Bcrypt(app)` to prevent naming collisions. Additionally a configuration value for `BCRYPT_LOG_ROUNDS` may be set in the configuration of the Flask app. If none is provided this will internally be assigned to 12. (This value is used in determining the complexity of the encryption, see bcrypt for more details.) You may also set the hash version using the `BCRYPT_HASH_PREFIX` field in 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: self.init_app(app) def init_app(self, app): '''Initalizes the application with the extension. :param app: The Flask application object. ''' 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 isinstance(unicode_string, str): bytes_object = bytes(unicode_string, '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` sets the log_rounds parameter of `bcrypt.gensalt()` which determines the complexity of the salt. 12 is the default value. Specifying `prefix` sets the `prefix` parameter of `bcrypt.gensalt()` which determines the version of the algorithm used to create the hash. Example usage of :class:`generate_password_hash` might look something like this:: pw_hash = bcrypt.generate_password_hash('secret', 10) :param password: The password to be hashed. :param rounds: The optional number of rounds. :param prefix: The algorithm version to use. ''' if not password: raise ValueError('Password must be non-empty.') if rounds is None: rounds = self._log_rounds if prefix is None: prefix = self._prefix # Python 3 unicode strings must be encoded as bytes before hashing. 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) def check_password_hash(self, pw_hash, password): '''Tests a password hash against a candidate password. The candidate password is first hashed and then subsequently compared in constant time to the existing hash. This will either return `True` or `False`. Example usage of :class:`check_password_hash` would look something like this:: pw_hash = bcrypt.generate_password_hash('secret', 10) bcrypt.check_password_hash(pw_hash, 'secret') # returns True :param pw_hash: The hash to be compared against. :param password: The password to compare. ''' # Python 3 unicode strings must be encoded as bytes before hashing. pw_hash = self._unicode_to_bytes(pw_hash) password = self._unicode_to_bytes(password) if self._handle_long_passwords: password = hashlib.sha256(password).hexdigest() password = self._unicode_to_bytes(password) return hmac.compare_digest(bcrypt.hashpw(password, pw_hash), pw_hash) flask-bcrypt-1.0.1/setup.py000066400000000000000000000027201422273716000156310ustar00rootroot00000000000000import os from setuptools import setup this_directory = os.path.dirname(__file__) module_path = os.path.join(this_directory, 'flask_bcrypt.py') version_line = [line for line in open(module_path) if line.startswith('__version_info__')][0] with open(os.path.join(this_directory, 'README.markdown')) as f: long_description = f.read() __version__ = '.'.join(eval(version_line.split('__version_info__ = ')[-1])) setup( name='Flask-Bcrypt', version=__version__, url='https://github.com/maxcountryman/flask-bcrypt', license='BSD', author='Max Countryman', author_email='maxc@me.com', description='Brcrypt hashing for Flask.', long_description=long_description, long_description_content_type='text/markdown', py_modules=['flask_bcrypt'], zip_safe=False, platforms='any', install_requires=['Flask', 'bcrypt>=3.1.1'], classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ], test_suite='test_bcrypt' ) flask-bcrypt-1.0.1/test_bcrypt.py000066400000000000000000000061141422273716000170340ustar00rootroot00000000000000# coding:utf-8 import unittest import flask from flask_bcrypt import (Bcrypt, check_password_hash, generate_password_hash) class BasicTestCase(unittest.TestCase): 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): pw_hash = self.bcrypt.generate_password_hash('secret') self.assertTrue(isinstance(pw_hash, bytes)) def test_custom_rounds(self): password = 'secret' pw_hash1 = self.bcrypt.generate_password_hash(password, 5) self.assertNotEqual(password, pw_hash1) def test_check_hash(self): pw_hash = self.bcrypt.generate_password_hash('secret') # check a correct password self.assertTrue(self.bcrypt.check_password_hash(pw_hash, 'secret')) # check an incorrect password self.assertFalse(self.bcrypt.check_password_hash(pw_hash, 'hunter2')) # check unicode pw_hash = self.bcrypt.generate_password_hash(u'\u2603') self.assertTrue(self.bcrypt.check_password_hash(pw_hash, u'\u2603')) # check helpers pw_hash = generate_password_hash('hunter2') self.assertTrue(check_password_hash(pw_hash, 'hunter2')) def test_check_hash_unicode_is_utf8(self): password = u'\u2603' pw_hash = self.bcrypt.generate_password_hash(password) # check a correct password self.assertTrue(self.bcrypt.check_password_hash(pw_hash, b'\xe2\x98\x83')) def test_rounds_set(self): self.assertEqual(self.bcrypt._log_rounds, 6) def test_unicode_hash(self): password = u'東京' 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()