Linux – How to create an SHA-512 hashed password for shadow

authenticationencryptionlinuxmd5

The previous SF questions I've seen have lead to answers that produce MD5 hashed password.

Does anyone have a suggestion on to produce an SHA-512 hashed password? I'd prefer a one liner instead of a script but, if a script is the only solution, that's fine as well.

Update

Replacing previous py2 versions with this one:

python3 -c "import crypt;print(crypt.crypt(input('clear-text pw: '), crypt.mksalt(crypt.METHOD_SHA512)))"

Best Answer

Edit: Please note this answer is 10+ years old.

Here's a one liner:

python -c 'import crypt; print crypt.crypt("test", "$6$random_salt")'

Python 3.3+ includes mksalt in crypt, which makes it much easier (and more secure) to use:

python3 -c 'import crypt; print(crypt.crypt("test", crypt.mksalt(crypt.METHOD_SHA512)))'

If you don't provide an argument to crypt.mksalt (it could accept crypt.METHOD_CRYPT, ...MD5, SHA256, and SHA512), it will use the strongest available.

The ID of the hash (number after the first $) is related to the method used:

  • 1 -> MD5
  • 2a -> Blowfish (not in mainline glibc; added in some Linux distributions)
  • 5 -> SHA-256 (since glibc 2.7)
  • 6 -> SHA-512 (since glibc 2.7)

I'd recommend you look up what salts are and such and as per smallclamgers comment the difference between encryption and hashing.

Update 1: The string produced is suitable for shadow and kickstart scripts.
Update 2: Warning. If you are using a Mac, see the comment about using this in python on a mac where it doesn't seem to work as expected.

On macOS you should not use the versions above, because Python uses the system's version of crypt() which does not behave the same and uses insecure DES encryption. You can use this platform independent one liner (requires passlib – install with pip3 install passlib):

python3 -c 'import passlib.hash; print(passlib.hash.sha512_crypt.hash("test"))'