2

How to implement the crypt option in Python 3?

I understand that the use is:

Hash = crypt.crypt(password, salt)

However, the function has a set of different hashing functions. From the documentation:

crypt.METHOD_SHA512 A Modular Crypt Format method with 16 character salt and 86 character hash. This is the strongest method.

crypt.METHOD_SHA256 Another Modular Crypt Format method with 16 character salt and 43 character hash.

crypt.METHOD_MD5 Another Modular Crypt Format method with 8 character salt and 22 character hash.

crypt.METHOD_CRYPT The traditional method with a 2 character salt and 13 characters of hash. This is the weakest method.

Again my question is how do I chose which algorithm the function uses?

This is a very basic question I can't believe that I failed to find the answer on my own - I apologise if I'm wasting your time.

3 Answers 3

3

You pass the method as the salt argument. From the crypt function docstring:

If salt is not specified or is None, the strongest available method will be selected and a salt generated. Otherwise, salt may be one of the crypt.METHOD_* values, or a string as returned by crypt.mksalt().

For example:

crypt.crypt("password", crypt.METHOD_SHA512)

Which under the hood becomes:

crypt.crypt("password", crypt.mksalt(crypt.METHOD_SHA512))
1
  • 3
    Thanks! But can I specify the process? That is could I use SHA512 but provide my own salt?
    – Tikhon
    Commented Jan 28, 2017 at 0:00
1

Adapted from a Red Hat solution and @Leonard_Saracini answer (remove the backslash to make it a oneliner):

python3 -c 'import crypt,getpass,sys; \
print(crypt.crypt(getpass.getpass(), crypt.mksalt(crypt.METHOD_SHA512)))'

This is should be secure as of August 2018.

0

using bash:$ python3 -c "import crypt; print(crypt.crypt('password', '\$6\$saltstring'))"

$6$ is for SHA512 and $ must be escaped by \ if you use a bash terminal like me

Not the answer you're looking for? Browse other questions tagged or ask your own question.