argon2_cffi¶
Release v16.0.0 (What’s new?).
Argon2 won the Password Hashing Competition and argon2_cffi
is the simplest way to use it in Python and PyPy:
>>> from argon2 import PasswordHasher
>>> ph = PasswordHasher()
>>> hash = ph.hash("secret")
>>> hash
'$argon2i$m=512,t=2,p=2$c29tZXNhbHQ$2IdoNVglVTxb9w4YVJqW8w'
>>> ph.verify(hash, "secret")
True
>>> ph.verify(hash, "wrong")
Traceback (most recent call last):
...
argon2.exceptions.VerificationError: Decoding failed
argon2_cffi
’s documentation lives at Read the Docs, the code on GitHub.
It’s rigorously tested on Python 2.6, 2.7, 3.3+, and PyPy.
User’s Guide¶
Argon2¶
Note
TL;DR: Use 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 two 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.
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 GPUs and ASICs 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.
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.
Installation¶
Generally speaking,
pip install argon2_cffi
should be all it takes.
But since Argon2 (the C library) isn’t packaged on any major distribution yet, argon2_cffi
vendors its C code which depending on the platform can lead to complications.
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:
pip install -U cffi pip setuptools
OS X & Windows¶
Binary wheels are provided on PyPI.
With a recent-enough pip
and setuptools
, they should be used automatically.
Linux¶
A working C compiler and CFFI environment is required.
If you’ve been able to compile Python CFFI extensions before, argon2_cffi
should install without any problems.
API Reference¶
argon2_cffi
comes with an high-level API and hopefully reasonable defaults for Argon2 parameters that result in a verification time of between 0.5ms and 1ms on recent-ish hardware.
Unless you have any special needs, all you need to know is:
>>> from argon2 import PasswordHasher
>>> ph = PasswordHasher()
>>> hash = ph.hash("s3kr3tp4ssw0rd")
>>> hash
u'$argon2i$m=512,t=2,p=2$0FFfEeL6JmUnpxwgwcSC8g$98BmZUa5A/3t5wb3ZxFLBg'
>>> ph.verify(hash, "s3kr3tp4ssw0rd")
True
>>> ph.verify(hash, "t0t411ywr0ng")
Traceback (most recent call last):
...
argon2.exceptions.VerificationError: Decoding failed
But of course the PasswordHasher
class has all the parametrization you’ll need:
-
class
argon2.
PasswordHasher
(time_cost=2, memory_cost=512, parallelism=2, hash_len=16, salt_len=16, encoding='utf-8')¶ High level class to hash passwords with sensible defaults.
Uses always Argon2i and a random salt.
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.
Parameters: - time_cost (int) – Defines the amount of computation realized and therefore the execution time, given in number of iterations.
- memory_cost (int) – Defines the memory usage, given in kibibytes.
- parallelism (int) – Defines the number of parallel threads (changes the resulting hash value).
- hash_len (int) – Length of the hash in bytes.
- salt_len (int) – Length of random salt to be generated for each password.
- encoding (str) – The Argon2 C library expects bytes. So if
hash()
orverify()
are passed an unicode string, it will be encoded using this encoding.
New in version 16.0.0.
-
hash
(password)¶ Hash password and return an encoded hash.
Parameters: password ( bytes
orunicode
) – Password to hash.Raises: argon2.exceptions.HashingError – If hashing fails. Return type: unicode
-
verify
(hash, password)¶ Verify that password matches hash.
Parameters: - hash (unicode) – An encoded hash as returned from
PasswordHasher.hash()
. - password (
bytes
orunicode
) – The password to verify.
Raises: argon2.exceptions.VerificationError – If verification fails.
Returns: True
on success, raiseVerificationError
otherwise.Return type: - hash (unicode) – An encoded hash as returned from
If you don’t specify any parameters, the following constants are used:
-
argon2.
DEFAULT_RANDOM_SALT_LENGTH
¶
-
argon2.
DEFAULT_HASH_LENGTH
¶
-
argon2.
DEFAULT_TIME_COST
¶
-
argon2.
DEFAULT_MEMORY_COST
¶
-
argon2.
DEFAULT_PARALLELISM
¶
You can see their values in PasswordHasher
.
Exceptions¶
-
exception
argon2.exceptions.
VerificationError
¶ Raised if verification failed.
You can find the original error message from Argon2 in
args[0]
.
-
exception
argon2.exceptions.
HashingError
¶ Raised if hashing failed.
You can find the original error message from Argon2 in
args[0]
.
Low Level¶
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.
-
class
argon2.low_level.
Type
¶ Enum of Argon2 variants.
-
D
= 0¶ 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.
-
I
= 1¶ 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.
-
-
argon2.low_level.
hash_secret
(secret, salt, time_cost, memory_cost, parallelism, hash_len, type)¶ Hash secret and return an encoded hash.
An encoded hash can be directly passed into
verify_secret()
as it contains all parameters and the salt.Parameters: For an explanation of the Argon2 parameters see
PasswordHasher
.Return type: bytes Raises: argon2.exceptions.HashingError – If hashing fails. New in version 16.0.0.
>>> 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$m=8,t=1,p=1$c29tZXNhbHQ$H0oN1/L3H8t8hcg47pAyJZ8toBh2UbgcMt0zRFrqt4mEJCeKSEWGxt+KpZrMwxvr7M5qktNcc/bk/hvbinueJA'
-
argon2.low_level.
verify_secret
(hash, secret, type)¶ Verify whether secret is correct for hash of type.
Parameters: - hash (bytes) – An encoded Argon2 hash as returned by
hash_secret()
. - secret (bytes) – The secret to verify whether it matches the one in hash.
- type (Type) – Type for hash.
Raises: argon2.exceptions.VerificationError – If verification fails.
Returns: True
on success, raiseVerificationError
otherwise.Return type: - hash (bytes) – An encoded Argon2 hash as returned by
The raw hash can also be computed:
-
argon2.low_level.
hash_secret_raw
(secret, salt, time_cost, memory_cost, parallelism, hash_len, type)¶ Hash password and return a raw hash.
This function takes the same parameters as
hash_secret()
.
>>> argon2.low_level.hash_password_raw(b"secret", b"somesalt")
b'\xd8\x87h5X%U<[\xf7\x0e\x18T\x9a\x96\xf3'
The super low-level argon2_core()
function is exposed too if you need access to very specific options:
-
argon2.low_level.
core
(context, type)¶ Direct binding to the Argon2
core
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).Use at your own peril;
argon2_cffi
does not use this binding itself.Parameters: Return type: Returns: An Argon2 error code. Can be transformed into a string using
error_to_str()
.New in version 16.0.0.
In order to use 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:
>>> from argon2.low_level import 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(
... 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
<cdata 'struct Argon2_Context *' owning 120 bytes>
>>> core(ctx, Type.D.value)
0
>>> out = bytes(ffi.buffer(ctx.out, ctx.outlen))
>>> out
b'j\x9ap\xb4\xe7\xd6\x9c\xcf'
>>> 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.
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 (argon2.PasswordHasher
) and a low-level (argon2.low_level
) solution.
There are no immediate plans to remove them though.
-
argon2.
hash_password
(password, salt=None, time_cost=2, memory_cost=512, parallelism=2, hash_len=16, type=<Type.I: 1>)¶ Legacy alias for
hash_secret()
with default parameters.Deprecated since version 16.0.0: Use
argon2.PasswordHasher
for passwords.
-
argon2.
hash_password_raw
(password, salt=None, time_cost=2, memory_cost=512, parallelism=2, hash_len=16, type=<Type.I: 1>)¶ Legacy alias for
hash_secret_raw()
with default parameters.Deprecated since version 16.0.0: Use
argon2.PasswordHasher
for passwords.
-
argon2.
verify_password
(hash, password, type=<Type.I: 1>)¶ Legacy alias for
verify_secret()
with default parameters.Deprecated since version 16.0.0: Use
argon2.PasswordHasher
for passwords.
Choosing Parameters¶
Note
You can probably just use argon2.PasswordHasher
with its default values and be fine.
Only tweak these if you’ve determined using CLI that these 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 but it should be noted that they also mention that no value for time_cost
or memory_cost
is actually insecure (cf. section 6.4).
- Choose whether you want Argon2i or Argon2d (
type
). If you don’t know what that means, choose Argon2i (argon2.Type.I
). - Figure out how many threads can be used on each call to Argon2 (
parallelism
). They recommend twice as many as the number of cores dedicated to hashing passwords. - Figure out how much memory each call can afford (
memory_cost
). - Choose a salt length. 16 Bytes are fine.
- Choose a hash length (
hash_len
). 16 Bytes are fine. - Figure out how long each call can take. One recommendation for concurent user logins is to keep it under 0.5ms.
- Measure the time for hashing using your chosen parameters.
Find a
time_cost
that is within your accounted time. Iftime_cost=1
takes too long, lowermemory_cost
.
argon2_cffi
’s CLI will help you with this process.
CLI¶
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:
$ python -m argon2 -t 1 -m 512 -p 2
Running Argon2i 100 times with:
hash_len: 16
memory_cost: 512
parallelism: 2
time_cost: 1
Measuring...
0.418ms per password verification
This should make it much easier to determine the right parameters for your use case and your environment.
Frequently Asked Questions¶
- I’m using
bcrypt
/scrypt
/PBKDF2
, 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, pick Argon2 because it’s a 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.
Project Information¶
Backward 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
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 CLI.
How To Contribute¶
Every open source project lives from the generous help by contributors that sacrifice their time and argon2_cffi
is no different.
Here are a few guidelines to get you started:
- Try to limit each pull request to one change only.
- 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 on Travis CI.
If you lack some Python version, you can can always limit the environments like
tox -e py27,py35
(in that case you may want to look into pyenv that makes it very easy to install many different Python versions in parallel). - Make sure your changes pass our CI. You won’t get any feedback until it’s green unless you ask for it.
- If you address review feedback, make sure to bump the pull request. Maintainers don’t receive notifications if you push new commits.
- If your change is noteworthy, add an entry to the changelog. Use present tense, semantic newlines, and add link to your pull request.
- No contribution is too small; please submit as many fixes for typos and grammar bloopers as you can!
- Don’t break backward compatibility.
- Always add tests and docs for your code. This is a hard rule; patches with missing tests or documentation won’t be merged.
- Write good test docstrings.
- Obey PEP 8 and PEP 257.
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!
Contributor Code of Conduct¶
As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality.
Examples of unacceptable behavior by participants include:
- The use of sexualized language or imagery
- Personal attacks
- Trolling or insulting/derogatory comments
- Public or private harassment
- Publishing other’s private information, such as physical or electronic addresses, without explicit permission
- Other unethical or unprofessional conduct
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.
By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect of managing this project. Project maintainers who do not follow or enforce the Code of Conduct may be permanently removed from the project team.
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community.
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting a project maintainer 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. Maintainers are obligated to maintain confidentiality with regard to the reporter of an incident.
This Code of Conduct is adapted from the Contributor Covenant, version 1.3.0, available at http://contributor-covenant.org/version/1/3/0/.
Changelog¶
Versions are year-based with a strict backward compatibility policy. The third digit is only for regressions.
16.0.0 (2016-01-02)¶
Vendoring argon2
@ 421dafd2a8af5cbb215e16da5953663eb101d139.
Deprecations:¶
hash_password()
,hash_password_raw()
, andverify_password()
should not be used anymore. For hashing passwords, use the newargon2.PasswordHasher
. If you want to implement your own higher-level abstractions, use the new low-level APIshash_secret()
,hash_secret_raw()
, andverify_secret()
from theargon2.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 passedNone
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 ashash_password()
such thatverify_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.
Credits & 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.
msinttypes¶
In order to be able to compile on Visual Studio 2008 and Visual Studio 2010 which are required for Python 2.6/2.7 and 3.3/3.4 respectively, we also ship two C headers with integer types. They are from the msinttypes project (auto-import on GitHub) and licensed under New BSD:
Copyright (c) 2006-2013 Alexander Chemeris
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
- Neither the name of the product nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ‘’AS IS’’ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.