Search code examples
linuxauthenticationsalt-cryptographycrypt

how is the salt for user password hash created when creating a new user, for use with crypt() after?


currently making a little analysis on the authentication based on password on linux, i understood the following :

users passwords hashes are stored in /etc/shadow, with the salt used to generate them. The id also provide the algorithm used to get the hash. To verify if a password is correct, we pass the id and the salt to the crypt function, generate a temporary hash and compare it to the hash registered.

However, when you create a new user for example, you need to populate that shadow file with hash and salt. Hash is of course obtained by calling crypt function, but i can't figure out how is the salt generated when invoking that crypt function.

Indeed, from what i have read and understoof of the libc code relative to crypt function, there is nothing relative to generate a random salt. We can provide crypt with a random salt we have created by hand when creating a new user, but we almost always create users without providing salts for their password hashing.

So, how is that salt generated the first time when creating a user? Is /dev/random used?

I would appreciate some code or commands in the answer.

thanks!


Solution

  • There is no standard function to generate the salt but every good library should generate a random one for you. As written in another comment some salts have to be of a specific alphabet like "A-Za-z0-9./" for crypt() while others accept random data.

    For Java, look at the Apache Commons Codec project which implements a Unix crypt() compatible function. It's a simple for loop that choses random characters from a given alphabet:

    http://grepcode.com/file/repo1.maven.org/maven2/commons-codec/commons-codec/1.10/org/apache/commons/codec/digest/B64.java#B64.getRandomSalt%28int%29