Manually generate password for /etc/shadow

You can use following commands for the same:

Method 1 (md5, sha256, sha512)

openssl passwd -6 -salt xyz  yourpass

Note: passing -1 will generate an MD5 password, -5 a SHA256 and -6 SHA512 (recommended)

Method 2 (md5, sha256, sha512)

mkpasswd --method=SHA-512 --stdin

The option --method accepts md5, sha-256 and sha-512

Method 3 (des, md5, sha256, sha512)

As @tink suggested, we can update the password using chpasswd using:

echo "username:password" | chpasswd 

Or you can use the encrypted password with chpasswd. First generate it using this:

perl -e 'print crypt("YourPasswd", "salt", "sha512"),"\n"'

Then later you can use the generated password to update /etc/shadow:

echo "username:encryptedPassWd" | chpasswd -e

The encrypted password we can also use to create a new user with this password, for example:

useradd -p 'encryptedPassWd'  username

On Ubuntu 12.04, there is mkpasswd (from the whois package): Overfeatured front end to crypt(3)

mkpasswd  -m sha-512 -S saltsalt -s <<< YourPass

Where:

  • -m = Compute the password using the TYPE method. If TYPE is help then the available methods are printed.
  • -S = salt used.

E.g.

$ mkpasswd -m help

-s = Read password from stdin

This solution has the following benefits:

  • Nothing additional to install
  • Does not store the password in your shell history
  • Generates a random salt for you
  • Uses a modern, strong hashing algorithm, SHA-512
  • Re-prompts for the password to avoid mistakes.

    $ python3 -c "from getpass import getpass; from crypt import *; \
        p=getpass(); print('\n'+crypt(p, METHOD_SHA512)) \
        if p==getpass('Please repeat: ') else print('\nFailed repeating.')"
    

References

  • How to create a SHA-512 hashed password for /etc/shadow?
  • SHA512 with salt