The Passlib documentation has moved to https://passlib.readthedocs.io
passlib.ifc
– Password Hash Interface¶
PasswordHash API¶
This module provides the PasswordHash
abstract base class.
This class defines the common methods and attributes present
on all the hashes importable from the passlib.hash
module.
Additionally, the passlib.context.CryptContext
class is deliberately
designed to parallel many of this interface’s methods.
See also
PasswordHash Tutorial – Overview of this interface and how to use it.
Base Abstract Class¶
-
class
passlib.ifc.
PasswordHash
¶ This class provides an abstract interface for an arbitrary password hasher.
Applications will generally not construct instances directly – most of the operations are performed via classmethods, allowing instances of a given class to be an internal detail used to implement the various operations.
While
PasswordHash
offers a number of methods and attributes, most applications will only need the two primary methods:PasswordHash.hash()
- generate new salt, return hash of password.PasswordHash.verify()
- verify password against existing hash.
Two additional support methods are also provided:
PasswordHash.using()
- create subclass with customized configuration.PasswordHash.identify()
- check if hash belongs to this algorithm.
Each hash algorithm also provides a number of informational attributes, allowing programmatic inspection of its options and parameter limits.
See also
PasswordHash Tutorial – Overview of this interface and how to use it.
Hashing & Verification Methods¶
Most applications will only need to use two methods:
PasswordHash.hash()
to generate new hashes, and PasswordHash.verify()
to check passwords against existing hashes.
These methods provide an easy interface for working with a password hash,
and abstract away details such as salt generation, hash normalization,
and hash comparison.
-
classmethod
PasswordHash.
hash
(secret, **kwds)¶ Digest password using format-specific algorithm, returning resulting hash string.
For most hashes supported by Passlib, the returned string will contain: an algorithm identifier, a cost parameter, the salt string, and finally the password digest itself.
Parameters: - secret (unicode or bytes) – string containing the password to encode.
- **kwds –
All additional keywords are algorithm-specific, and will be listed in that hash’s documentation; though many of the more common keywords are listed under
PasswordHash.setting_kwds
andPasswordHash.context_kwds
.Deprecated since version 1.7: Passing
PasswordHash.setting_kwds
such asrounds
andsalt_size
directly into thehash()
method is deprecated. Callers should instead usehandler.using(**settings).hash(secret)
. Support for the old method is is tentatively scheduled for removal in Passlib 2.0.Context keywords such as
user
should still be provided tohash()
.
Returns: Resulting password hash, encoded in an algorithm-specific format. This will always be an instance of
str
(i.e.unicode
under Python 3,ascii
-encodedbytes
under Python 2).Raises: - ValueError –
- If a
kwd
‘s value is invalid (e.g. if asalt
string is too small, or arounds
value is out of range). - If
secret
contains characters forbidden by the hash algorithm (e.g.des_crypt
forbids NULL characters).
- If a
- TypeError –
- if
secret
is notunicode
orbytes
. - if a
kwd
argument has an incorrect type. - if an algorithm-specific required
kwd
is not provided.
- if
Changed in version 1.6: Hashes now raise
TypeError
if a required keyword is missing, rather thanValueError
like in previous releases; in order to conform with normal Python behavior.Changed in version 1.6: Passlib is now much stricter about input validation: for example, out-of-range
rounds
values now cause an error instead of being clipped (though applications may set relaxed=True to restore the old behavior).Changed in version 1.7: This method was renamed from
encrypt()
. Deprecated support for passing settings directly intohash()
.
-
classmethod
PasswordHash.
encrypt
(secret, **kwds)¶ Legacy alias for
PasswordHash.hash()
.Deprecated since version 1.7: This method was renamed to
hash()
in version 1.7. This alias will be removed in version 2.0, and should only be used for compatibility with Passlib 1.3 - 1.6.
-
classmethod
PasswordHash.
verify
(secret, hash, **context_kwds)¶ Verify a secret using an existing hash.
This checks if a secret matches against the one stored inside the specified hash.
Parameters: - secret (unicode or bytes) – A string containing the password to check.
- hash –
A string containing the hash to check against, such as returned by
PasswordHash.hash()
.Hashes may be specified as
unicode
orascii
-encodedbytes
. - **kwds –
Very few hashes will have additional keywords.
The ones that do typically require external contextual information in order to calculate the digest. For these hashes, the values must match the ones passed to the original
PasswordHash.hash()
call when the hash was generated, or the password will not verify.These additional keywords are algorithm-specific, and will be listed in that hash’s documentation; though the more common keywords are listed under
PasswordHash.context_kwds
. Examples of common keywords includeuser
.
Returns: True
if the secret matches, otherwiseFalse
.Raises: - TypeError –
- if either
secret
orhash
is not a unicode or bytes instance. - if the hash requires additional
kwds
which are not provided, - if a
kwd
argument has the wrong type.
- if either
- ValueError –
- if
hash
does not match this algorithm’s format. - if the
secret
contains forbidden characters (seePasswordHash.hash()
). - if a configuration/salt string generated by
PasswordHash.genconfig()
is passed in as the value forhash
(these strings look similar to a full hash, but typically lack the digest portion needed to verify a password).
- if
Changed in version 1.6: This function now raises
ValueError
ifNone
or a config string is provided instead of a properly-formed hash; previous releases were inconsistent in their handling of these two border cases.
See also
- Hashing & Verifying tutorial for a usage example
Crypt Methods¶
Taken together, the PasswordHash.genconfig()
and PasswordHash.genhash()
are two tightly-coupled methods that mimic the standard Unix
“crypt” interface. The first method generates salt / configuration
strings from a set of settings, and the second hashes the password
using the provided configuration string.
See also
Most applications will find PasswordHash.hash()
much more useful,
as it combines the functionality of these two methods into one.
-
classmethod
PasswordHash.
genconfig
(**setting_kwds)¶ Deprecated since version 1.7: As of 1.7, this method is deprecated, and slated for complete removal in Passlib 2.0.
For all known real-world uses,
.hash("", **settings)
should provide equivalent functionality.This deprecation may be reversed if a use-case presents itself in the mean time.
Returns a configuration string encoding settings for hash generation.
This function takes in all the same
PasswordHash.setting_kwds
asPasswordHash.hash()
, fills in suitable defaults, and encodes the settings into a single “configuration” string, suitable passing toPasswordHash.genhash()
.Parameters: **kwds – All additional keywords are algorithm-specific, and will be listed in that hash’s documentation; though many of the more common keywords are listed under PasswordHash.setting_kwds
Examples of common keywords includesalt
androunds
.Returns: A configuration string (as str
).Raises: ValueError, TypeError – This function raises exceptions for the same reasons as PasswordHash.hash()
.Changed in version 1.7: This should now always return a full hash string, even in cases where previous releases would return a truncated “configuration only” string, or
None
.
-
classmethod
PasswordHash.
genhash
(secret, config, **context_kwds)¶ Encrypt secret using specified configuration string.
Deprecated since version 1.7: As of 1.7, this method is deprecated, and slated for complete removal in Passlib 2.0.
This deprecation may be reversed if a use-case presents itself in the mean time.
This takes in a password and a configuration string, and returns a hash for that password.
Parameters: - secret (unicode or bytes) – string containing the password to be encrypted.
- config (unicode or bytes) –
configuration string to use when hashing the secret. this can either be an existing hash that was previously returned by
PasswordHash.genhash()
, or a configuration string that was previously created byPasswordHash.genconfig()
.Changed in version 1.7:
None
is no longer accepted for hashes which (prior to 1.7) lacked a configuration string format. - **kwds –
Very few hashes will have additional keywords.
The ones that do typically require external contextual information in order to calculate the digest. For these hashes, the values must match the ones passed to the original
PasswordHash.hash()
call when the hash was generated, or the password will not verify.These additional keywords are algorithm-specific, and will be listed in that hash’s documentation; though the more common keywords are listed under :
PasswordHash.context_kwds
. Examples of common keywords includeuser
.
Returns: Encoded hash matching specified secret, config, and kwds. This will always be a native
str
instance.Raises: ValueError, TypeError – This function raises exceptions for the same reasons as
PasswordHash.hash()
.Warning
Traditionally, password verification using the “crypt” interface was done by testing if
hash == genhash(password, hash)
. This test is only reliable for a handful of algorithms, as various hash representation issues may cause false results. Applications are strongly urged to useverify()
instead.
Factory Creation¶
One powerful method offered by the PasswordHash
class PasswordHash.using()
.
This method allows you to quickly create subclasses of a specific hash,
providing it with preconfigured defaults specific to your application:
-
classmethod
PasswordHash.
using
(relaxed=False, **settings)¶ This method takes in a set of algorithm-specific settings, and returns a new handler object which uses the specified default settings instead.
Parameters: **settings – All keywords are algorithm-specific, and will be listed in that hash’s documentation; though many of the more common keywords are listed under
PasswordHash.setting_kwds
. Examples of common keywords includerounds
andsalt_size
.Returns: A new object which adheres to
PasswordHash
api.Raises: - ValueError –
- If a keywords’s value is invalid (e.g. if a
salt
string is too small, or arounds
value is out of range).
- If a keywords’s value is invalid (e.g. if a
- TypeError –
- if a
kwd
argument has an incorrect type.
- if a
New in version 1.7.
- ValueError –
See also
Customizing the Configuration tutorial for a usage example
Hash Inspection Methods¶
There are currently two hash inspection methods, PasswordHash.identify()
and PasswordHash.needs_update()
.
-
classmethod
PasswordHash.
identify
(hash)¶ Quickly identify if a hash string belongs to this algorithm.
Parameters: hash (unicode or bytes) – the candidate hash string to check Returns: True
if the input is a configuration string or hash string- identifiable as belonging to this scheme (even if it’s malformed).
False
if the input does not belong to this scheme.
Raises: TypeError – if hash
is not a unicode or bytes instance.Note
A small number of the hashes supported by Passlib lack a reliable method of identification (e.g.
lmhash
andnthash
both consist of 32 hexadecimal characters, with no distinguishing features). For such hashes, this method may return false positives.See also
If you are considering using this method to select from multiple algorithms (e.g. in order to verify a password), you will be better served by the CryptContext class.
-
classmethod
PasswordHash.
needs_update
(hash, secret=None)¶ check if hash’s configuration is outside desired bounds, or contains some other internal option which requires updating the password hash.
Parameters: - hash – hash string to examine
- secret – optional secret known to have verified against the provided hash. (this is used by some hashes to detect legacy algorithm mistakes).
Returns: whether secret needs re-hashing.
New in version 1.7.
General Informational Attributes¶
Each hash provides a handful of informational attributes, allowing programs to dynamically adapt to the requirements of different hash algorithms. The following attributes should be defined for all the hashes in passlib:
-
PasswordHash.
name
¶ Name uniquely identifying this hash.
For the hashes built into Passlib, this will always match the location where it was imported from —
passlib.hash.name
— though externally defined hashes may not adhere to this.This should always be a
str
consisting of lowercasea-z
, the digits0-9
, and the underscore character_
.
-
PasswordHash.
setting_kwds
¶ Tuple listing the keywords supported by
PasswordHash.using()
control hash generation, and which will be encoded into the resulting hash.- (These keywords will also be accepted by
PasswordHash.hash()
andPasswordHash.genconfig()
, - though that behavior is deprecated as of Passlib 1.7; and will be removed in Passlib 2.0).
This list commonly includes keywords for controlling salt generation, adjusting time-cost parameters, etc. Most of these settings are optional, and suitable defaults will be chosen if they are omitted (e.g. salts will be autogenerated).
While the documentation for each hash should have a complete list of the specific settings the hash uses, the following keywords should have roughly the same behavior for all the hashes that support them:
salt
Specifies a fixed salt string to use, rather than randomly generating one.
This option is supported by most of the hashes in Passlib, though typically it isn’t used, as random generation of a salt is usually the desired behavior.
Hashes typically require this to be a
unicode
orbytes
instance, with additional constraints appropriate to the algorithm.
salt_size
Most algorithms which support the
salt
setting will autogenerate a salt when none is provided. Most of those hashes will also offer this option, which allows the caller to specify the size of salt which should be generated. If omitted, the hash’s default salt size will be used.See also
the salt info attributes (below)
rounds
If present, this means the hash can vary the number of internal rounds used in some part of its algorithm, allowing the calculation to take a variable amount of processor time, for increased security.
While this is almost always a non-negative integer, additional constraints may be present for each algorithm (such as the cost varying on a linear or logarithmic scale).
This value is typically omitted, in which case a default value will be used. The defaults for all the hashes in Passlib are periodically retuned to strike a balance between security and responsiveness.
See also
the rounds info attributes (below)
ident
If present, the class supports multiple formats for encoding the same hash. The class’s documentation will generally list the allowed values, allowing alternate output formats to be selected.
Note that these values will typically correspond to different revision of the hash algorithm itself, and they may not all offer the same level of security.
truncate_error
This will be present if and only if the hash truncates passwords larger than some limit (reported via it’struncate_size
attribute). By default, they will silently truncate passwords above their limit. Settingtruncate_error=True
will causePasswordHash.hash()
to raise aPasswordTruncateError
instead.relaxed
By default, passing an invalid value to
PasswordHash.using()
will result in aValueError
. However, ifrelaxed=True
then Passlib will attempt to correct the error and (if successful) issue aPasslibHashWarning
instead. This warning may then be filtered if desired. Correctable errors include (but are not limited to):rounds
andsalt_size
values that are too low or too high,salt
strings that are too large.New in version 1.6.
- (These keywords will also be accepted by
-
PasswordHash.
context_kwds
¶ Tuple listing the keywords supported by
PasswordHash.hash()
,PasswordHash.verify()
, andPasswordHash.genhash()
. These keywords are different from the settings kwds in that the context keywords affect the hash, but are not encoded within it, and thus must be provided each time the hash is calculated.This list commonly includes a user account, http realm identifier, etc. Most of these keywords are required by the hashes which support them, as they are frequently used in place of an embedded salt parameter.
Most hash algorithms in Passlib will have no context keywords.
While the documentation for each hash should have a complete list of the specific context keywords the hash uses, the following keywords should have roughly the same behavior for all the hashes that support them:
user
If present, the class requires a username be specified whenever performing a hash calculation (e.g.postgres_md5
andoracle10
).encoding
Some hashes have poorly-defined or host-dependant unicode behavior, and properly hashing a non-ASCII password requires providing the correct encoding (lmhash
is perhaps the worst offender). Hashes which provide this keyword will always expose their default encoding programmatically via thePasswordHash.default_encoding
attribute.
-
passlib.ifc.
truncate_size
¶ A positive integer, indicating the hash will truncate any passwords larger than this many bytes. If
None
(the more common case), indicates the hash will use the entire password provided.Hashes which specify this setting will also support a
truncate_error
flag via theirPasswordHash.using()
method, to configure how truncation is handled.
See also
Customizing the Configuration tutorial for a usage example
Salt Information Attributes¶
For schemes which support a salt string,
"salt"
should be listed in their PasswordHash.setting_kwds
,
and the following attributes should be defined:
-
PasswordHash.
max_salt_size
¶ The maximum number of bytes/characters allowed in the salt. Should either be a positive integer, or
None
(indicating the algorithm has no effective upper limit).
-
PasswordHash.
min_salt_size
¶ The minimum number of bytes/characters required for the salt. Must be an integer between 0 and
PasswordHash.max_salt_size
.
-
PasswordHash.
default_salt_size
¶ The default salt size that will be used when generating a salt, assuming
salt_size
is not set explicitly. This is typically the same asmax_salt_size
, or a sane default ifmax_salt_size=None
.
-
PasswordHash.
salt_chars
¶ A unicode string containing all the characters permitted in a salt string.
For most Modular Crypt Format hashes, this is equal to
passlib.utils.binary.HASH64_CHARS
. For the rare hashes where thesalt
parameter must be specified in bytes, this will be a placeholderbytes
object containing all 256 possible byte values.
Rounds Information Attributes¶
For schemes which support a variable time-cost parameter,
"rounds"
should be listed in their PasswordHash.setting_kwds
,
and the following attributes should be defined:
-
PasswordHash.
max_rounds
¶ The maximum number of rounds the scheme allows. Specifying a value beyond this will result in a
ValueError
. This will be either a positive integer, orNone
(indicating the algorithm has no effective upper limit).
-
PasswordHash.
min_rounds
¶ The minimum number of rounds the scheme allows. Specifying a value below this will result in a
ValueError
. Will always be an integer between 0 andPasswordHash.max_rounds
.
-
PasswordHash.
default_rounds
¶ The default number of rounds that will be used if none is explicitly provided to
PasswordHash.hash()
. This will always be an integer betweenPasswordHash.min_rounds
andPasswordHash.max_rounds
.
-
PasswordHash.
rounds_cost
¶ While the cost parameter
rounds
is an integer, how it corresponds to the amount of time taken can vary between hashes. This attribute indicates the scale used by the hash:"linear"
- time taken scales linearly with rounds value (e.g.sha512_crypt
)"log2"
- time taken scales exponentially with rounds value (e.g.bcrypt
)
Todo
document the additional PasswordHash.using()
keywords
available for setting rounds limits.