I am reading a book and it gives me a simple Python script to crack /etc/shadow passwords that were encrypted with the crypt() function. It then challenges you to amend the Python program to work with the newer Crypt3 SHA-512 algorithm used in modern Linux(es).

I am getting stuck on outputting the same hash that is stored in /etc/shadow. I have a user test1 with a password of password and /etc/shadow looks like this:

cat /etc/shadow | grep test1

An the simplest form of my script looks like this:

import hashlib
dk = hashlib.pbkdf2_hmac('sha512',b'password',b'sRgBNCzw',5000)

Inspecting dk looks like this:

>>> dk
'.YQ\xf0\xf1\x1f\x08\x0e\x9c\xa9-E\x90\x89\xebZ\xb1\x04ao:\x00;\x9a\xcb?\xaa\x04H\x14\xb6&\x9c\x0e}#\xbd\xf5\xe6\xa5\xd6\xda|xu\x1e\xa1\xd1\x95D\x94\x15\x19 \xccEX\\\xf0g\x97|\\\xee'

Which I guess is Python's best effort at representing a binary blob as text. However, I need to compare this with the hashed value of the Crypt3 function which is:


Now just looking at the hashed value in the shadow file I can see it looks like base64 so I use this:


And get this:


Further reading has taught me that the Crypt3 function uses a slightly modified version of base64 that does away with padding and '='.

Can any one help with how I can get my hash to match the hash in /etc/shadow using Python?

  • Have you seen unix.stackexchange.com/questions/158400/…? It looks like it's generating the same $6$ type that you are even though it's using a different algorithm. Dec 24, 2015 at 1:17
  • 'violent python' is my guess for the book? At least that's the one that brought me here.
    – sjas
    Oct 29, 2017 at 15:33

1 Answer 1


Based on information in this question, I was able to successfully reproduce a hash.

After setting my password to password, I executed these commands

$ sudo grep neil /etc/shadow
$ python -c 'import crypt; print crypt.crypt("password", "$6$GpNiWKnm$")'
$ python --version
Python 2.7.10

It should be noted that the hash algorithm that is in use can be determined by the value between the first pair of dollar signs. In this case the $6$ means it's sha-512 (reference).

  • Thanks Neil yes this works great. I was blinkerd by hashlib.
    – squareborg
    Dec 24, 2015 at 12:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .