pax_global_header00006660000000000000000000000064141127270100014505gustar00rootroot0000000000000052 comment=567fc08fa6c82ce1dff0b2e9927ee7c013e87444 argon2-cffi-21.1.0/000077500000000000000000000000001411272701000136635ustar00rootroot00000000000000argon2-cffi-21.1.0/.github/000077500000000000000000000000001411272701000152235ustar00rootroot00000000000000argon2-cffi-21.1.0/.github/CODE_OF_CONDUCT.rst000066400000000000000000000062621411272701000202400ustar00rootroot00000000000000Contributor Covenant Code of Conduct ==================================== Our Pledge ---------- In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. Our Standards ------------- Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting Our Responsibilities -------------------- Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. Scope ----- This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. Enforcement ----------- Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at hs@ox.cx. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. Attribution ----------- This Code of Conduct is adapted from the `Contributor Covenant `_, version 1.4, available at . argon2-cffi-21.1.0/.github/CONTRIBUTING.rst000066400000000000000000000170101411272701000176630ustar00rootroot00000000000000How To Contribute ================= First off, thank you for considering contributing to ``argon2-cffi``! It's people like *you* who make it such a great tool for everyone. This document intends to make contribution more accessible by codifying tribal knowledge and expectations. Don't be afraid to open half-finished PRs, and ask questions if something is unclear! Workflow -------- - No contribution is too small! Please submit as many fixes for typos and grammar bloopers as you can! - Try to limit each pull request to *one* change only. - Since we squash on merge, it's up to you how you handle updates to the main branch. Whether you prefer to rebase on main or merge main into your branch, do whatever is more comfortable for you. - *Always* add tests and docs for your code. This is a hard rule; patches with missing tests or documentation can't be merged. - Make sure your changes pass our CI_. You won't get any feedback until it's green unless you ask for it. - Once you've addressed review feedback, make sure to bump the pull request with a short note, so we know you're done. - Don’t break `backward compatibility`_. Code ---- - Obey `PEP 8`_ and `PEP 257`_. We use the ``"""``\ -on-separate-lines style for docstrings: .. code-block:: python def func(x): """ Do something. :param str x: A very important parameter. :rtype: str """ - If you add or change public APIs, tag the docstring using ``.. versionadded:: 16.0.0 WHAT`` or ``.. versionchanged:: 16.2.0 WHAT``. - We use isort_ to sort our imports, and we follow the Black_ code style with a line length of 79 characters. As long as you run our full tox suite before committing, or install our pre-commit_ hooks (ideally you'll do both -- see below "Local Development Environment"), you won't have to spend any time on formatting your code at all. If you don't, CI will catch it for you -- but that seems like a waste of your time! Tests ----- - Write your asserts as ``expected == actual`` to line them up nicely: .. code-block:: python x = f() assert 42 == x.some_attribute assert "foo" == x._a_private_attribute - To run the test suite, all you need is a recent tox_. It will ensure the test suite runs with all dependencies against all Python versions just as it will in our CI. If you lack some Python versions, you can can always limit the environments like ``tox -e py27,py35`` (in that case you may want to look into pyenv_, which makes it very easy to install many different Python versions in parallel). - Write `good test docstrings`_. Documentation ------------- - Use `semantic newlines`_ in reStructuredText_ files (files ending in ``.rst``): .. code-block:: rst This is a sentence. This is another sentence. - If you start a new section, add two blank lines before and one blank line after the header, except if two headers follow immediately after each other: .. code-block:: rst Last line of previous section. Header of New Top Section ------------------------- Header of New Section ^^^^^^^^^^^^^^^^^^^^^ First line of new section. - If your change is noteworthy, add an entry to the changelog_. Use `semantic newlines`_, and add a link to your pull request: .. code-block:: rst - Added ``argon2_cffi.func()`` that does foo. It's pretty cool. [`#1 `_] - ``argon2_cffi.func()`` now doesn't crash the Large Hadron Collider anymore. That was a nasty bug! [`#2 `_] Local Development Environment ----------------------------- You can (and should) run our test suite using tox_. However, you’ll probably want a more traditional environment as well. We highly recommend to develop using the latest Python 3 release because ``argon2_cffi`` tries to take advantage of modern features whenever possible. First create a `virtual environment `_. It’s out of scope for this document to list all the ways to manage virtual environments in Python, but if you don’t already have a pet way, take some time to look at tools like `pew `_, `virtualfish `_, and `virtualenvwrapper `_. Next, get an up to date checkout of the ``argon2_cffi`` repository: .. code-block:: bash $ git clone git@github.com:hynek/argon2_cffi.git or if you want to use git via ``https``: .. code-block:: bash $ git clone https://github.com/hynek/argon2_cffi.git Change into the newly created directory and **after activating your virtual environment** install an editable version of ``argon2_cffi`` along with its tests and docs requirements: - First you have to make sure, that our git submodules are up to date and the Argon2 extension is built: #. ``git submodule init`` (to initialize git submodule mechanics) #. ``git submodule update`` (to update the vendored Argon2 C library to the version ``argon2_cffi`` is currently packaging) #. ``python setup.py build`` (to build the CFFI module) One of the environments requires a system-wide installation of Argon2. On macOS, it's available in Homebrew (`brew install argon2`, but you also will have to update your `LDFLAGS` so you compiler finds it) and recent Ubuntus (zesty and later) ship it too. - Next (re-)install ``argon2_cffi`` along with its developement requirements: .. code-block:: bash $ pip install -e '.[dev]' **** **Whenever the Argon2 C code changes**: you will have to perform the steps above again except of ``git submodule init``. **** At this point, .. code-block:: bash $ python -m pytest should work and pass, as should: .. code-block:: bash $ cd docs $ make html The built documentation can then be found in ``docs/_build/html/``. To avoid committing code that violates our style guide, we strongly advise you to install pre-commit_ [#f1]_ hooks: .. code-block:: bash $ pre-commit install You can also run them anytime (as our tox does) using: .. code-block:: bash $ pre-commit run --all-files .. [#f1] pre-commit should have been installed into your virtualenv automatically when you ran ``pip install -e '.[dev]'`` above. If pre-commit is missing, it may be that you need to re-run ``pip install -e '.[dev]'``. **** Please note that this project is released with a Contributor `Code of Conduct`_. By participating in this project you agree to abide by its terms. Please report any harm to `Hynek Schlawack`_ in any way you find appropriate. Thank you for considering to contribute! .. _Hynek Schlawack: https://hynek.me/about/ .. _`PEP 8`: https://www.python.org/dev/peps/pep-0008/ .. _`PEP 257`: https://www.python.org/dev/peps/pep-0257/ .. _`good test docstrings`: https://jml.io/pages/test-docstrings.html .. _`Code of Conduct`: https://github.com/hynek/argon2-cffi/blob/main/.github/CODE_OF_CONDUCT.rst .. _changelog: https://github.com/hynek/argon2-cffi/blob/main/CHANGELOG.rst .. _`tox`: https://tox.readthedocs.io/ .. _pyenv: https://github.com/pyenv/pyenv .. _reStructuredText: https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html .. _semantic newlines: https://rhodesmill.org/brandon/2012/one-sentence-per-line/ .. _CI: https://github.com/hynek/argon2-cffi/actions?query=workflow%3ACI .. _black: https://github.com/psf/black .. _pre-commit: https://pre-commit.com/ .. _isort: https://github.com/PyCQA/isort .. _`backward compatibility`: https://argon2-cffi.readthedocs.io/en/stable/backward-compatibility.html argon2-cffi-21.1.0/.github/FUNDING.yml000066400000000000000000000001001411272701000170270ustar00rootroot00000000000000--- github: hynek ko_fi: the_hynek tidelift: "pypi/argon2_cffi" argon2-cffi-21.1.0/.github/workflows/000077500000000000000000000000001411272701000172605ustar00rootroot00000000000000argon2-cffi-21.1.0/.github/workflows/main.yml000066400000000000000000000064431411272701000207360ustar00rootroot00000000000000--- name: CI on: push: branches: ["main"] pull_request: branches: ["main"] # Allow rebuilds via API. repository_dispatch: types: rebuild jobs: tests: name: "Python ${{ matrix.python-version }}" runs-on: "ubuntu-latest" env: USING_COVERAGE: "3.5,3.6,3.7,3.8" strategy: matrix: python-version: ["3.5", "3.6", "3.7", "3.8", "3.9", "3.10.0-beta - 3.10", "pypy3"] steps: - uses: "actions/checkout@v2" with: submodules: "recursive" - uses: "actions/setup-python@v2" with: python-version: "${{ matrix.python-version }}" - name: "Install dependencies" run: | set -xe python -VV python -m site python -m pip install --upgrade pip setuptools wheel python -m pip install --upgrade coverage[toml] virtualenv tox tox-gh-actions - name: "Run tox targets for ${{ matrix.python-version }}" run: "python -m tox" - name: "Combine coverage" run: | set -xe python -m coverage combine python -m coverage xml if: "contains(env.USING_COVERAGE, matrix.python-version)" - name: "Upload coverage to Codecov" uses: "codecov/codecov-action@v1" if: "contains(env.USING_COVERAGE, matrix.python-version)" with: fail_ci_if_error: true system-package: runs-on: "ubuntu-latest" name: "Install and test with system package of Argon2." steps: - uses: "actions/checkout@v2" - uses: "actions/setup-python@v2" with: python-version: "3.9" - name: "Install dependencies" run: | set -xe sudo apt-get install libargon2-0 libargon2-0-dev # Ensure we cannot use our own Argon2 by accident. rm -rf extras python -VV python -m site python -m pip install --upgrade pip setuptools wheel python -m pip install --upgrade virtualenv tox - name: "Run tox -e system-argon2" run: "python -m tox -e system-argon2" package: name: "Build & verify package" runs-on: "ubuntu-latest" steps: - uses: "actions/checkout@v2" with: submodules: "recursive" - uses: "actions/setup-python@v2" with: python-version: "3.9" - name: "Install build, check-wheel-content, and twine" run: "python -m pip install build twine check-wheel-contents" - name: "Build package" run: "python -m build --sdist --wheel ." - name: "List result" run: "ls -l dist" - name: "Check wheel contents" run: "check-wheel-contents dist/*.whl" - name: "Check long_description" run: "python -m twine check dist/*" install-dev: strategy: matrix: os: ["ubuntu-latest", "windows-latest", "macos-latest"] name: "Verify dev env" runs-on: "${{ matrix.os }}" steps: - uses: "actions/checkout@v2" with: submodules: "recursive" - uses: "actions/setup-python@v2" with: python-version: "3.9" - name: "Install in dev mode" run: | python setup.py build python -m pip install -e .[dev] - name: "Import package" run: "python -c 'import argon2; print(argon2.__version__)'" argon2-cffi-21.1.0/.github/workflows/wheel.yml000066400000000000000000000050551411272701000211140ustar00rootroot00000000000000name: wheels on: workflow_dispatch: inputs: version: description: PyPI version (sdist already uploaded) required: true jobs: manylinux: runs-on: ubuntu-latest strategy: matrix: include: - name: cp35-cp35m image: quay.io/pypa/manylinux1_x86_64 - name: pp36-pypy36_pp73 image: pypywheels/manylinux2010-pypy_x86_64 - name: pp37-pypy37_pp73 image: pypywheels/manylinux2010-pypy_x86_64 steps: - run: | mkdir dist podman run --rm \ -v $PWD/dist:/dist:rw \ ${{ matrix.image }} \ bash -exc '\ yum install -y libffi-devel && \ /opt/python/${{ matrix.name }}/bin/pip wheel \ --no-deps --wheel-dir /tmp/wheels --no-binary :all: \ argon2-cffi==${{ github.event.inputs.version }} && \ auditwheel repair /tmp/wheels/* --wheel-dir /dist && \ find /dist -type f | xargs --verbose --replace unzip -l {} \ ' name: build wheel - uses: actions/upload-artifact@v2 with: name: wheels-manylinux-${{ matrix.name }} path: dist/*.whl macos: runs-on: macos-latest strategy: matrix: include: - name: cp35 py: "3.5" - name: pp36 py: pypy-3.6 - name: pp37 py: pypy-3.7 steps: - uses: actions/setup-python@v2 with: python-version: ${{ matrix.py }} - run: python -m pip install --upgrade pip setuptools wheel - run: 'python -m pip wheel --no-deps --wheel-dir dist --no-binary :all: argon2-cffi==${{ github.event.inputs.version }}' - uses: actions/upload-artifact@v2 with: name: wheels-macos-${{ matrix.name }} path: dist/*.whl windows: runs-on: windows-latest strategy: matrix: include: - name: cp35-x86 py: "3.5" arch: x86 - name: cp35-x64 py: "3.5" arch: x64 - name: pp36 py: pypy-3.6 arch: x86 - name: pp37 py: pypy-3.7 arch: x86 steps: - uses: actions/setup-python@v2 with: python-version: ${{ matrix.py }} architecture: ${{ matrix.arch }} - run: python -m pip install --upgrade pip setuptools wheel - run: 'python -m pip wheel --no-deps --wheel-dir dist --no-binary :all: argon2-cffi==${{ github.event.inputs.version }}' - uses: actions/upload-artifact@v2 with: name: wheels-windows-${{ matrix.name }} path: dist/*.whl argon2-cffi-21.1.0/.gitignore000066400000000000000000000002401411272701000156470ustar00rootroot00000000000000*.dylib *.egg-info *.pyc *.so .cache .coverage .coverage.* .eggs .hypothesis .pytest_cache/ .tox __pycache__ _build dist pip-wheel-metadata/ src/argon2/_ffi.py argon2-cffi-21.1.0/.gitmodules000066400000000000000000000001431411272701000160360ustar00rootroot00000000000000[submodule "libargon2"] path = extras/libargon2 url = https://github.com/p-h-c/phc-winner-argon2 argon2-cffi-21.1.0/.pre-commit-config.yaml000066400000000000000000000010111411272701000201350ustar00rootroot00000000000000--- repos: - repo: https://github.com/psf/black rev: 21.7b0 hooks: - id: black language_version: python3.8 - repo: https://github.com/PyCQA/isort rev: 5.9.3 hooks: - id: isort additional_dependencies: [toml] - repo: https://github.com/PyCQA/flake8 rev: 3.9.2 hooks: - id: flake8 - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.0.1 hooks: - id: trailing-whitespace - id: end-of-file-fixer - id: debug-statements argon2-cffi-21.1.0/.readthedocs.yml000066400000000000000000000003241411272701000167500ustar00rootroot00000000000000--- version: 2 python: # Keep version in sync with tox.ini (docs and gh-actions). version: 3.7 install: - method: pip path: . extra_requirements: - docs submodules: include: all argon2-cffi-21.1.0/AUTHORS.rst000066400000000000000000000025001411272701000155370ustar00rootroot00000000000000Credits & License ================= ``argon2-cffi`` is maintained by Hynek Schlawack and released under the `MIT license `_. The development is kindly supported by `Variomedia AG `_. A full list of contributors can be found in GitHub's `overview `_. Vendored Code ------------- Argon2 ^^^^^^ The original Argon2 repo can be found at https://github.com/P-H-C/phc-winner-argon2/. Except for the components listed below, the Argon2 code in this repository is copyright (c) 2015 Daniel Dinu, Dmitry Khovratovich (main authors), Jean-Philippe Aumasson and Samuel Neves, and under CC0_ license. The string encoding routines in src/encoding.c are copyright (c) 2015 Thomas Pornin, and under CC0_ license. The `BLAKE2 `_ code in ``src/blake2/`` is copyright (c) Samuel Neves, 2013-2015, and under CC0_ license. The authors of Argon2 also were very helpful to get the library to compile on ancient versions of Visual Studio for ancient versions of Python. The documentation also quotes frequently from the Argon2 paper_ to avoid mistakes by rephrasing. .. _CC0: https://creativecommons.org/publicdomain/zero/1.0/ .. _paper: https://www.password-hashing.net/argon2-specs.pdf argon2-cffi-21.1.0/CHANGELOG.rst000066400000000000000000000223301411272701000157040ustar00rootroot00000000000000Changelog ========= Versions are year-based with a strict backward compatibility policy. The third digit is only for regressions. 21.1.0 (2021-08-29) ------------------- Vendoring Argon2 @ `62358ba `_ (20190702) Backward-incompatible changes: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Microsoft stopped providing the necessary SDKs to ship Python 2.7 wheels and currenly the downloads amount to 0.09%. Therefore we have decided that Python 2.7 is not supported anymore. Deprecations: ^^^^^^^^^^^^^ *none* Changes: ^^^^^^^^ There are indeed no changes whatsoever to the code of *argon2-cffi*. The *Argon2* project also hasn't tagged a new release since July 2019. There also don't seem to be any important pending fixes. This release is mainly about improving the way binary wheels are built (abi3 on all platforms). ---- 20.1.0 (2020-05-11) ------------------- Vendoring Argon2 @ `62358ba `_ (20190702) Backward-incompatible changes: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ *none* Deprecations: ^^^^^^^^^^^^^ *none* Changes: ^^^^^^^^ - It is now possible to manually override the detection of SSE2 using the ``ARGON2_CFFI_USE_SSE2`` environment variable. ---- 19.2.0 (2019-10-27) ------------------- Vendoring Argon2 @ `62358ba `_ (20190702) Backward-incompatible changes: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - Python 3.4 is not supported anymore. It has been unsupported by the Python core team for a while now and its PyPI downloads are negligible. It's very unlikely that ``argon2-cffi`` will break under 3.4 anytime soon, but we don't test it and don't ship binary wheels for it anymore. Deprecations: ^^^^^^^^^^^^^ *none* Changes: ^^^^^^^^ - The dependency on ``enum34`` is now protected using a PEP 508 marker. This fixes problems when the sdist is handled by a different interpreter version than the one running it. `#48 `_ ---- 19.1.0 (2019-01-17) ------------------- Vendoring Argon2 @ `670229c `_ (20171227) Backward-incompatible changes: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ *none* Deprecations: ^^^^^^^^^^^^^ *none* Changes: ^^^^^^^^ - Added support for Argon2 v1.2 hashes in ``argon2.extract_parameters()``. ---- 18.3.0 (2018-08-19) ------------------- Vendoring Argon2 @ `670229c `_ (20171227) Backward-incompatible changes: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ *none* Deprecations: ^^^^^^^^^^^^^ *none* Changes: ^^^^^^^^ - ``argon2.PasswordHasher``'s hash type is configurable now. ---- 18.2.0 (2018-08-19) ------------------- Vendoring Argon2 @ `670229c `_ (20171227) Changes: ^^^^^^^^ - The hash type for ``argon2.PasswordHasher`` is Argon2\ **id** now. This decision has been made based on the recommendations in the latest `Argon2 RFC draft `_. `#33 `_ `#34 `_ - To make the change of hash type backward compatible, ``argon2.PasswordHasher.verify()`` now determines the type of the hash and verifies it accordingly. - Some of the hash parameters have been made stricter to be closer to said recommendations. The current goal for a hash verification times is around 50ms. `#41 `_ - To allow for bespoke decisions about upgrading Argon2 parameters, it's now possible to extract them from a hash via the ``argon2.extract_parameters()`` function. `#41 `_ - Additionally ``argon2.PasswordHasher`` now has a ``check_needs_rehash()`` method that allows to verify whether a hash has been created with the instance's parameters or whether it should be rehashed. `#41 `_ ---- 18.1.0 (2018-01-06) ------------------- Vendoring Argon2 @ `670229c `_ (20171227) Changes: ^^^^^^^^ - It is now possible to use the ``argon2-cffi`` bindings against an Argon2 library that is provided by the system. ---- 16.3.0 (2016-11-10) ------------------- Vendoring Argon2 @ `1c4fc41f81f358283755eea88d4ecd05e43b7fd3 `_ (20161029) Changes: ^^^^^^^^ - Prevent side-effects like the installation of ``cffi`` if ``setup.py`` is called with a command that doesn't require it. `#20 `_ - Fix a bunch of warnings with new ``cffi`` versions and Python 3.6. `#14 `_ `#16 `_ - Add low-level bindings for Argon2id functions. ---- 16.2.0 (2016-09-10) ------------------- Vendoring Argon2 @ `4844d2fee15d44cb19296ddf36029326d17c5aa3 `_ Changes: ^^^^^^^^ - Fix compilation on debian jessie. `#13 `_ ---- 16.1.0 (2016-04-19) ------------------- Vendoring Argon2 @ 00aaa6604501fade85853a4b2f5695611ff6e7c5_. Backward-incompatible changes: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - Python 3.3 and 2.6 aren't supported anymore. They may work by chance but any support to them has been ceased. The last Python 2.6 release was on October 29, 2013 and isn't supported by the CPython core team anymore. Major Python packages like Django and Twisted dropped Python 2.6 a while ago already. Python 3.3 never had a significant user base and wasn't part of any distribution's LTS release. Changes: ^^^^^^^^ - Add ``VerifyMismatchError`` that is raised if verification fails only because of a password/hash mismatch. It's a subclass of ``VerificationError`` therefore this change is completely backward compatible. - Add support for `Argon2 1.3 `_. Old hashes remain functional but opportunistic rehashing is strongly recommended. ---- 16.0.0 (2016-01-02) ------------------- Vendoring Argon2 @ 421dafd2a8af5cbb215e16da5953663eb101d139_. Deprecations: ^^^^^^^^^^^^^ - ``hash_password()``, ``hash_password_raw()``, and ``verify_password()`` should not be used anymore. For hashing passwords, use the new ``argon2.PasswordHasher``. If you want to implement your own higher-level abstractions, use the new low-level APIs ``hash_secret()``, ``hash_secret_raw()``, and ``verify_secret()`` from the ``argon2.low_level`` module. If you want to go *really* low-level, ``core()`` is for you. The old functions will *not* raise any warnings though and there are *no* immediate plans to remove them. Changes: ^^^^^^^^ - Add ``argon2.PasswordHasher``. A higher-level class specifically for hashing passwords that also works on Unicode strings. - Add ``argon2.low_level`` module with low-level API bindings for building own high-level abstractions. ---- 15.0.1 (2015-12-18) ------------------- Vendoring Argon2 @ 4fe0d8cda37691228dd5a96a310be57369403a4b_. Changes: ^^^^^^^^ - Fix ``long_description`` on PyPI. ---- 15.0.0 (2015-12-18) ------------------- Vendoring Argon2 @ 4fe0d8cda37691228dd5a96a310be57369403a4b_. Changes: ^^^^^^^^ - ``verify_password()`` doesn't guess the hash type if passed ``None`` anymore. Supporting this resulted in measurable overhead (~ 0.6ms vs 0.8ms on my notebook) since it had to happen in Python. That means that naïve usage of the API would give attackers an edge. The new behavior is that it has the same default value as ``hash_password()`` such that ``verify_password(hash_password(b"password"), b"password")`` still works. - Conditionally use the `SSE2 `_-optimized version of ``argon2`` on x86 architectures. - More packaging fixes. Most notably compilation on Visual Studio 2010 for Python 3.3 and 3.4. - Tweaked default parameters to more reasonable values. Verification should take between 0.5ms and 1ms on recent-ish hardware. ---- 15.0.0b5 (2015-12-10) --------------------- Vendoring Argon2 @ 4fe0d8cda37691228dd5a96a310be57369403a4b_. Initial work. Previous betas were only for fixing Windows packaging. The authors of Argon2 were kind enough to `help me `_ to get it building under Visual Studio 2008 that we’re forced to use for Python 2.7 on Windows. .. _421dafd2a8af5cbb215e16da5953663eb101d139: https://github.com/P-H-C/phc-winner-argon2/tree/421dafd2a8af5cbb215e16da5953663eb101d139 .. _4fe0d8cda37691228dd5a96a310be57369403a4b: https://github.com/P-H-C/phc-winner-argon2/tree/4fe0d8cda37691228dd5a96a310be57369403a4b .. _00aaa6604501fade85853a4b2f5695611ff6e7c5: https://github.com/P-H-C/phc-winner-argon2/tree/00aaa6604501fade85853a4b2f5695611ff6e7c5 argon2-cffi-21.1.0/FAQ.rst000066400000000000000000000023321411272701000150240ustar00rootroot00000000000000Frequently Asked Questions ========================== I'm using ``bcrypt``/``PBKDF2``/``scrypt``/``yescrypt``, do I need to migrate? Using password hashes that aren't memory hard carries a certain risk but there's **no immediate danger or need for action**. If however you are deciding how to hash password *today*, Argon2 is the superior, future-proof choice. But if you already use one of the hashes mentioned in the question, you should be fine for the foreseeable future. If you're using ``scrypt`` or ``yescrypt``, you will be probably fine for good. Why do the ``verify()`` methods raise an Exception instead of returning ``False``? #. The Argon2 library had no concept of a "wrong password" error in the beginning. Therefore when writing these bindings, an exception with the full error had to be raised so you could inspect what went actually wrong. It goes without saying that it's impossible to switch now for backward-compatibility reasons. #. In my opinion, a wrong password should raise an exception such that it can't pass unnoticed by accident. See also The Zen of Python: "Errors should never pass silently." #. It's more `Pythonic `_. argon2-cffi-21.1.0/LICENSE000066400000000000000000000020721411272701000146710ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2015 Hynek Schlawack Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. argon2-cffi-21.1.0/MANIFEST.in000066400000000000000000000004261411272701000154230ustar00rootroot00000000000000include *.rst *.md *.txt *.ini .coveragerc LICENSE .pre-commit-config.yaml pyproject.toml exclude src/argon2/_ffi.py .gitmodules extras/libargon2/.git *.yml graft tests graft .github graft .azure-pipelines recursive-exclude tests *.pyc graft extras graft docs prune docs/_build argon2-cffi-21.1.0/README.rst000066400000000000000000000045431411272701000153600ustar00rootroot00000000000000================= Argon2 for Python ================= .. image:: https://img.shields.io/badge/Docs-Read%20The%20Docs-black :target: https://argon2-cffi.readthedocs.io/ :alt: Documentation .. image:: https://img.shields.io/badge/license-MIT-C06524 :target: https://github.com/hynek/argon2-cffi/blob/main/LICENSE :alt: License: MIT .. image:: https://img.shields.io/pypi/v/argon2-cffi :target: https://pypi.org/project/argon2-cffi/ :alt: PyPI version .. image:: https://static.pepy.tech/personalized-badge/argon2-cffi?period=month&units=international_system&left_color=grey&right_color=blue&left_text=Downloads%20/%20Month :target: https://pepy.tech/project/argon2-cffi :alt: Downloads / Month .. teaser-begin `Argon2 `_ won the `Password Hashing Competition `_ and *argon2-cffi* is the simplest way to use it in Python and PyPy: .. code-block:: pycon >>> from argon2 import PasswordHasher >>> ph = PasswordHasher() >>> hash = ph.hash("s3kr3tp4ssw0rd") >>> hash # doctest: +SKIP '$argon2id$v=19$m=102400,t=2,p=8$tSm+JOWigOgPZx/g44K5fQ$WDyus6py50bVFIPkjA28lQ' >>> ph.verify(hash, "s3kr3tp4ssw0rd") True >>> ph.check_needs_rehash(hash) False >>> ph.verify(hash, "t0t411ywr0ng") Traceback (most recent call last): ... argon2.exceptions.VerifyMismatchError: The password does not match the supplied hash *argon2-cffi*'s documentation lives at `Read the Docs `_, the code on `GitHub `_. It’s rigorously tested on Python 3.5+, and PyPy3. It implements *Argon2* version 1.3, as described in `Argon2: the memory-hard function for password hashing and other applications `_. argon2-cffi for Enterprise ========================== Available as part of the Tidelift Subscription. The maintainers of *argon2-cffi* and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source packages you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact packages you use. `Learn more. `_ argon2-cffi-21.1.0/SECURITY.md000066400000000000000000000007771411272701000154670ustar00rootroot00000000000000# Security Policy ## Supported Versions We are following [CalVer](https://calver.org) with generous backward-compatibility guarantees. Therefore we only support the latest version. ## Reporting a Vulnerability If you think you found a Vulnerability, please contact Hynek Schlawack at . If you insist on using PGP, you can use the key `0xAE2536227F69F181`. The fingerprint must be `C2A0 4F86 ACE2 8ADC F817 DBB7 AE25 3622 7F69 F181`. You can also find it on [Keybase](https://keybase.io/hynek). argon2-cffi-21.1.0/codecov.yml000066400000000000000000000002571411272701000160340ustar00rootroot00000000000000--- comment: false coverage: status: patch: default: target: "100" project: default: target: "100" argon2-cffi-21.1.0/docs/000077500000000000000000000000001411272701000146135ustar00rootroot00000000000000argon2-cffi-21.1.0/docs/Makefile000066400000000000000000000152221411272701000162550ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 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 " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @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/prometheus_async.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/prometheus_async.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/prometheus_async" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/prometheus_async" @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." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @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." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 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." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." argon2-cffi-21.1.0/docs/api.rst000066400000000000000000000116421411272701000161220ustar00rootroot00000000000000API Reference ============= .. module:: argon2 ``argon2-cffi`` comes with an high-level API and hopefully reasonable defaults for Argon2 parameters that result in a verification time of 40--50ms on recent-ish hardware. .. warning:: The current memory requirement is set to rather conservative 100 MB. However, in memory constrained environments like Docker containers that can lead to problems. One possible non-obvious symptom are apparent freezes that are caused by swapping. Please check :doc:`parameters` for more details. Unless you have any special needs, all you need to know is: .. doctest:: >>> from argon2 import PasswordHasher >>> ph = PasswordHasher() >>> hash = ph.hash("s3kr3tp4ssw0rd") >>> hash # doctest: +SKIP '$argon2id$v=19$m=102400,t=2,p=8$tSm+JOWigOgPZx/g44K5fQ$WDyus6py50bVFIPkjA28lQ' >>> ph.verify(hash, "s3kr3tp4ssw0rd") True >>> ph.check_needs_rehash(hash) False >>> ph.verify(hash, "t0t411ywr0ng") Traceback (most recent call last): ... argon2.exceptions.VerifyMismatchError: The password does not match the supplied hash A login function could thus look like this: .. literalinclude:: login_example.py :language: python ---- While the :class:`PasswordHasher` class has the aspiration to be good to use out of the box, it has all the parametrization you'll need: .. autoclass:: PasswordHasher :members: hash, verify, check_needs_rehash If you don't specify any parameters, the following constants are used: .. data:: DEFAULT_RANDOM_SALT_LENGTH .. data:: DEFAULT_HASH_LENGTH .. data:: DEFAULT_TIME_COST .. data:: DEFAULT_MEMORY_COST .. data:: DEFAULT_PARALLELISM You can see their values in :class:`PasswordHasher`. Exceptions ---------- .. autoexception:: argon2.exceptions.VerificationError .. autoexception:: argon2.exceptions.VerifyMismatchError .. autoexception:: argon2.exceptions.HashingError .. autoexception:: argon2.exceptions.InvalidHash Utilities --------- .. autofunction:: extract_parameters .. autoclass:: Parameters Low Level --------- .. automodule:: argon2.low_level .. autoclass:: Type :members: D, I, ID .. autodata:: ARGON2_VERSION .. autofunction:: hash_secret .. doctest:: >>> import argon2 >>> argon2.low_level.hash_secret( ... b"secret", b"somesalt", ... time_cost=1, memory_cost=8, parallelism=1, hash_len=64, type=argon2.low_level.Type.D ... ) b'$argon2d$v=19$m=8,t=1,p=1$c29tZXNhbHQ$ba2qC75j0+JAunZZ/L0hZdQgCv+tOieBuKKXSrQiWm7nlkRcK+YqWr0i0m0WABJKelU8qHJp0SZzH0b1Z+ITvQ' .. autofunction:: verify_secret The raw hash can also be computed: .. autofunction:: hash_secret_raw .. doctest:: >>> argon2.low_level.hash_secret_raw( ... b"secret", b"somesalt", ... time_cost=1, memory_cost=8, parallelism=1, hash_len=8, type=argon2.low_level.Type.D ... ) b'\xe4n\xf5\xc8|\xa3>\x1d' The super low-level ``argon2_core()`` function is exposed too if you need access to very specific options: .. autofunction:: core In order to use :func:`core`, you need access to ``argon2-cffi``'s FFI objects. Therefore it is OK to use ``argon2.low_level.ffi`` and ``argon2.low_level.lib`` when working with it: .. doctest:: >>> from argon2.low_level import ARGON2_VERSION, Type, core, ffi, lib >>> pwd = b"secret" >>> salt = b"12345678" >>> hash_len = 8 >>> # Make sure you keep FFI objects alive until *after* the core call! >>> cout = ffi.new("uint8_t[]", hash_len) >>> cpwd = ffi.new("uint8_t[]", pwd) >>> csalt = ffi.new("uint8_t[]", salt) >>> ctx = ffi.new( ... "argon2_context *", dict( ... version=ARGON2_VERSION, ... out=cout, outlen=hash_len, ... pwd=cpwd, pwdlen=len(pwd), ... salt=csalt, saltlen=len(salt), ... secret=ffi.NULL, secretlen=0, ... ad=ffi.NULL, adlen=0, ... t_cost=1, ... m_cost=8, ... lanes=1, threads=1, ... allocate_cbk=ffi.NULL, free_cbk=ffi.NULL, ... flags=lib.ARGON2_DEFAULT_FLAGS, ... ) ... ) >>> ctx >>> core(ctx, Type.D.value) 0 >>> out = bytes(ffi.buffer(ctx.out, ctx.outlen)) >>> out b'\xb4\xe2HjO\x14d\x9b' >>> out == argon2.low_level.hash_secret_raw(pwd, salt, 1, 8, 1, 8, Type.D) True All constants and types on ``argon2.low_level.lib`` are guaranteed to stay as long they are not altered by Argon2 itself. .. autofunction:: error_to_str Deprecated APIs --------------- These APIs are from the first release of ``argon2-cffi`` and proved to live in an unfortunate mid-level. On one hand they have defaults and check parameters but on the other hand they only consume byte strings. Therefore the decision has been made to replace them by a high-level (:class:`argon2.PasswordHasher`) and a low-level (:mod:`argon2.low_level`) solution. There are no immediate plans to remove them though. .. autofunction:: argon2.hash_password .. autofunction:: argon2.hash_password_raw .. autofunction:: argon2.verify_password argon2-cffi-21.1.0/docs/argon2.rst000066400000000000000000000057141411272701000165440ustar00rootroot00000000000000Argon2 ====== .. note:: **TL;DR**: Use :class:`argon2.PasswordHasher` with its default parameters to securely hash your passwords. You do **not** need to read or understand anything below this box. Argon2 is a secure password hashing algorithm. It is designed to have both a configurable runtime as well as memory consumption. This means that you can decide how long it takes to hash a password and how much memory is required. Argon2 comes in three variants: Argon2d is faster and uses data-depending memory access, which makes it less suitable for hashing secrets and more suitable for cryptocurrencies and applications with no threats from side-channel timing attacks. Argon2i uses data-independent memory access, which is preferred for password hashing and password-based key derivation. Argon2i is slower as it makes more passes over the memory to protect from tradeoff attacks. Argon2id is a hybrid of Argon2i and Argon2d, using a combination of data-depending and data-independent memory accesses, which gives some of Argon2i's resistance to side-channel cache timing attacks and much of Argon2d's resistance to GPU cracking attacks. Why “just use bcrypt” Is Not the Best Answer (Anymore) ------------------------------------------------------ The current workhorses of password hashing are unquestionably bcrypt_ and PBKDF2_. And while they're still fine to use, the password cracking community embraced new technologies like GPU_\ s and ASIC_\ s to crack password in a highly parallel fashion. An effective measure against extreme parallelism proved making computation of password hashes also *memory* hard. The best known implementation of that approach is to date scrypt_. However according to the `Argon2 paper`_, page 2: […] the existence of a trivial time-memory tradeoff allows compact implementations with the same energy cost. Therefore a new algorithm was needed. This time future-proof and with committee-vetting instead of single implementors. .. _bcrypt: https://en.wikipedia.org/wiki/Bcrypt .. _PBKDF2: https://en.wikipedia.org/wiki/PBKDF2 .. _GPU: https://hashcat.net/hashcat/ .. _ASIC: https://en.wikipedia.org/wiki/Application-specific_integrated_circuit .. _scrypt: https://en.wikipedia.org/wiki/Scrypt .. _Argon2 paper: https://www.password-hashing.net/argon2-specs.pdf Password Hashing Competition ---------------------------- The `Password Hashing Competition`_ took place between 2012 and 2015 to find a new, secure, and future-proof password hashing algorithm. Previously the NIST was in charge but after certain events and revelations_ their integrity has been put into question by the general public. So a group of independent cryptographers and security researchers came together. In the end, Argon2 was announced_ as the winner. .. _Password Hashing Competition: https://www.password-hashing.net/ .. _revelations: https://en.wikipedia.org/wiki/Dual_EC_DRBG .. _announced: https://groups.google.com/forum/#!topic/crypto-competitions/3QNdmwBS98o argon2-cffi-21.1.0/docs/backward-compatibility.rst000066400000000000000000000011051411272701000217670ustar00rootroot00000000000000Backward Compatibility ====================== ``argon2-cffi`` has a very strong backward compatibility policy. Generally speaking, you shouldn't ever be afraid of updating. If breaking changes are needed do be done, they are: #. …announced in the changelog_. #. …the old behavior raises a :exc:`DeprecationWarning` for a year. #. …are done with another announcement in the changelog_. What explicitly *may* change over time are the default hashing parameters and the behavior of the :doc:`cli`. .. _changelog: https://argon2-cffi.readthedocs.io/en/stable/changelog.html argon2-cffi-21.1.0/docs/changelog.rst000066400000000000000000000000361411272701000172730ustar00rootroot00000000000000.. include:: ../CHANGELOG.rst argon2-cffi-21.1.0/docs/cli.rst000066400000000000000000000011601411272701000161120ustar00rootroot00000000000000CLI === To aid you with finding the parameters, ``argon2-cffi`` offers a CLI interface that can be accessed using ``python -m argon2``. It will benchmark Argon2’s password *verification* in the current environment. You can use command line arguments to set hashing parameters: .. code-block:: text $ python -m argon2 Running Argon2id 100 times with: hash_len: 16 bytes memory_cost: 102400 KiB parallelism: 8 threads time_cost: 2 iterations Measuring... 45.3ms per password verification This should make it much easier to determine the right parameters for your use case and your environment. argon2-cffi-21.1.0/docs/conf.py000066400000000000000000000222111411272701000161100ustar00rootroot00000000000000# # argon2-cffi documentation build configuration file, created by # sphinx-quickstart on Sun May 11 16:17:15 2014. # # 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 codecs import datetime import os import re def read(*parts): """ Build an absolute path from *parts* and and return the contents of the resulting file. Assume UTF-8 encoding. """ here = os.path.abspath(os.path.dirname(__file__)) with codecs.open(os.path.join(here, *parts), "rb", "utf-8") as f: return f.read() def find_version(*file_paths): """ Build a path from *file_paths* and search for a ``__version__`` string inside. """ version_file = read(*file_paths) version_match = re.search( r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M ) if version_match: return version_match.group(1) raise RuntimeError("Unable to find version string.") # 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('.')) # -- 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.doctest", "sphinx.ext.intersphinx", "sphinx.ext.todo", ] # 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 = "argon2-cffi" year = datetime.date.today().year copyright = "2015, Hynek Schlawack" # 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. release = find_version("..", "src", "argon2", "__init__.py") version = release.rsplit(".", 1)[0] # The full version, including alpha/beta/rc tags. # 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 # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. # keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = "furo" # 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 = [] # 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'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. # html_extra_path = [] # 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 = "argon2-cffidoc" # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # 'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ( "index", "argon2-cffi.tex", "argon2-cffi Documentation", "Hynek Schlawack", "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 # 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", "argon2-cffi", "argon2-cffi Documentation", ["Hynek Schlawack"], 1, ) ] # If true, show URL addresses after external links. # man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ( "index", "argon2-cffi", "argon2-cffi Documentation", "Hynek Schlawack", "argon2-cffi", "One line description of project.", "Miscellaneous", ) ] # Documents to append as an appendix to all manuals. # texinfo_appendices = [] # If false, no module index is generated. # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. # texinfo_no_detailmenu = False # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {"https://docs.python.org/3": None} argon2-cffi-21.1.0/docs/contributing.rst000066400000000000000000000000741411272701000200550ustar00rootroot00000000000000.. _contributing: .. include:: ../.github/CONTRIBUTING.rst argon2-cffi-21.1.0/docs/faq.rst000066400000000000000000000000301411272701000161050ustar00rootroot00000000000000.. include:: ../FAQ.rst argon2-cffi-21.1.0/docs/index.rst000066400000000000000000000007411411272701000164560ustar00rootroot00000000000000``argon2-cffi`` =============== Release v\ |release| (:doc:`What's new? `). .. include:: ../README.rst :start-after: teaser-begin User's Guide ------------ .. toctree:: :maxdepth: 1 argon2 installation api parameters cli faq Project Information ------------------- .. toctree:: :maxdepth: 1 backward-compatibility contributing changelog license Indices and tables ================== * :ref:`genindex` * :ref:`search` argon2-cffi-21.1.0/docs/installation.rst000066400000000000000000000052271411272701000200540ustar00rootroot00000000000000Installation ============ Using the Vendored Argon2 ------------------------- .. code-block:: bash python -m pip install argon2-cffi should be all it takes. But since ``argon2-cffi`` vendors Argon2's C code by default, it can lead to complications depending on the platform. The C code is known to compile and work on all common platforms (including x86, ARM, and PPC). On x86, an SSE2_-optimized version is used. If something goes wrong, please try to update your ``cffi``, ``pip`` and ``setuptools`` first: .. code-block:: bash python -m pip install -U cffi pip setuptools Overall this should be the safest bet because ``argon2-cffi`` has been specifically tested against the vendored version. Wheels ^^^^^^ Binary `wheels `_ for macOS, Windows, and Linux are provided on PyPI_. With a recent-enough ``pip`` and ``setuptools``, they should be used automatically. Source Distribution ^^^^^^^^^^^^^^^^^^^ A working C compiler and `CFFI environment`_ are required. If you've been able to compile Python CFFI extensions before, ``argon2-cffi`` should install without any problems. Using a System-wide Installation of Argon2 ------------------------------------------ If you set ``ARGON2_CFFI_USE_SYSTEM`` to ``1`` (and *only* ``1``), ``argon2-cffi`` will not build its bindings. However binary wheels are preferred by ``pip`` and Argon2 gets installed along with ``argon2-cffi`` anyway. Therefore you also have to instruct ``pip`` to use a source distribution: .. code-block:: bash env ARGON2_CFFI_USE_SYSTEM=1 \ python -m pip install --no-binary=argon2-cffi argon2-cffi This approach can lead to problems around your build chain and you can run into incompatibilities between Argon2 and ``argon2-cffi`` if the latter has been tested against a different version. **It is your own responsibility to deal with these risks if you choose this path.** Available since version 18.1.0. Override Automatic SSE2 Detection --------------------------------- Usually the build process tries to guess whether or not it should use SSE2_-optimized code. This can go wrong and is problematic for cross-compiling. Therefore you can use the ``ARGON2_CFFI_USE_SSE2`` environment variable to control the process: - If you set it to ``1``, ``argon2-cffi`` will build **with** SSE2 support. - If you set it to ``0``, ``argon2-cffi`` will build **without** SSE2 support. - If you set it to anything else, it will be ignored and ``argon2-cffi`` will try to guess. Available since version 20.1.0. .. _SSE2: https://en.wikipedia.org/wiki/SSE2 .. _PyPI: https://pypi.org/project/argon2-cffi/ .. _CFFI environment: https://cffi.readthedocs.io/en/latest/installation.html argon2-cffi-21.1.0/docs/license.rst000066400000000000000000000000341411272701000167640ustar00rootroot00000000000000.. include:: ../AUTHORS.rst argon2-cffi-21.1.0/docs/login_example.py000066400000000000000000000007061411272701000200130ustar00rootroot00000000000000import argon2 ph = argon2.PasswordHasher() def login(db, user, password): hash = db.get_password_hash_for_user(user) # Verify password, raises exception if wrong. ph.verify(hash, password) # Now that we have the cleartext password, # check the hash's parameters and if outdated, # rehash the user's password in the database. if ph.check_needs_rehash(hash): db.set_password_hash_for_user(user, ph.hash(password)) argon2-cffi-21.1.0/docs/parameters.rst000066400000000000000000000056011411272701000175120ustar00rootroot00000000000000Choosing Parameters =================== .. note:: You can probably just use :class:`argon2.PasswordHasher` with its default values and be fine. But it's good to double check using ``argon2-cffi``'s :doc:`cli` client, whether its defaults are too slow or too fast for your use case. Finding the right parameters for a password hashing algorithm is a daunting task. The authors of Argon2 specified a method in their `paper `_, however some parts of it have been revised in the `RFC draft`_ for Argon2 that is currently being written. The current recommended best practice is as follow: #. Choose whether you want Argon2i, Argon2d, or Argon2id (``type``). If you don't know what that means, choose Argon2id (:attr:`argon2.Type.ID`). #. Figure out how many threads can be used on each call to Argon2 (``parallelism``, called "lanes" in the RFC). They recommend twice as many as the number of cores dedicated to hashing passwords. :class:`~argon2.PasswordHasher` will *not* determine this for you and use a default value that you can find in the linked API docs. #. Figure out how much memory each call can afford (``memory_cost``). The RFC recommends 4 GB for backend authentication and 1 GB for frontend authentication. The APIs use Kibibytes_ (1024 bytes) as base unit. #. Select the salt length. 16 bytes is sufficient for all applications, but can be reduced to 8 bytes in the case of space constraints. #. Choose a hash length (``hash_len``, called "tag length" in the documentation). 16 bytes is sufficient for password verification. #. Figure out how long each call can take. One `recommendation `_ for concurent user logins is to keep it under 0.5 ms. The RFC recommends under 500 ms. The truth is somewhere between those two values: more is more secure, less is a better user experience. ``argon2-cffi``'s defaults try to land somewhere in the middle and aim for ~50ms, but the actual time depends on your hardware. Please note though, that even a verification time of 1 second won't protect you against bad passwords from the "top 10,000 passwords" lists that you can find online. #. Measure the time for hashing using your chosen parameters. Find a ``time_cost`` that is within your accounted time. If ``time_cost=1`` takes too long, lower ``memory_cost``. ``argon2-cffi``'s :doc:`cli` will help you with this process. .. note:: Alternatively, you can also refer to the `OWASP cheatsheet `_. .. _`RFC draft`: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-argon2-13#section-4 .. _kibibytes: https://en.wikipedia.org/wiki/Kibibyte argon2-cffi-21.1.0/extras/000077500000000000000000000000001411272701000151715ustar00rootroot00000000000000argon2-cffi-21.1.0/extras/libargon2/000077500000000000000000000000001411272701000170505ustar00rootroot00000000000000argon2-cffi-21.1.0/pyproject.toml000066400000000000000000000010441411272701000165760ustar00rootroot00000000000000[build-system] requires = ["setuptools>=40.6.0", "wheel", "cffi>=1.0"] build-backend = "setuptools.build_meta" [tool.pytest.ini_options] addopts = "-ra --strict-markers --capture=no" xfail_strict = true testpaths = "tests" filterwarnings = [ "once::Warning", ] [tool.coverage.run] parallel = true branch = true source = ["argon2"] [tool.coverage.paths] source = ["src", ".tox/*/site-packages"] [tool.coverage.report] show_missing = true omit = ["src/argon2/_ffi_build.py"] [tool.black] line-length = 79 [tool.isort] profile = "attrs" argon2-cffi-21.1.0/setup.py000066400000000000000000000273001411272701000153770ustar00rootroot00000000000000import codecs import os import platform import re import sys from distutils.command.build import build from distutils.command.build_clib import build_clib from distutils.errors import DistutilsSetupError from setuptools import find_packages, setup from setuptools.command.install import install ############################################################################### NAME = "argon2-cffi" PACKAGES = find_packages(where="src") use_sse2 = os.environ.get("ARGON2_CFFI_USE_SSE2", None) if use_sse2 == "1": optimized = True elif use_sse2 == "0": optimized = False else: # Optimized version requires SSE2 extensions. They have been around since # 2001 so we try to compile it on every recent-ish x86. optimized = platform.machine() in ("i686", "x86", "x86_64", "AMD64") CFFI_MODULES = ["src/argon2/_ffi_build.py:ffi"] lib_base = os.path.join("extras", "libargon2", "src") include_dirs = [ os.path.join(lib_base, "..", "include"), os.path.join(lib_base, "blake2"), ] sources = [ os.path.join(lib_base, path) for path in [ "argon2.c", os.path.join("blake2", "blake2b.c"), "core.c", "encoding.c", "opt.c" if optimized else "ref.c", "thread.c", ] ] # Add vendored integer types headers if necessary. windows = "win32" in str(sys.platform).lower() LIBRARIES = [("argon2", {"include_dirs": include_dirs, "sources": sources})] META_PATH = os.path.join("src", "argon2", "__init__.py") KEYWORDS = ["password", "hash", "hashing", "security"] PROJECT_URLS = { "Documentation": "https://argon2-cffi.readthedocs.io/", "Bug Tracker": "https://github.com/hynek/argon2-cffi/issues", "Source Code": "https://github.com/hynek/argon2-cffi", "Funding": "https://github.com/sponsors/hynek", "Tidelift": "https://tidelift.com/subscription/pkg/pypi-argon2-cffi?" "utm_source=pypi-argon2-cffi&utm_medium=pypi", "Ko-fi": "https://ko-fi.com/the_hynek", } CLASSIFIERS = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: MacOS :: MacOS X", "Operating System :: Microsoft :: Windows", "Operating System :: POSIX", "Operating System :: Unix", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Programming Language :: Python", "Topic :: Security :: Cryptography", "Topic :: Security", "Topic :: Software Development :: Libraries :: Python Modules", ] PYTHON_REQUIRES = ">=3.5" SETUP_REQUIRES = ["cffi"] INSTALL_REQUIRES = ["cffi>=1.0.0"] EXTRAS_REQUIRE = { "docs": ["sphinx", "furo"], "tests": ["coverage[toml]>=5.0.2", "hypothesis", "pytest"], } EXTRAS_REQUIRE["dev"] = ( EXTRAS_REQUIRE["tests"] + EXTRAS_REQUIRE["docs"] + ["wheel", "pre-commit"] ) ############################################################################### def keywords_with_side_effects(argv): """ Get a dictionary with setup keywords that (can) have side effects. :param argv: A list of strings with command line arguments. :returns: A dictionary with keyword arguments for the ``setup()`` function. This setup.py script uses the setuptools 'setup_requires' feature because this is required by the cffi package to compile extension modules. The purpose of ``keywords_with_side_effects()`` is to avoid triggering the cffi build process as a result of setup.py invocations that don't need the cffi module to be built (setup.py serves the dual purpose of exposing package metadata). Stolen from pyca/cryptography. """ no_setup_requires_arguments = ( "-h", "--help", "-n", "--dry-run", "-q", "--quiet", "-v", "--verbose", "-V", "--version", "--author", "--author-email", "--classifiers", "--contact", "--contact-email", "--description", "--egg-base", "--fullname", "--help-commands", "--keywords", "--licence", "--license", "--long-description", "--maintainer", "--maintainer-email", "--name", "--no-user-cfg", "--obsoletes", "--platforms", "--provides", "--requires", "--url", "clean", "egg_info", "register", "sdist", "upload", ) def is_short_option(argument): """Check whether a command line argument is a short option.""" return len(argument) >= 2 and argument[0] == "-" and argument[1] != "-" def expand_short_options(argument): """Expand combined short options into canonical short options.""" return ("-" + char for char in argument[1:]) def argument_without_setup_requirements(argv, i): """Check whether a command line argument needs setup requirements.""" if argv[i] in no_setup_requires_arguments: # Simple case: An argument which is either an option or a command # which doesn't need setup requirements. return True elif is_short_option(argv[i]) and all( option in no_setup_requires_arguments for option in expand_short_options(argv[i]) ): # Not so simple case: Combined short options none of which need # setup requirements. return True elif argv[i - 1 : i] == ["--egg-base"]: # Tricky case: --egg-info takes an argument which should not make # us use setup_requires (defeating the purpose of this code). return True else: return False if all( argument_without_setup_requirements(argv, i) for i in range(1, len(argv)) ): return {"cmdclass": {"build": DummyBuild, "install": DummyInstall}} else: use_system_argon2 = ( os.environ.get("ARGON2_CFFI_USE_SYSTEM", "0") == "1" ) if use_system_argon2: disable_subcommand(build, "build_clib") cmdclass = {"build_clib": BuildCLibWithCompilerFlags} if BDistWheel is not None: cmdclass["bdist_wheel"] = BDistWheel return { "setup_requires": SETUP_REQUIRES, "cffi_modules": CFFI_MODULES, "libraries": LIBRARIES, "cmdclass": cmdclass, } def disable_subcommand(command, subcommand_name): for name, method in command.sub_commands: if name == subcommand_name: command.sub_commands.remove((subcommand_name, method)) break setup_requires_error = ( "Requested setup command that needs 'setup_requires' while command line " "arguments implied a side effect free command or option." ) class DummyBuild(build): """ This class makes it very obvious when ``keywords_with_side_effects()`` has incorrectly interpreted the command line arguments to ``setup.py build`` as one of the 'side effect free' commands or options. """ def run(self): raise RuntimeError(setup_requires_error) class DummyInstall(install): """ This class makes it very obvious when ``keywords_with_side_effects()`` has incorrectly interpreted the command line arguments to ``setup.py install`` as one of the 'side effect free' commands or options. """ def run(self): raise RuntimeError(setup_requires_error) HERE = os.path.abspath(os.path.dirname(__file__)) def read(*parts): """ Build an absolute path from *parts* and and return the contents of the resulting file. Assume UTF-8 encoding. """ with codecs.open(os.path.join(HERE, *parts), "rb", "utf-8") as f: return f.read() META_FILE = read(META_PATH) def find_meta(meta): """ Extract __*meta*__ from META_FILE. """ meta_match = re.search( r"^__{meta}__ = ['\"]([^'\"]*)['\"]".format(meta=meta), META_FILE, re.M ) if meta_match: return meta_match.group(1) raise RuntimeError("Unable to find __{meta}__ string.".format(meta=meta)) VERSION = find_meta("version") URL = find_meta("url") LONG = ( read("README.rst") + "\n\n" + "Release Information\n" + "===================\n\n" + re.search( r"(\d+.\d.\d \(.*?\)\r?\n.*?)\r?\n\r?\n\r?\n----\r?\n\r?\n\r?\n", read("CHANGELOG.rst"), re.S, ).group(1) + "\n\n`Full changelog " + "<{url}en/stable/changelog.html>`_.\n\n".format(url=URL) + read("AUTHORS.rst") ) class BuildCLibWithCompilerFlags(build_clib): """ We need to pass ``-msse2`` for the optimized build. """ def build_libraries(self, libraries): """ Mostly copy pasta from ``distutils.command.build_clib``. """ for (lib_name, build_info) in libraries: sources = build_info.get("sources") if sources is None or not isinstance(sources, (list, tuple)): raise DistutilsSetupError( "in 'libraries' option (library '%s'), " "'sources' must be present and must be " "a list of source filenames" % lib_name ) sources = list(sources) print("building '{}' library".format(lib_name)) # First, compile the source code to object files in the library # directory. (This should probably change to putting object # files in a temporary build directory.) macros = build_info.get("macros") include_dirs = build_info.get("include_dirs") objects = self.compiler.compile( sources, extra_preargs=["-msse2"] if optimized and not windows else [], output_dir=self.build_temp, macros=macros, include_dirs=include_dirs, debug=self.debug, ) # Now "link" the object files together into a static library. # (On Unix at least, this isn't really linking -- it just # builds an archive. Whatever.) self.compiler.create_static_lib( objects, lib_name, output_dir=self.build_clib, debug=self.debug ) if sys.version_info > (3,) and platform.python_implementation() == "CPython": try: import wheel.bdist_wheel except ImportError: BDistWheel = None else: class BDistWheel(wheel.bdist_wheel.bdist_wheel): def finalize_options(self): self.py_limited_api = "cp3{}".format(sys.version_info[1]) wheel.bdist_wheel.bdist_wheel.finalize_options(self) else: BDistWheel = None if __name__ == "__main__": setup( name=NAME, description=find_meta("description"), license=find_meta("license"), url=URL, project_urls=PROJECT_URLS, version=VERSION, author=find_meta("author"), author_email=find_meta("email"), maintainer=find_meta("author"), maintainer_email=find_meta("email"), long_description=LONG, long_description_content_type="text/x-rst", keywords=KEYWORDS, packages=PACKAGES, package_dir={"": "src"}, classifiers=CLASSIFIERS, python_requires=PYTHON_REQUIRES, install_requires=INSTALL_REQUIRES, extras_require=EXTRAS_REQUIRE, # CFFI zip_safe=False, ext_package="argon2", **keywords_with_side_effects(sys.argv) ) argon2-cffi-21.1.0/src/000077500000000000000000000000001411272701000144525ustar00rootroot00000000000000argon2-cffi-21.1.0/src/argon2/000077500000000000000000000000001411272701000156425ustar00rootroot00000000000000argon2-cffi-21.1.0/src/argon2/__init__.py000066400000000000000000000020541411272701000177540ustar00rootroot00000000000000from . import exceptions, low_level from ._legacy import hash_password, hash_password_raw, verify_password from ._password_hasher import ( DEFAULT_HASH_LENGTH, DEFAULT_MEMORY_COST, DEFAULT_PARALLELISM, DEFAULT_RANDOM_SALT_LENGTH, DEFAULT_TIME_COST, PasswordHasher, ) from ._utils import Parameters, extract_parameters from .low_level import Type __version__ = "21.1.0" __title__ = "argon2-cffi" __description__ = "The secure Argon2 password hashing algorithm." __url__ = "https://argon2-cffi.readthedocs.io/" __uri__ = __url__ __doc__ = __description__ + " <" + __url__ + ">" __author__ = "Hynek Schlawack" __email__ = "hs@ox.cx" __license__ = "MIT" __copyright__ = "Copyright (c) 2015 " + __author__ __all__ = [ "DEFAULT_HASH_LENGTH", "DEFAULT_MEMORY_COST", "DEFAULT_PARALLELISM", "DEFAULT_RANDOM_SALT_LENGTH", "DEFAULT_TIME_COST", "Parameters", "PasswordHasher", "Type", "exceptions", "extract_parameters", "hash_password", "hash_password_raw", "low_level", "verify_password", ] argon2-cffi-21.1.0/src/argon2/__main__.py000066400000000000000000000040331411272701000177340ustar00rootroot00000000000000import argparse import sys import timeit from . import ( DEFAULT_HASH_LENGTH, DEFAULT_MEMORY_COST, DEFAULT_PARALLELISM, DEFAULT_TIME_COST, PasswordHasher, ) def main(argv): parser = argparse.ArgumentParser(description="Benchmark Argon2.") parser.add_argument( "-n", type=int, default=100, help="Number of iterations to measure." ) parser.add_argument( "-t", type=int, help="`time_cost`", default=DEFAULT_TIME_COST ) parser.add_argument( "-m", type=int, help="`memory_cost`", default=DEFAULT_MEMORY_COST ) parser.add_argument( "-p", type=int, help="`parallelism`", default=DEFAULT_PARALLELISM ) parser.add_argument( "-l", type=int, help="`hash_length`", default=DEFAULT_HASH_LENGTH ) args = parser.parse_args(argv[1:]) password = b"secret" ph = PasswordHasher( time_cost=args.t, memory_cost=args.m, parallelism=args.p, hash_len=args.l, ) hash = ph.hash(password) params = { "time_cost": (args.t, "iterations"), "memory_cost": (args.m, "KiB"), "parallelism": (args.p, "threads"), "hash_len": (args.l, "bytes"), } print("Running Argon2id %d times with:" % (args.n,)) for k, v in sorted(params.items()): print("%s: %d %s" % (k, v[0], v[1])) print("\nMeasuring...") duration = timeit.timeit( "ph.verify({hash!r}, {password!r})".format( hash=hash, password=password ), setup="""\ from argon2 import PasswordHasher, Type ph = PasswordHasher( time_cost={time_cost!r}, memory_cost={memory_cost!r}, parallelism={parallelism!r}, hash_len={hash_len!r}, ) gc.enable()""".format( time_cost=args.t, memory_cost=args.m, parallelism=args.p, hash_len=args.l, ), number=args.n, ) print( "\n{:.1f}ms per password verification".format(duration / args.n * 1000) ) if __name__ == "__main__": # pragma: nocover main(sys.argv) argon2-cffi-21.1.0/src/argon2/_ffi_build.py000066400000000000000000000111711411272701000202770ustar00rootroot00000000000000import os from cffi import FFI include_dirs = [os.path.join("extras", "libargon2", "include")] use_system_argon2 = os.environ.get("ARGON2_CFFI_USE_SYSTEM", "0") == "1" if use_system_argon2: include_dirs = [] ffi = FFI() ffi.set_source( "_ffi", "#include ", include_dirs=include_dirs, libraries=["argon2"], ) ffi.cdef( """\ typedef enum Argon2_type { Argon2_d = ..., Argon2_i = ..., Argon2_id = ..., } argon2_type; typedef enum Argon2_version { ARGON2_VERSION_10 = ..., ARGON2_VERSION_13 = ..., ARGON2_VERSION_NUMBER = ... } argon2_version; int argon2_hash(const uint32_t t_cost, const uint32_t m_cost, const uint32_t parallelism, const void *pwd, const size_t pwdlen, const void *salt, const size_t saltlen, void *hash, const size_t hashlen, char *encoded, const size_t encodedlen, argon2_type type, const uint32_t version); int argon2_verify(const char *encoded, const void *pwd, const size_t pwdlen, argon2_type type); const char *argon2_error_message(int error_code); typedef int (*allocate_fptr)(uint8_t **memory, size_t bytes_to_allocate); typedef void (*deallocate_fptr)(uint8_t *memory, size_t bytes_to_allocate); typedef struct Argon2_Context { uint8_t *out; /* output array */ uint32_t outlen; /* digest length */ uint8_t *pwd; /* password array */ uint32_t pwdlen; /* password length */ uint8_t *salt; /* salt array */ uint32_t saltlen; /* salt length */ uint8_t *secret; /* key array */ uint32_t secretlen; /* key length */ uint8_t *ad; /* associated data array */ uint32_t adlen; /* associated data length */ uint32_t t_cost; /* number of passes */ uint32_t m_cost; /* amount of memory requested (KB) */ uint32_t lanes; /* number of lanes */ uint32_t threads; /* maximum number of threads */ uint32_t version; /* version number */ allocate_fptr allocate_cbk; /* pointer to memory allocator */ deallocate_fptr free_cbk; /* pointer to memory deallocator */ uint32_t flags; /* array of bool options */ } argon2_context; int argon2_ctx(argon2_context *context, argon2_type type); /* Error codes */ typedef enum Argon2_ErrorCodes { ARGON2_OK = ..., ARGON2_OUTPUT_PTR_NULL = ..., ARGON2_OUTPUT_TOO_SHORT = ..., ARGON2_OUTPUT_TOO_LONG = ..., ARGON2_PWD_TOO_SHORT = ..., ARGON2_PWD_TOO_LONG = ..., ARGON2_SALT_TOO_SHORT = ..., ARGON2_SALT_TOO_LONG = ..., ARGON2_AD_TOO_SHORT = ..., ARGON2_AD_TOO_LONG = ..., ARGON2_SECRET_TOO_SHORT = ..., ARGON2_SECRET_TOO_LONG = ..., ARGON2_TIME_TOO_SMALL = ..., ARGON2_TIME_TOO_LARGE = ..., ARGON2_MEMORY_TOO_LITTLE = ..., ARGON2_MEMORY_TOO_MUCH = ..., ARGON2_LANES_TOO_FEW = ..., ARGON2_LANES_TOO_MANY = ..., ARGON2_PWD_PTR_MISMATCH = ..., /* NULL ptr with non-zero length */ ARGON2_SALT_PTR_MISMATCH = ..., /* NULL ptr with non-zero length */ ARGON2_SECRET_PTR_MISMATCH = ..., /* NULL ptr with non-zero length */ ARGON2_AD_PTR_MISMATCH = ..., /* NULL ptr with non-zero length */ ARGON2_MEMORY_ALLOCATION_ERROR = ..., ARGON2_FREE_MEMORY_CBK_NULL = ..., ARGON2_ALLOCATE_MEMORY_CBK_NULL = ..., ARGON2_INCORRECT_PARAMETER = ..., ARGON2_INCORRECT_TYPE = ..., ARGON2_OUT_PTR_MISMATCH = ..., ARGON2_THREADS_TOO_FEW = ..., ARGON2_THREADS_TOO_MANY = ..., ARGON2_MISSING_ARGS = ..., ARGON2_ENCODING_FAIL = ..., ARGON2_DECODING_FAIL = ..., ARGON2_THREAD_FAIL = ..., ARGON2_DECODING_LENGTH_FAIL= ..., ARGON2_VERIFY_MISMATCH = ..., } argon2_error_codes; #define ARGON2_FLAG_CLEAR_PASSWORD ... #define ARGON2_FLAG_CLEAR_SECRET ... #define ARGON2_DEFAULT_FLAGS ... #define ARGON2_MIN_LANES ... #define ARGON2_MAX_LANES ... #define ARGON2_MIN_THREADS ... #define ARGON2_MAX_THREADS ... #define ARGON2_SYNC_POINTS ... #define ARGON2_MIN_OUTLEN ... #define ARGON2_MAX_OUTLEN ... #define ARGON2_MIN_MEMORY ... #define ARGON2_MAX_MEMORY_BITS ... #define ARGON2_MAX_MEMORY ... #define ARGON2_MIN_TIME ... #define ARGON2_MAX_TIME ... #define ARGON2_MIN_PWD_LENGTH ... #define ARGON2_MAX_PWD_LENGTH ... #define ARGON2_MIN_AD_LENGTH ... #define ARGON2_MAX_AD_LENGTH ... #define ARGON2_MIN_SALT_LENGTH ... #define ARGON2_MAX_SALT_LENGTH ... #define ARGON2_MIN_SECRET ... #define ARGON2_MAX_SECRET ... uint32_t argon2_encodedlen(uint32_t t_cost, uint32_t m_cost, uint32_t parallelism, uint32_t saltlen, uint32_t hashlen, argon2_type type); """ ) if __name__ == "__main__": ffi.compile() argon2-cffi-21.1.0/src/argon2/_legacy.py000066400000000000000000000032271411272701000176230ustar00rootroot00000000000000""" Legacy mid-level functions. """ import os from ._password_hasher import ( DEFAULT_HASH_LENGTH, DEFAULT_MEMORY_COST, DEFAULT_PARALLELISM, DEFAULT_RANDOM_SALT_LENGTH, DEFAULT_TIME_COST, ) from .low_level import Type, hash_secret, hash_secret_raw, verify_secret def hash_password( password, salt=None, time_cost=DEFAULT_TIME_COST, memory_cost=DEFAULT_MEMORY_COST, parallelism=DEFAULT_PARALLELISM, hash_len=DEFAULT_HASH_LENGTH, type=Type.I, ): """ Legacy alias for :func:`hash_secret` with default parameters. .. deprecated:: 16.0.0 Use :class:`argon2.PasswordHasher` for passwords. """ if salt is None: salt = os.urandom(DEFAULT_RANDOM_SALT_LENGTH) return hash_secret( password, salt, time_cost, memory_cost, parallelism, hash_len, type ) def hash_password_raw( password, salt=None, time_cost=DEFAULT_TIME_COST, memory_cost=DEFAULT_MEMORY_COST, parallelism=DEFAULT_PARALLELISM, hash_len=DEFAULT_HASH_LENGTH, type=Type.I, ): """ Legacy alias for :func:`hash_secret_raw` with default parameters. .. deprecated:: 16.0.0 Use :class:`argon2.PasswordHasher` for passwords. """ if salt is None: salt = os.urandom(DEFAULT_RANDOM_SALT_LENGTH) return hash_secret_raw( password, salt, time_cost, memory_cost, parallelism, hash_len, type ) def verify_password(hash, password, type=Type.I): """ Legacy alias for :func:`verify_secret` with default parameters. .. deprecated:: 16.0.0 Use :class:`argon2.PasswordHasher` for passwords. """ return verify_secret(hash, password, type) argon2-cffi-21.1.0/src/argon2/_password_hasher.py000066400000000000000000000154101411272701000215500ustar00rootroot00000000000000import os from ._utils import Parameters, _check_types, extract_parameters from .exceptions import InvalidHash from .low_level import Type, hash_secret, verify_secret DEFAULT_RANDOM_SALT_LENGTH = 16 DEFAULT_HASH_LENGTH = 16 DEFAULT_TIME_COST = 2 DEFAULT_MEMORY_COST = 102400 DEFAULT_PARALLELISM = 8 def _ensure_bytes(s, encoding): """ Ensure *s* is a bytes string. Encode using *encoding* if it isn't. """ if isinstance(s, bytes): return s return s.encode(encoding) class PasswordHasher: r""" High level class to hash passwords with sensible defaults. Uses Argon2\ **id** by default and always uses a random salt_ for hashing. But it can verify any type of Argon2 as long as the hash is correctly encoded. The reason for this being a class is both for convenience to carry parameters and to verify the parameters only *once*. Any unnecessary slowdown when hashing is a tangible advantage for a brute force attacker. :param int time_cost: Defines the amount of computation realized and therefore the execution time, given in number of iterations. :param int memory_cost: Defines the memory usage, given in kibibytes_. :param int parallelism: Defines the number of parallel threads (*changes* the resulting hash value). :param int hash_len: Length of the hash in bytes. :param int salt_len: Length of random salt to be generated for each password. :param str encoding: The Argon2 C library expects bytes. So if :meth:`hash` or :meth:`verify` are passed an unicode string, it will be encoded using this encoding. :param Type type: Argon2 type to use. Only change for interoperability with legacy systems. .. versionadded:: 16.0.0 .. versionchanged:: 18.2.0 Switch from Argon2i to Argon2id based on the recommendation by the current RFC draft. See also :doc:`parameters`. .. versionchanged:: 18.2.0 Changed default *memory_cost* to 100 MiB and default *parallelism* to 8. .. versionchanged:: 18.2.0 ``verify`` now will determine the type of hash. .. versionchanged:: 18.3.0 The Argon2 type is configurable now. .. _salt: https://en.wikipedia.org/wiki/Salt_(cryptography) .. _kibibytes: https://en.wikipedia.org/wiki/Binary_prefix#kibi """ __slots__ = ["_parameters", "encoding"] def __init__( self, time_cost=DEFAULT_TIME_COST, memory_cost=DEFAULT_MEMORY_COST, parallelism=DEFAULT_PARALLELISM, hash_len=DEFAULT_HASH_LENGTH, salt_len=DEFAULT_RANDOM_SALT_LENGTH, encoding="utf-8", type=Type.ID, ): e = _check_types( time_cost=(time_cost, int), memory_cost=(memory_cost, int), parallelism=(parallelism, int), hash_len=(hash_len, int), salt_len=(salt_len, int), encoding=(encoding, str), type=(type, Type), ) if e: raise TypeError(e) # Cache a Parameters object for check_needs_rehash. self._parameters = Parameters( type=type, version=19, salt_len=salt_len, hash_len=hash_len, time_cost=time_cost, memory_cost=memory_cost, parallelism=parallelism, ) self.encoding = encoding @property def time_cost(self): return self._parameters.time_cost @property def memory_cost(self): return self._parameters.memory_cost @property def parallelism(self): return self._parameters.parallelism @property def hash_len(self): return self._parameters.hash_len @property def salt_len(self): return self._parameters.salt_len @property def type(self): return self._parameters.type def hash(self, password): """ Hash *password* and return an encoded hash. :param password: Password to hash. :type password: ``bytes`` or ``unicode`` :raises argon2.exceptions.HashingError: If hashing fails. :rtype: unicode """ return hash_secret( secret=_ensure_bytes(password, self.encoding), salt=os.urandom(self.salt_len), time_cost=self.time_cost, memory_cost=self.memory_cost, parallelism=self.parallelism, hash_len=self.hash_len, type=self.type, ).decode("ascii") _header_to_type = { b"$argon2i$": Type.I, b"$argon2d$": Type.D, b"$argon2id": Type.ID, } def verify(self, hash, password): """ Verify that *password* matches *hash*. .. warning:: It is assumed that the caller is in full control of the hash. No other parsing than the determination of the hash type is done by ``argon2-cffi``. :param hash: An encoded hash as returned from :meth:`PasswordHasher.hash`. :type hash: ``bytes`` or ``unicode`` :param password: The password to verify. :type password: ``bytes`` or ``unicode`` :raises argon2.exceptions.VerifyMismatchError: If verification fails because *hash* is not valid for *password*. :raises argon2.exceptions.VerificationError: If verification fails for other reasons. :raises argon2.exceptions.InvalidHash: If *hash* is so clearly invalid, that it couldn't be passed to Argon2. :return: ``True`` on success, raise :exc:`~argon2.exceptions.VerificationError` otherwise. :rtype: bool .. versionchanged:: 16.1.0 Raise :exc:`~argon2.exceptions.VerifyMismatchError` on mismatches instead of its more generic superclass. .. versionadded:: 18.2.0 Hash type agility. """ hash = _ensure_bytes(hash, "ascii") try: hash_type = self._header_to_type[hash[:9]] except (IndexError, KeyError, LookupError): raise InvalidHash() return verify_secret( hash, _ensure_bytes(password, self.encoding), hash_type ) def check_needs_rehash(self, hash): """ Check whether *hash* was created using the instance's parameters. Whenever your Argon2 parameters -- or ``argon2-cffi``'s defaults! -- change, you should rehash your passwords at the next opportunity. The common approach is to do that whenever a user logs in, since that should be the only time when you have access to the cleartext password. Therefore it's best practice to check -- and if necessary rehash -- passwords after each successful authentication. :rtype: bool .. versionadded:: 18.2.0 """ return self._parameters != extract_parameters(hash) argon2-cffi-21.1.0/src/argon2/_utils.py000066400000000000000000000106701411272701000175170ustar00rootroot00000000000000from .exceptions import InvalidHash from .low_level import Type NoneType = type(None) def _check_types(**kw): """ Check each ``name: (value, types)`` in *kw*. Returns a human-readable string of all violations or `None``. """ errors = [] for name, (value, types) in kw.items(): if not isinstance(value, types): if isinstance(types, tuple): types = ", or ".join(t.__name__ for t in types) else: types = types.__name__ errors.append( "'{name}' must be a {type} (got {actual})".format( name=name, type=types, actual=type(value).__name__ ) ) if errors != []: return ", ".join(errors) + "." def _encoded_str_len(l): """ Compute how long a byte string of length *l* becomes if encoded to hex. """ return (l << 2) / 3 + 2 def _decoded_str_len(l): """ Compute how long an encoded string of length *l* becomes. """ rem = l % 4 if rem == 3: last_group_len = 2 elif rem == 2: last_group_len = 1 else: last_group_len = 0 return l // 4 * 3 + last_group_len class Parameters: """ Argon2 hash parameters. See :doc:`parameters` on how to pick them. :ivar Type type: Hash type. :ivar int version: Argon2 version. :ivar int salt_len: Length of the salt in bytes. :ivar int hash_len: Length of the hash in bytes. :ivar int time_cost: Time cost in iterations. :ivar int memory_cost: Memory cost in kibibytes. :ivar int parallelism: Number of parallel threads. .. versionadded:: 18.2.0 """ __slots__ = [ "type", "version", "salt_len", "hash_len", "time_cost", "memory_cost", "parallelism", ] def __init__( self, type, version, salt_len, hash_len, time_cost, memory_cost, parallelism, ): self.type = type self.version = version self.salt_len = salt_len self.hash_len = hash_len self.time_cost = time_cost self.memory_cost = memory_cost self.parallelism = parallelism def __repr__(self): return ( "" % ( self.type, self.version, self.hash_len, self.salt_len, self.time_cost, self.memory_cost, self.parallelism, ) ) def __eq__(self, other): if self.__class__ != other.__class__: return NotImplemented return ( self.type, self.version, self.salt_len, self.hash_len, self.time_cost, self.memory_cost, self.parallelism, ) == ( other.type, other.version, other.salt_len, other.hash_len, other.time_cost, other.memory_cost, other.parallelism, ) def __ne__(self, other): if self.__class__ != other.__class__: return NotImplemented return not self.__eq__(other) _NAME_TO_TYPE = {"argon2id": Type.ID, "argon2i": Type.I, "argon2d": Type.D} _REQUIRED_KEYS = sorted(("v", "m", "t", "p")) def extract_parameters(hash): """ Extract parameters from an encoded *hash*. :param str params: An encoded Argon2 hash string. :rtype: Parameters .. versionadded:: 18.2.0 """ parts = hash.split("$") # Backwards compatibility for Argon v1.2 hashes if len(parts) == 5: parts.insert(2, "v=18") if len(parts) != 6: raise InvalidHash if parts[0] != "": raise InvalidHash try: type = _NAME_TO_TYPE[parts[1]] kvs = { k: int(v) for k, v in ( s.split("=") for s in [parts[2]] + parts[3].split(",") ) } except Exception: raise InvalidHash if sorted(kvs.keys()) != _REQUIRED_KEYS: raise InvalidHash return Parameters( type=type, salt_len=_decoded_str_len(len(parts[4])), hash_len=_decoded_str_len(len(parts[5])), version=kvs["v"], time_cost=kvs["t"], memory_cost=kvs["m"], parallelism=kvs["p"], ) argon2-cffi-21.1.0/src/argon2/exceptions.py000066400000000000000000000013701411272701000203760ustar00rootroot00000000000000class Argon2Error(Exception): """ Superclass of all argon2 exceptions. Never thrown directly. """ class VerificationError(Argon2Error): """ Verification failed. You can find the original error message from Argon2 in ``args[0]``. """ class VerifyMismatchError(VerificationError): """ The secret does not match the hash. Subclass of :exc:`argon2.exceptions.VerificationError`. .. versionadded:: 16.1.0 """ class HashingError(Argon2Error): """ Raised if hashing failed. You can find the original error message from Argon2 in ``args[0]``. """ class InvalidHash(ValueError): """ Raised if the hash is invalid before passing it to Argon2. .. versionadded:: 18.2.0 """ argon2-cffi-21.1.0/src/argon2/low_level.py000066400000000000000000000147321411272701000202130ustar00rootroot00000000000000""" Low-level functions if you want to build your own higher level abstractions. .. warning:: This is a "Hazardous Materials" module. You should **ONLY** use it if you're 100% absolutely sure that you know what you’re doing because this module is full of land mines, dragons, and dinosaurs with laser guns. """ from enum import Enum from ._ffi import ffi, lib from .exceptions import HashingError, VerificationError, VerifyMismatchError __all__ = [ "ARGON2_VERSION", "Type", "ffi", "hash_secret", "hash_secret_raw", "verify_secret", ] ARGON2_VERSION = lib.ARGON2_VERSION_NUMBER """ The latest version of the Argon2 algorithm that is supported (and used by default). .. versionadded:: 16.1.0 """ class Type(Enum): """ Enum of Argon2 variants. Please see :doc:`parameters` on how to pick one. """ D = lib.Argon2_d r""" Argon2\ **d** is faster and uses data-depending memory access, which makes it less suitable for hashing secrets and more suitable for cryptocurrencies and applications with no threats from side-channel timing attacks. """ I = lib.Argon2_i r""" Argon2\ **i** uses data-independent memory access. Argon2i is slower as it makes more passes over the memory to protect from tradeoff attacks. """ ID = lib.Argon2_id r""" Argon2\ **id** is a hybrid of Argon2i and Argon2d, using a combination of data-depending and data-independent memory accesses, which gives some of Argon2i's resistance to side-channel cache timing attacks and much of Argon2d's resistance to GPU cracking attacks. That makes it the preferred type for password hashing and password-based key derivation. .. versionadded:: 16.3.0 """ def hash_secret( secret, salt, time_cost, memory_cost, parallelism, hash_len, type, version=ARGON2_VERSION, ): """ Hash *secret* and return an **encoded** hash. An encoded hash can be directly passed into :func:`verify_secret` as it contains all parameters and the salt. :param bytes secret: Secret to hash. :param bytes salt: A salt_. Should be random and different for each secret. :param Type type: Which Argon2 variant to use. :param int version: Which Argon2 version to use. For an explanation of the Argon2 parameters see :class:`PasswordHasher`. :rtype: bytes :raises argon2.exceptions.HashingError: If hashing fails. .. versionadded:: 16.0.0 .. _salt: https://en.wikipedia.org/wiki/Salt_(cryptography) .. _kibibytes: https://en.wikipedia.org/wiki/Binary_prefix#kibi """ size = ( lib.argon2_encodedlen( time_cost, memory_cost, parallelism, len(salt), hash_len, type.value, ) + 1 ) buf = ffi.new("char[]", size) rv = lib.argon2_hash( time_cost, memory_cost, parallelism, ffi.new("uint8_t[]", secret), len(secret), ffi.new("uint8_t[]", salt), len(salt), ffi.NULL, hash_len, buf, size, type.value, version, ) if rv != lib.ARGON2_OK: raise HashingError(error_to_str(rv)) return ffi.string(buf) def hash_secret_raw( secret, salt, time_cost, memory_cost, parallelism, hash_len, type, version=ARGON2_VERSION, ): """ Hash *password* and return a **raw** hash. This function takes the same parameters as :func:`hash_secret`. .. versionadded:: 16.0.0 """ buf = ffi.new("uint8_t[]", hash_len) rv = lib.argon2_hash( time_cost, memory_cost, parallelism, ffi.new("uint8_t[]", secret), len(secret), ffi.new("uint8_t[]", salt), len(salt), buf, hash_len, ffi.NULL, 0, type.value, version, ) if rv != lib.ARGON2_OK: raise HashingError(error_to_str(rv)) return bytes(ffi.buffer(buf, hash_len)) def verify_secret(hash, secret, type): """ Verify whether *secret* is correct for *hash* of *type*. :param bytes hash: An encoded Argon2 hash as returned by :func:`hash_secret`. :param bytes secret: The secret to verify whether it matches the one in *hash*. :param Type type: Type for *hash*. :raises argon2.exceptions.VerifyMismatchError: If verification fails because *hash* is not valid for *secret* of *type*. :raises argon2.exceptions.VerificationError: If verification fails for other reasons. :return: ``True`` on success, raise :exc:`~argon2.exceptions.VerificationError` otherwise. :rtype: bool .. versionadded:: 16.0.0 .. versionchanged:: 16.1.0 Raise :exc:`~argon2.exceptions.VerifyMismatchError` on mismatches instead of its more generic superclass. """ rv = lib.argon2_verify( ffi.new("char[]", hash), ffi.new("uint8_t[]", secret), len(secret), type.value, ) if rv == lib.ARGON2_OK: return True elif rv == lib.ARGON2_VERIFY_MISMATCH: raise VerifyMismatchError(error_to_str(rv)) else: raise VerificationError(error_to_str(rv)) def core(context, type): """ Direct binding to the ``argon2_ctx`` function. .. warning:: This is a strictly advanced function working on raw C data structures. Both Argon2's and ``argon2-cffi``'s higher-level bindings do a lot of sanity checks and housekeeping work that *you* are now responsible for (e.g. clearing buffers). The structure of the *context* object can, has, and will change with *any* release! Use at your own peril; ``argon2-cffi`` does *not* use this binding itself. :param context: A CFFI Argon2 context object (i.e. an ``struct Argon2_Context``/``argon2_context``). :param int type: Which Argon2 variant to use. You can use the ``value`` field of :class:`Type`'s fields. :rtype: int :return: An Argon2 error code. Can be transformed into a string using :func:`error_to_str`. .. versionadded:: 16.0.0 """ return lib.argon2_ctx(context, type) def error_to_str(error): """ Convert an Argon2 error code into a native string. :param int error: An Argon2 error code as returned by :func:`core`. :rtype: str .. versionadded:: 16.0.0 """ msg = ffi.string(lib.argon2_error_message(error)) msg = msg.decode("ascii") return msg argon2-cffi-21.1.0/tests/000077500000000000000000000000001411272701000150255ustar00rootroot00000000000000argon2-cffi-21.1.0/tests/__init__.py000066400000000000000000000000001411272701000171240ustar00rootroot00000000000000argon2-cffi-21.1.0/tests/test_legacy.py000066400000000000000000000072101411272701000177020ustar00rootroot00000000000000import pytest from hypothesis import given from hypothesis import strategies as st from argon2 import ( DEFAULT_RANDOM_SALT_LENGTH, Type, hash_password, hash_password_raw, verify_password, ) from argon2._utils import _encoded_str_len from argon2.exceptions import HashingError, VerificationError from .test_low_level import ( TEST_HASH_I, TEST_HASH_LEN, TEST_MEMORY, TEST_PARALLELISM, TEST_PASSWORD, TEST_SALT, TEST_TIME, i_and_d_encoded, i_and_d_raw, ) class TestHash: def test_hash_defaults(self): """ Calling without arguments works. """ hash_password(b"secret") def test_raw_defaults(self): """ Calling without arguments works. """ hash_password_raw(b"secret") @i_and_d_encoded def test_hash_password(self, type, hash): """ Creates the same encoded hash as the Argon2 CLI client. """ rv = hash_password( TEST_PASSWORD, TEST_SALT, TEST_TIME, TEST_MEMORY, TEST_PARALLELISM, TEST_HASH_LEN, type, ) assert hash == rv assert isinstance(rv, bytes) @i_and_d_raw def test_hash_password_raw(self, type, hash): """ Creates the same raw hash as the Argon2 CLI client. """ rv = hash_password_raw( TEST_PASSWORD, TEST_SALT, TEST_TIME, TEST_MEMORY, TEST_PARALLELISM, TEST_HASH_LEN, type, ) assert hash == rv assert isinstance(rv, bytes) def test_hash_nul_bytes(self): """ Hashing passwords with NUL bytes works as expected. """ rv = hash_password_raw(b"abc\x00", TEST_SALT) assert rv != hash_password_raw(b"abc", TEST_SALT) def test_random_salt(self): """ Omitting a salt, creates a random one. """ rv = hash_password(b"secret") salt = rv.split(b",")[-1].split(b"$")[1] assert ( # -1 for not NUL byte int(_encoded_str_len(DEFAULT_RANDOM_SALT_LENGTH)) - 1 == len(salt) ) def test_hash_wrong_arg_type(self): """ Passing an argument of wrong type raises TypeError. """ with pytest.raises(TypeError): hash_password("oh no, unicode!") def test_illegal_argon2_parameter(self): """ Raises HashingError if hashing fails. """ with pytest.raises(HashingError): hash_password(TEST_PASSWORD, memory_cost=1) @given(st.binary(max_size=128)) def test_hash_fast(self, password): """ Hash various passwords as cheaply as possible. """ hash_password( password, salt=b"12345678", time_cost=1, memory_cost=8, parallelism=1, hash_len=8, ) class TestVerify: @i_and_d_encoded def test_success(self, type, hash): """ Given a valid hash and password and correct type, we succeed. """ assert True is verify_password(hash, TEST_PASSWORD, type) def test_fail_wrong_argon2_type(self): """ Given a valid hash and password and wrong type, we fail. """ with pytest.raises(VerificationError): verify_password(TEST_HASH_I, TEST_PASSWORD, Type.D) def test_wrong_arg_type(self): """ Passing an argument of wrong type raises TypeError. """ with pytest.raises(TypeError): verify_password(TEST_HASH_I, TEST_PASSWORD.decode("ascii")) argon2-cffi-21.1.0/tests/test_low_level.py000066400000000000000000000210421411272701000204250ustar00rootroot00000000000000import binascii import os import pytest from hypothesis import assume, given, settings from hypothesis import strategies as st from argon2.exceptions import ( HashingError, VerificationError, VerifyMismatchError, ) from argon2.low_level import ( ARGON2_VERSION, Type, core, ffi, hash_secret, hash_secret_raw, lib, verify_secret, ) # Example data obtained using the official Argon2 CLI client: # # $ echo -n "password" | ./argon2 somesalt -t 2 -m 16 -p 4 # Type: Argon2i # Iterations: 2 # Memory: 65536 KiB # Parallelism: 4 # Hash: 20c8adf6a90550b08c03f5628b32f9edc9d32ce6b90e254cf5e330a40bcfc2be # Encoded: $argon2i$v=19$m=65536,t=2,p=4$ # c29tZXNhbHQ$IMit9qkFULCMA/ViizL57cnTLOa5DiVM9eMwpAvPwr4 # 0.120 seconds # Verification ok # # $ echo -n "password" | ./argon2 somesalt -t 2 -m 16 -p 4 -d # Type: Argon2d # Iterations: 2 # Memory: 65536 KiB # Parallelism: 4 # Hash: 7199f977eac587e65fb91866da21941a072b5b960b78ceaaecbdef06c766140d # Encoded: $argon2d$v=19$m=65536,t=2,p=4$ # c29tZXNhbHQ$cZn5d+rFh+ZfuRhm2iGUGgcrW5YLeM6q7L3vBsdmFA0 # 0.119 seconds # Verification ok # # Type: Argon2id # Iterations: 2 # Memory: 65536 KiB # Parallelism: 4 # Hash: 1a9677b0afe81fda7b548895e7a1bfeb8668ffc19a530e37e088a668fab1c02a # Encoded: $argon2id$v=19$m=65536,t=2,p=4$ # c29tZXNhbHQ$GpZ3sK/oH9p7VIiV56G/64Zo/8GaUw434IimaPqxwCo # 0.154 seconds # Verification ok TEST_HASH_I_OLD = ( b"$argon2i$m=65536,t=2,p=4" b"$c29tZXNhbHQAAAAAAAAAAA" b"$QWLzI4TY9HkL2ZTLc8g6SinwdhZewYrzz9zxCo0bkGY" ) # a v1.2 hash without a version tag TEST_HASH_I = ( b"$argon2i$v=19$m=65536,t=2,p=4$" b"c29tZXNhbHQ$IMit9qkFULCMA/ViizL57cnTLOa5DiVM9eMwpAvPwr4" ) TEST_HASH_D = ( b"$argon2d$v=19$m=65536,t=2,p=4$" b"c29tZXNhbHQ$cZn5d+rFh+ZfuRhm2iGUGgcrW5YLeM6q7L3vBsdmFA0" ) TEST_HASH_ID = ( b"$argon2id$v=19$m=65536,t=2,p=4$" b"c29tZXNhbHQ$GpZ3sK/oH9p7VIiV56G/64Zo/8GaUw434IimaPqxwCo" ) TEST_RAW_I = binascii.unhexlify( b"20c8adf6a90550b08c03f5628b32f9edc9d32ce6b90e254cf5e330a40bcfc2be" ) TEST_RAW_D = binascii.unhexlify( b"7199f977eac587e65fb91866da21941a072b5b960b78ceaaecbdef06c766140d" ) TEST_RAW_ID = binascii.unhexlify( b"1a9677b0afe81fda7b548895e7a1bfeb8668ffc19a530e37e088a668fab1c02a" ) TEST_PASSWORD = b"password" TEST_SALT_LEN = 16 TEST_SALT = b"somesalt" TEST_TIME = 2 TEST_MEMORY = 65536 TEST_PARALLELISM = 4 TEST_HASH_LEN = 32 i_and_d_encoded = pytest.mark.parametrize( "type,hash", [(Type.I, TEST_HASH_I), (Type.D, TEST_HASH_D), (Type.ID, TEST_HASH_ID)], ) i_and_d_raw = pytest.mark.parametrize( "type,hash", [(Type.I, TEST_RAW_I), (Type.D, TEST_RAW_D), (Type.ID, TEST_RAW_ID)], ) both_hash_funcs = pytest.mark.parametrize( "func", [hash_secret, hash_secret_raw] ) class TestHash: @i_and_d_encoded def test_hash_secret(self, type, hash): """ Creates the same encoded hash as the Argon2 CLI client. """ rv = hash_secret( TEST_PASSWORD, TEST_SALT, TEST_TIME, TEST_MEMORY, TEST_PARALLELISM, TEST_HASH_LEN, type, ) assert hash == rv assert isinstance(rv, bytes) @i_and_d_raw def test_hash_secret_raw(self, type, hash): """ Creates the same raw hash as the Argon2 CLI client. """ rv = hash_secret_raw( TEST_PASSWORD, TEST_SALT, TEST_TIME, TEST_MEMORY, TEST_PARALLELISM, TEST_HASH_LEN, type, ) assert hash == rv assert isinstance(rv, bytes) def test_hash_nul_bytes(self): """ Hashing secrets with NUL bytes works as expected. """ params = ( TEST_SALT, TEST_TIME, TEST_MEMORY, TEST_PARALLELISM, TEST_HASH_LEN, Type.I, ) rv = hash_secret_raw(b"abc\x00", *params) assert rv != hash_secret_raw(b"abc", *params) @both_hash_funcs def test_hash_wrong_arg_type(self, func): """ Passing an argument of wrong type raises TypeError. """ with pytest.raises(TypeError): func("oh no, unicode!") @both_hash_funcs def test_illegal_argon2_parameter(self, func): """ Raises HashingError if hashing fails. """ with pytest.raises(HashingError): func( TEST_PASSWORD, TEST_SALT, TEST_TIME, 1, TEST_PARALLELISM, TEST_HASH_LEN, Type.I, ) @both_hash_funcs @given(st.binary(max_size=128)) def test_hash_fast(self, func, secret): """ Hash various secrets as cheaply as possible. """ hash_secret( secret, salt=b"12345678", time_cost=1, memory_cost=8, parallelism=1, hash_len=8, type=Type.I, ) class TestVerify: @i_and_d_encoded def test_success(self, type, hash): """ Given a valid hash and secret and correct type, we succeed. """ assert True is verify_secret(hash, TEST_PASSWORD, type) @i_and_d_encoded def test_fail(self, type, hash): """ Wrong password fails. """ with pytest.raises(VerifyMismatchError): verify_secret(hash, bytes(reversed(TEST_PASSWORD)), type) def test_fail_wrong_argon2_type(self): """ Given a valid hash and secret and wrong type, we fail. """ verify_secret(TEST_HASH_D, TEST_PASSWORD, Type.D) verify_secret(TEST_HASH_I, TEST_PASSWORD, Type.I) with pytest.raises(VerificationError): verify_secret(TEST_HASH_I, TEST_PASSWORD, Type.D) def test_wrong_arg_type(self): """ Passing an argument of wrong type raises TypeError. """ with pytest.raises(TypeError) as e: verify_secret(TEST_HASH_I, TEST_PASSWORD.decode("ascii"), Type.I) assert e.value.args[0].startswith( "initializer for ctype 'uint8_t[]' must be a" ) def test_old_hash(self): """ Hashes without a version tag are recognized and verified correctly. """ assert True is verify_secret(TEST_HASH_I_OLD, TEST_PASSWORD, Type.I) @given( password=st.binary(min_size=lib.ARGON2_MIN_PWD_LENGTH, max_size=65), time_cost=st.integers(lib.ARGON2_MIN_TIME, 3), parallelism=st.integers(lib.ARGON2_MIN_LANES, 5), memory_cost=st.integers(0, 1025), hash_len=st.integers(lib.ARGON2_MIN_OUTLEN, 513), salt_len=st.integers(lib.ARGON2_MIN_SALT_LENGTH, 513), ) @settings(deadline=None) def test_argument_ranges( password, time_cost, parallelism, memory_cost, hash_len, salt_len ): """ Ensure that both hashing and verifying works for most combinations of legal values. Limits are intentionally chosen to be *not* on 2^x boundaries. This test is rather slow. """ assume(parallelism * 8 <= memory_cost) hash = hash_secret( secret=password, salt=os.urandom(salt_len), time_cost=time_cost, parallelism=parallelism, memory_cost=memory_cost, hash_len=hash_len, type=Type.I, ) assert verify_secret(hash, password, Type.I) def test_core(): """ If called with equal parameters, core() will return the same as hash_secret(). """ pwd = b"secret" salt = b"12345678" hash_len = 8 # Keep FFI objects alive throughout the function. cout = ffi.new("uint8_t[]", hash_len) cpwd = ffi.new("uint8_t[]", pwd) csalt = ffi.new("uint8_t[]", salt) ctx = ffi.new( "argon2_context *", dict( out=cout, outlen=hash_len, version=ARGON2_VERSION, pwd=cpwd, pwdlen=len(pwd), salt=csalt, saltlen=len(salt), secret=ffi.NULL, secretlen=0, ad=ffi.NULL, adlen=0, t_cost=1, m_cost=8, lanes=1, threads=1, allocate_cbk=ffi.NULL, free_cbk=ffi.NULL, flags=lib.ARGON2_DEFAULT_FLAGS, ), ) rv = core(ctx, Type.D.value) assert 0 == rv assert ( hash_secret_raw( pwd, salt=salt, time_cost=1, memory_cost=8, parallelism=1, hash_len=hash_len, type=Type.D, ) == bytes(ffi.buffer(ctx.out, ctx.outlen)) ) argon2-cffi-21.1.0/tests/test_password_hasher.py000066400000000000000000000065601411272701000216410ustar00rootroot00000000000000import pytest from argon2 import PasswordHasher, Type, extract_parameters from argon2._password_hasher import _ensure_bytes from argon2.exceptions import InvalidHash class TestEnsureBytes: def test_is_bytes(self): """ Bytes are just returned. """ s = "föö".encode() rv = _ensure_bytes(s, "doesntmatter") assert isinstance(rv, bytes) assert s == rv def test_is_unicode(self): """ Unicode is encoded using the specified encoding. """ s = "föö" rv = _ensure_bytes(s, "latin1") assert isinstance(rv, bytes) assert s.encode("latin1") == rv bytes_and_unicode_password = pytest.mark.parametrize( "password", ["pässword".encode("latin1"), "pässword"] ) class TestPasswordHasher: @bytes_and_unicode_password def test_hash(self, password): """ Hashing works with unicode and bytes. Uses correct parameters. """ ph = PasswordHasher(1, 8, 1, 16, 16, "latin1") h = ph.hash(password) prefix = "$argon2id$v=19$m=8,t=1,p=1$" assert isinstance(h, str) assert h[: len(prefix)] == prefix @bytes_and_unicode_password def test_verify_agility(self, password): """ Verification works with unicode and bytes and variant is correctly detected. """ ph = PasswordHasher(1, 8, 1, 16, 16, "latin1") hash = ( # handrolled artisanal test vector "$argon2i$m=8,t=1,p=1$" "bL/lLsegFKTuR+5vVyA8tA$VKz5CHavCtFOL1N5TIXWSA" ) assert ph.verify(hash, password) @bytes_and_unicode_password def test_hash_verify(self, password): """ Hashes are valid and can be verified. """ ph = PasswordHasher() assert ph.verify(ph.hash(password), password) is True def test_check(self): """ Raises a helpful TypeError on wrong arguments. """ with pytest.raises(TypeError) as e: PasswordHasher("1") assert "'time_cost' must be a int (got str)." == e.value.args[0] def test_verify_invalid_hash(self): """ If the hash can't be parsed, InvalidHash is raised. """ with pytest.raises(InvalidHash): PasswordHasher().verify("tiger", "does not matter") def test_check_needs_rehash_no(self): """ Return False if the hash has the correct parameters. """ ph = PasswordHasher(1, 8, 1, 16, 16) assert not ph.check_needs_rehash(ph.hash("foo")) def test_check_needs_rehash_yes(self): """ Return True if any of the parameters changes. """ ph = PasswordHasher(1, 8, 1, 16, 16) ph_old = PasswordHasher(1, 8, 1, 8, 8) assert ph.check_needs_rehash(ph_old.hash("foo")) def test_type_is_configurable(self): """ Argon2id is default but can be changed. """ ph = PasswordHasher(time_cost=1, memory_cost=64) default_hash = ph.hash("foo") assert Type.ID is ph.type is ph._parameters.type assert Type.ID is extract_parameters(default_hash).type ph = PasswordHasher(time_cost=1, memory_cost=64, type=Type.I) assert Type.I is ph.type is ph._parameters.type assert Type.I is extract_parameters(ph.hash("foo")).type assert ph.check_needs_rehash(default_hash) argon2-cffi-21.1.0/tests/test_utils.py000066400000000000000000000071501411272701000176010ustar00rootroot00000000000000from base64 import b64encode import pytest from hypothesis import given from hypothesis import strategies as st from argon2 import Parameters, Type, extract_parameters from argon2._utils import NoneType, _check_types, _decoded_str_len from argon2.exceptions import InvalidHash class TestCheckTypes: def test_success(self): """ Returns None if all types are okay. """ assert None is _check_types( bytes=(b"bytes", bytes), tuple=((1, 2), tuple), str_or_None=(None, (str, NoneType)), ) def test_fail(self): """ Returns summary of failures. """ rv = _check_types( bytes=("not bytes", bytes), str_or_None=(42, (str, NoneType)) ) assert "." == rv[-1] # proper grammar FTW assert "'str_or_None' must be a str, or NoneType (got int)" in rv assert "'bytes' must be a bytes (got str)" in rv @given(st.binary()) def test_decoded_str_len(bs): """ _decoded_str_len computes the resulting length. """ assert len(bs) == _decoded_str_len(len(b64encode(bs).rstrip(b"="))) VALID_HASH = ( "$argon2id$v=19$m=65536,t=2,p=4$" "c29tZXNhbHQ$GpZ3sK/oH9p7VIiV56G/64Zo/8GaUw434IimaPqxwCo" ) VALID_PARAMETERS = Parameters( type=Type.ID, salt_len=8, hash_len=32, version=19, memory_cost=65536, time_cost=2, parallelism=4, ) VALID_HASH_V18 = ( "$argon2i$m=8,t=1,p=1$c29tZXNhbHQ$gwQOXSNhxiOxPOA0+PY10P9QFO" "4NAYysnqRt1GSQLE55m+2GYDt9FEjPMHhP2Cuf0nOEXXMocVrsJAtNSsKyfg" ) VALID_PARAMETERS_V18 = Parameters( type=Type.I, salt_len=8, hash_len=64, version=18, memory_cost=8, time_cost=1, parallelism=1, ) class TestExtractParameters: def test_valid_hash(self): """ A valid hash is parsed. """ parsed = extract_parameters(VALID_HASH) assert VALID_PARAMETERS == parsed def test_valid_hash_v18(self): """ A valid Argon v1.2 hash is parsed. """ parsed = extract_parameters(VALID_HASH_V18) assert VALID_PARAMETERS_V18 == parsed @pytest.mark.parametrize( "hash", [ "", "abc" + VALID_HASH, VALID_HASH.replace("p=4", "p=four"), VALID_HASH.replace(",p=4", ""), ], ) def test_invalid_hash(self, hash): """ Invalid hashes of various types raise an InvalidHash error. """ with pytest.raises(InvalidHash): extract_parameters(hash) class TestParameters: def test_eq(self): """ Parameters are iff every attribute is equal. """ assert VALID_PARAMETERS == VALID_PARAMETERS assert not VALID_PARAMETERS != VALID_PARAMETERS def test_eq_wrong_type(self): """ Parameters are only compared if they have the same type. """ assert VALID_PARAMETERS != "foo" assert not VALID_PARAMETERS == object() def test_repr(self): """ __repr__ returns s ensible string. """ assert repr( Parameters( type=Type.ID, salt_len=8, hash_len=32, version=19, memory_cost=65536, time_cost=2, parallelism=4, ) ) in [ ", version=19, hash_len=32, " "salt_len=8, time_cost=2, memory_cost=65536, parallelism=4)>", "", ] argon2-cffi-21.1.0/tox.ini000066400000000000000000000042261411272701000152020ustar00rootroot00000000000000[flake8] exclude = src/argon2/_ffi.py ignore = # Ambiguous variable names # Ignored, since there is an enum value "I" for the algorithm type Argon2I E741 # Not an actual PEP8 violation W503 # Black vs flake8 conflict E203 [gh-actions] python = 3.5: py35 3.6: py36 3.7: py37, docs 3.8: py38, lint 3.9: py39, manifest 3.10: py310 pypy3: pypy3 [tox] envlist = lint,py35,py36,py37,py38,py39,py310,pypy3,system-argon2,docs,manifest,pypi-description,coverage-report isolated_build = true [testenv:lint] description = Run all pre-commit hooks. basepython = python3.8 skip_install = true deps = pre-commit passenv = HOMEPATH # needed on Windows commands = pre-commit run --all-files --show-diff [testenv] description = Run tests and measure coverage. extras = tests commands = coverage run --parallel -m pytest {posargs} coverage run --parallel -m argon2 -n 1 -t 1 -m 8 -p 1 [testenv:system-argon2] description = Run tests against bindings that use a system installation of Argon2. basepython = python3.8 setenv = ARGON2_CFFI_USE_SYSTEM=1 extras = tests install_command = pip install {opts} --no-binary=argon2-cffi {packages} commands = python -m pytest {posargs} python -m argon2 -n 1 -t 1 -m 8 -p 1 [testenv:docs] description = Build docs and run doctests. # Keep basepython in sync with gh-actions and .readthedocs.yml. basepython = python3.7 extras = docs commands = python -m doctest README.rst sphinx-build -W -b html -d {envtmpdir}/doctrees docs docs/_build/html sphinx-build -W -b doctest -d {envtmpdir}/doctrees docs docs/_build/html [testenv:manifest] description = Ensure MANIFEST.in is up to date. deps = check-manifest skip_install = true commands = check-manifest [testenv:pypi-description] description = Ensure README.rst renders on PyPI. skip_install = true deps = twine pip >= 18.0.0 commands = pip wheel -w {envtmpdir}/build --no-deps . twine check {envtmpdir}/build/* [testenv:coverage-report] description = Report coverage over all test runs. basepython = python3.8 deps = coverage[toml]>=5.0.2 skip_install = true commands = coverage combine coverage report