/etc/shadow - HowTo: Generate Password Hash in Linux

Linux stores users' encrypted passwords, as well as other security information such as account or password expiration values, in the /etc/shadow file.

Someday you may need to edit the /etc/shadow file manually to set or change ones password.

For this you would have to generate password's hash in the format compatible with /etc/shadow.

There is no need to install any additional tools as it can be easily done from the Linux command line using Python.

Generate Password Hash for /etc/shadow

Read more: Encrypt And Decrypt Files With A Password Using OpenSSL

The encrypted passwords in /etc/shadow file are stored in the following format:

$ID$SALT$ENCRYPTED

The $ID indicates the type of encryption, the $SALT is a random (up to 16 characters) string and $ENCRYPTED is a password's hash.

Hash Type ID Hash Length
MD5 $1 22 characters
SHA-256 $5 43 characters
SHA-512 $6 86 characters

Use the below commands from the Linux shell to generate hashed password for /etc/shadow with the random salt.

Read more: Create a Password Protected ZIP File in Linux

Generate MD5 Password Hash

python -c "import random,string,crypt; randomsalt = ''.join(random.sample(string.ascii_letters,8)); print crypt.crypt('MySecretPassword', '\$1\$%s\$' % randomsalt)"
$1$TbmEpHMW$05UMvhmGD4Mu27t6ND7AT0

Generate SHA-256 Password Hash

python -c "import random,string,crypt; randomsalt = ''.join(random.sample(string.ascii_letters,8)); print crypt.crypt('MySecretPassword', '\$5\$%s\$' % randomsalt)"
$5$EbuBToLa$m6di42WAC01AbsKjA01t5c.L9oZ9foHc1Ch4CysHFG3

Generate SHA-512 Password Hash

python -c "import random,string,crypt; randomsalt = ''.join(random.sample(string.ascii_letters,8)); print crypt.crypt('MySecretPassword', '\$6\$%s\$' % randomsalt)"
$6$TOegwWck$6WGKWqOBM7LiVPGgOoHQ16GmAuGrJoyP/TZY/N12DNPbEzXfyk/06HI.vTi1WJnppYxysIS6XI0TW0NYi3KKS.