Skip to content

Instantly share code, notes, and snippets.

@cecil
Created May 7, 2016 07:58
Show Gist options
  • Select an option

  • Save cecil/3d2f9f0c8f16cbd0ebc8374b7fd8e388 to your computer and use it in GitHub Desktop.

Select an option

Save cecil/3d2f9f0c8f16cbd0ebc8374b7fd8e388 to your computer and use it in GitHub Desktop.
Python script to generate a hash for /etc/shadow (SHA512) and LDAP (SSHA1)
#!/usr/bin/python
#
# Python script to generate a hash for /etc/shadow (SHA512) and LDAP (SSHA1)
# In case you needed to support a hypothetical environment that had both auth mechanisms in play.
#
import hashlib
from base64 import urlsafe_b64encode as encode
from base64 import urlsafe_b64decode as decode
from getpass import getpass
import crypt
import os
def hashssha1(password):
salt = os.urandom(4)
h = hashlib.sha1(password)
h.update(salt)
return "{SSHA}" + encode(h.digest() + salt)
def hash512(password):
h = crypt.crypt(password, "$6$16_CHARACTER_SALT_HERE")
return(h)
if __name__ == '__main__':
passin = getpass('Please enter clear-text password: ')
# print("cats " + passin)
print("SSHA1 :: " + hashssha1(passin))
print("SHA512 :: " + hash512(passin))
@Torxed

Torxed commented Aug 28, 2022

Copy link
Copy Markdown

For what it's worth, if someone reacted to https://serverfault.com/a/412441/150015 and ends up here looking for any modern solution/code.
This was introduced in Python3.4 2014 as a built-in:

salt = base64.b64encode(os.urandom(12))
password = base64.b64encode(hashlib.pbkdf2_hmac('sha512', bytes(passin, 'UTF-8'), salt, 200000, 64))
print(f"SHA512 :: $6${salt.decode('UTF-8')}${password.decode('UTF-8')}")

But also this:

Deprecated since version 3.10: Slow Python implementation of pbkdf2_hmac is deprecated. In the future the function will only be available when Python is compiled with OpenSSL.

@gohrner

gohrner commented Mar 27, 2026

Copy link
Copy Markdown

@Torxed: This does not really create a hash suitable for /etc/shadow - it's marked as sha512crypt, which is not what pbkdf2_hmac computes. This will not work in practice.

From man crypt(5):

sha512crypt
A hash based on SHA-2 with 512-bit output, originally developed by Ulrich Drepper for GNU libc. Supported on Linux but not common
elsewhere. Acceptable for new hashes. The default CPU time cost parameter is 5000, which is too low for modern hardware.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment