BCrypt — Passlib v1.7.4 Documentation (2024)

BCrypt was developed to replace md5_crypt for BSD systems.It uses a modified version of the Blowfish stream cipher. Featuringa large salt and variable number of rounds, it’s currently the defaultpassword hash for many systems (notably BSD), and has no known weaknesses.It is one of the four hashes Passlib recommendsfor new applications. This class can be used directly as follows:

>>> from passlib.hash import bcrypt>>> # generate new salt, hash password>>> h = bcrypt.hash("password")>>> h'$2a$12$NT0I31Sa7ihGEWpka9ASYrEFkhuTNeBQ2xfZskIiiJeyFXhRgS.Sy'>>> # the same, but with an explicit number of rounds>>> bcrypt.using(rounds=13).hash("password")'$2b$13$HMQTprwhaUwmir.g.ZYoXuRJhtsbra4uj.qJPHrKsX5nGlhpts0jm'>>> # verify password>>> bcrypt.verify("password", h)True>>> bcrypt.verify("wrong", h)False

Note

It is strongly recommended that you installbcryptwhen using this hash.

See also

the generic PasswordHash usage examples

Interface

class passlib.hash.bcrypt

This class implements the BCrypt password hash, and follows the PasswordHash API.

It supports a fixed-length salt, and a variable number of rounds.

The using() method accepts the following optional keywords:

Parameters:
  • salt (str) – Optional salt string.If not specified, one will be autogenerated (this is recommended).If specified, it must be 22 characters, drawn from the regexp range [./0-9A-Za-z].
  • rounds (int) – Optional number of rounds to use.Defaults to 12, must be between 4 and 31, inclusive.This value is logarithmic, the actual number of iterations used will be 2**rounds– increasing the rounds by +1 will double the amount of time taken.
  • ident (str) –

    Specifies which version of the BCrypt algorithm will be used when creating a new hash.Typically this option is not needed, as the default ("2b") is usually the correct choice.If specified, it must be one of the following:

    • "2" - the first revision of BCrypt, which suffers from a minor security flaw and is generally not used anymore.
    • "2a" - some implementations suffered from rare security flaws, replaced by 2b.
    • "2y" - format specific to the crypt_blowfish BCrypt implementation,identical to "2b" in all but name.
    • "2b" - latest revision of the official BCrypt algorithm, current default.
  • truncate_error (bool) –

    By default, BCrypt will silently truncate passwords larger than 72 bytes.Setting truncate_error=True will cause hash()to raise a PasswordTruncateError instead.

    New in version 1.7.

  • relaxed (bool) –

    By default, providing an invalid value for one of the otherkeywords will result in a ValueError. If relaxed=True,and the error can be corrected, a PasslibHashWarningwill be issued instead. Correctable errors include roundsthat are too small or too large, and salt strings that are too long.

    New in version 1.6.

Changed in version 1.6: This class now supports "2y" hashes, and recognizes(but does not support) the broken "2x" hashes.(see the crypt_blowfish bugfor details).

Changed in version 1.6: Added a pure-python backend.

Changed in version 1.6.3: Added support for "2b" variant.

Changed in version 1.7: Now defaults to "2b" variant.

Bcrypt Backends

Warning

Support for py-bcrypt and bcryptor will be dropped in Passlib 1.8,as these libraries are unmaintained.

This class will use the first available of five possible backends:

  1. bcrypt, if installed.
  2. py-bcrypt, if installed (DEPRECATED)
  3. bcryptor, if installed (DEPRECATED).
  4. stdlib’s crypt.crypt(), if the host OS supports BCrypt(primarily BSD-derived systems).
  5. A pure-python implementation of BCrypt, built into Passlib.

If no backends are available, hash() and verify()will throw MissingBackendError when they are invoked.You can check which backend is in use by calling bcrypt.get_backend().

As of Passlib 1.6.3, a one-time check is peformed when the backend is first loaded,to detect the backend’s capabilities & bugs. If this check detects a fatal bug,a PasslibSecurityError will be raised. This generally meansyou need to upgrade the external package being used as the backend(this will be detailed in the error message).

Warning

The pure-python backend (#5) is disabled by default!

That backend is currently too slow to be usable given the number of rounds requiredfor security. That said, if you have no other alternative and need to use it,set the environmental variable PASSLIB_BUILTIN_BCRYPT="enabled"before importing Passlib.

What’s “too slow”? Passlib’s rounds selection guidelinescurrently require BCrypt be able to do at least 12 cost in under 300ms. By this standardthe pure-python backend is 128x too slow under CPython 2.7, and 16x too slow under PyPy 1.8.(speedups are welcome!)

Format & Algorithm

Bcrypt is compatible with the Modular Crypt Format, and uses a number of identifyingprefixes: $2$, $2a$, $2x$, $2y$, and $2b$. Each prefix indicatesa different revision of the BCrypt algorithm; and all but the $2b$ identifier areconsidered deprecated.

An example hash (of password) is:

$2b$12$GhvMmNVjRW29ulnudl.LbuAnUtN/LRfe1JsBm1Xu6LE3059z5Tr8m

Bcrypt hashes have the format $2a$rounds$saltchecksum, where:

  • rounds is a cost parameter, encoded as 2 zero-padded decimal digits,which determines the number of iterations used via iterations=2**rounds (rounds is 12 in the example).
  • salt is a 22 character salt string, using the characters in the regexp range [./A-Za-z0-9] (GhvMmNVjRW29ulnudl.Lbu in the example).Note that due to padding bits within the encoding, the last character should always be one of [.Oeu]:under some bcrypt implementations, other final characters may result in false negatives when verifying.
  • checksum is a 31 character checksum, using the same characters as the salt (AnUtN/LRfe1JsBm1Xu6LE3059z5Tr8m in the example).

While BCrypt’s basic algorithm is described in its design document [1],the OpenBSD implementation [2] is considered the canonical reference, eventhough it differs from the design document in a few small ways.

Security Issues

  • Password Truncation.

    While not a security issue per-se, bcrypt does have one major limitation:password are truncated on the first NULL byte (if any),and only the first 72 bytes of a password are hashed… all the rest are ignored.Furthermore, bytes 55-72 are not fully mixed into the resulting hash (citation needed!).To work around both these issues, many applications first run the password through a messagedigest such as (HMAC-) SHA2-256. Passlib offers the premade passlib.hash.bcrypt_sha256 - BCrypt+SHA256to take care of this issue.

Deviations

This implementation of bcrypt differs from others in a few ways:

  • Restricted salt string character set:

    BCrypt does not specify what the behavior should be whenpassed a salt string outside of the regexp range [./A-Za-z0-9].In order to avoid this situation, Passlib strictly limits salts to theallowed character set, and will throw a ValueError if an invalidsalt character is encountered.

  • Unicode Policy:

    The underlying algorithm takes in a password specifiedas a series of non-null bytes, and does not specify what encodingshould be used; though a us-ascii compatible encodingis implied by nearly all implementations of bcryptas well as all known reference hashes.

    In order to provide support for unicode strings,Passlib will encode unicode passwords using utf-8before running them through bcrypt. If a differentencoding is desired by an application, the password should be encodedbefore handing it to Passlib.

  • Padding Bits

    BCrypt’s base64 encoding results in the last character of the saltencoding only 2 bits of data, the remaining 4 are “padding” bits.Similarly, the last character of the digest contains 4 bits of data,and 2 padding bits. Because of the way they are coded, many BCrypt implementationswill reject all passwords if these padding bits are not set to 0.Due to a legacy issue with Passlib <= 1.5.2,Passlib will print a warning if it encounters hashes with any padding bits set,and then validate the hash as if the padding bits were cleared.(This behavior will eventually be deprecated and such hasheswill throw a ValueError instead).

  • The crypt_blowfish 8-bit bug

    Pre-1.1 versions of the crypt_blowfishbcrypt implementation suffered from a serious flaw [3]in how they handled 8-bit passwords. The manner in which the flaw was fixed resultedin crypt_blowfish adding support for two new BCrypt hash identifiers:

    $2x$, allowing sysadmins to mark any $2a$ hashes which were potentiallygenerated with the buggy algorithm. Passlib 1.6 recognizes (but does notcurrently support generating or verifying) these hashes.

    $2y$, the default for crypt_blowfish 1.1-1.2, indicatesthe hash was generated with the canonical OpenBSD-compatible algorithm,and should match correctly generated $2a$ hashes.Passlib 1.6 can generate and verify these hashes.

    As well, crypt_blowfish 1.2 modified the way it generates $2a$ hashes,so that passwords containing the byte value 0xFF are hashed in a mannerincompatible with either the buggy or canonical algorithms. Passlibdoes not support this algorithmic variant either, though it shouldbe very rarely encountered in practice.

    (crypt_blowfish 1.3 switched to the $2b$ standard as the default)

    Changed in version 1.6.3: Passlib will now throw a PasslibSecurityError if an attempt ismade to use any backend which is vulnerable to this bug.

  • The ‘BSD wraparound’ bug

    OpenBSD <= 5.4, and most bcrypt libraries derived from it’s source,are vulnerable to a ‘wraparound’ bug [4], where passwords largerthan 254 characters will be incorrectly hashed using only the first fewcharacters of the string, resulting in a severely weakened hash.

    OpenBSD 5.5 fixed this flaw,and introduced the $2b$ hash identifier to indicate the hash was generated with the correctalgorithm.

    py-bcrypt <= 0.4 is known to be vulnerable to this, as well as the os_cryptbackend (if running on a vulnerable operating system).

    Passlib 1.6.3 adds the following:

    • Support for the $2b$ hash format (though for backward compat it has not been madethe default yet).
    • Detects if the active backend is vulnerable to the bug, issues a warning,and enables a workaround so that vulnerable passwords will still be hashed correctly.(This does mean that existing hashes suffering this vulnerability will no longer verifyusing their correct password).

Footnotes

[1]the bcrypt format specification -http://www.usenix.org/event/usenix99/provos/provos_html/
[2]the OpenBSD BCrypt source -http://www.openbsd.org/cgi-bin/cvsweb/src/lib/libc/crypt/bcrypt.c
[3]The flaw in pre-1.1 crypt_blowfish is described here -CVE-2011-2483
[4]The wraparound flaw is described here -http://www.openwall.com/lists/oss-security/2012/01/02/4
BCrypt — Passlib v1.7.4 Documentation (2024)

FAQs

What is the difference between bcrypt and Passlib? ›

BCrypt does not specify what the behavior should be when passed a salt string outside of the regexp range [./A-Za-z0-9] . In order to avoid this situation, Passlib strictly limits salts to the allowed character set, and will throw a ValueError if an invalid salt character is encountered.

Is bcrypt compromised? ›

While bcrypt hashing offers significant protection, it's important to note that it isn't a fail-safe solution against password compromise.

How to install passlib bcrypt? ›

Use pip install passlib[bcrypt] to get the recommended bcrypt setup. If any of these packages are installed, they will be used to provide support for the argon2 hash algorithm. argon2_cffi is currently the recommended option. Use pip install passlib[argon2] to get the recommended argon2 setup.

Is bcrypt safe for password hashing? ›

As you can see in the below table, the cost factor of bcrypt makes it extremely secure against brute force attacks thanks to its slow-working hashing algorithm.

What is the disadvantage of bcrypt? ›

Bcrypt is slower and requires some memory (4 kiB IIRC), so one spends 100ms to check a valid password whereas an attacker needs days / years to crack it because he's slowed down and can't use GPUs efficiently.

Can bcrypt passwords be decrypted? ›

How to decrypt an encrypted password in Mendix app set to bcrypt? You cannot do this because: Passwords are hashed, not encrypted. Hashing is one way only, you cannot reverse it.

Is bcrypt secure in 2024? ›

MD5 reigned supreme for several years but bcrypt was in the lead in 2020, 2021, 2023 and again so far in 2024. Password storage solutions like LastPass, 1Password, and Bitwarden use the hashing approach called PBKDF2 salted with a strong hash alternative to MD5, called SHA-256. Even NIST recommends PBKDF2 SHA-256.

Can you reverse bcrypt hash? ›

It uses a one-way hash function, meaning that once the password is hashed, it cannot be reversed to its original form. Every time the user logs into their account, bcrypt hashes their password anew and compares the new hash value to the version stored in the system's memory to check if the passwords match.

Is bcrypt deprecated? ›

bcrypt-nodejs is deprecated and throws a warning on install #8903.

What version of Python is Passlib? ›

Passlib is a password hashing library for Python 2 & 3, which provides cross-platform implementations of over 20 password hashing algorithms, as well as a framework for managing existing password hashes.

How to install passlib in windows? ›

Installation Instructions
  1. To download and install using :command:`easy_install`: easy_install passlib.
  2. To download and install using :command:`pip`: pip install passlib.
  3. To install from a source directory using :command:`setup.py`: python setup.py install.

What hash is $2? ›

$2a$ : The hash algorithm identifier (bcrypt)

Do I need bcrypt? ›

By using a cryptographically secure hash function, bcrypt significantly slows down the hashing process, making it computationally expensive. This is a good thing because it makes it much harder for attackers to use brute-force methods to guess passwords.

What is bcrypt's cost? ›

Bcrypt uses a cost parameter that specify the number of cycles to use in the algorithm. Increasing this number the algorithm will spend more time to generate the hash output. The cost parameter is represented by an integer value between 4 to 31.

Can hashed passwords be hacked? ›

If they successfully crack a hashed password, they may gain unauthorized access to user accounts and steal sensitive information. They may also use the stolen information for ransomware attacks, where the organization has to pay large sums of money to regain the sensitive data hackers have stolen and encrypted.

What is the difference between bcrypt and passport? ›

Passport is a library to help you implement authorisation in a NodeJS app. The node bcrypt library provides a function to hash a string (which will be a password), it doesn't have any scope beyond that.

What is the better alternative to bcrypt? ›

While there are of course deeper nuances to Argon2, bcrypt, and scrypt, the choice between them boils down to weighing computing and time requirements against memory hardness and parameter number. Argon2 is a great memory-hard password hashing algorithm, which makes it good for offline key derivation.

What to use instead of passlib? ›

Passlib alternatives and similar packages
  • Paramiko. 9.0 7.0 L2 Passlib VS Paramiko. ...
  • cryptography. 8.5 9.9 L2 Passlib VS cryptography. ...
  • PyCrypto. 7.2 4.3 L4 Passlib VS PyCrypto. ...
  • Themis. 5.7 3.6 L3 Passlib VS Themis. ...
  • pyOpenSSL -- A Python wrapper around the OpenSSL library. ...
  • PyNacl. ...
  • ContentHash for Python. ...
  • HashLib4Python-CPPWrapper.
Mar 31, 2016

What is the difference between encrypt and bcrypt? ›

bcrypt() is for creating a Hash , which is a one-way process to turn a plain-text string into a hashed value. You cannot un-hash a value, so there is no way to return the value to it's "normal" state. encrypt() is for "obfuscation", which changes the plain-text string into a non-human readable value.

Top Articles
Filing Off The Serial Numbers
How to Buy Luna: A Step-by-Step Beginner's Guide
Katie Nickolaou Leaving
UPS Paketshop: Filialen & Standorte
123Movies Encanto
Kokichi's Day At The Zoo
Archived Obituaries
Klustron 9
Stl Craiglist
Aces Fmc Charting
David Packouz Girlfriend
Paula Deen Italian Cream Cake
Lesson 1 Homework 5.5 Answer Key
Cvs Devoted Catalog
Smokeland West Warwick
Zendaya Boob Job
Bc Hyundai Tupelo Ms
Craigslist Pets Longview Tx
People Portal Loma Linda
Aspen.sprout Forum
Samsung Galaxy S24 Ultra Negru dual-sim, 256 GB, 12 GB RAM - Telefon mobil la pret avantajos - Abonament - In rate | Digi Romania S.A.
Tamilrockers Movies 2023 Download
Willam Belli's Husband
Scotchlas Funeral Home Obituaries
Decosmo Industrial Auctions
Bethel Eportal
Home
Studentvue Calexico
Sacramento Craigslist Cars And Trucks - By Owner
Play It Again Sports Forsyth Photos
Myra's Floral Princeton Wv
Best New England Boarding Schools
2430 Research Parkway
Cbs Trade Value Chart Week 10
Luciipurrrr_
Plato's Closet Mansfield Ohio
Glossytightsglamour
Arcane Odyssey Stat Reset Potion
Games R Us Dallas
Bernie Platt, former Cherry Hill mayor and funeral home magnate, has died at 90
Gary Lezak Annual Salary
Aurora Il Back Pages
Miami Vice turns 40: A look back at the iconic series
Grizzly Expiration Date Chart 2023
Unblocked Games 6X Snow Rider
9294027542
Page 5747 – Christianity Today
Elvis Costello announces King Of America & Other Realms
Call2Recycle Sites At The Home Depot
Mawal Gameroom Download
Grandma's Portuguese Sweet Bread Recipe Made from Scratch
Latest Posts
Article information

Author: Merrill Bechtelar CPA

Last Updated:

Views: 6047

Rating: 5 / 5 (70 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Merrill Bechtelar CPA

Birthday: 1996-05-19

Address: Apt. 114 873 White Lodge, Libbyfurt, CA 93006

Phone: +5983010455207

Job: Legacy Representative

Hobby: Blacksmithing, Urban exploration, Sudoku, Slacklining, Creative writing, Community, Letterboxing

Introduction: My name is Merrill Bechtelar CPA, I am a clean, agreeable, glorious, magnificent, witty, enchanting, comfortable person who loves writing and wants to share my knowledge and understanding with you.