使用Linux用来散列用户密码的算法来散列字符串?

What's the algorithm that Linux uses to hash users' passwords? How can I implement that algorithm in PHP?

You might need to know some background information on Linux password storage formats - especially on shadowed password configuration before you can actually implement your own.

On Linux distributions using glibc2, the hash function has a 'magic bit' and salt prefixed to it.

The magic bit starts off with '$x$' and is used to determined the hash function that was used:

  • $1$ for MD5
  • $2$ for Blowfish,
  • $5$ for SHA-256 and
  • $6$ for SHA-512

(Other unix systems like NetBSD might have different values for this).

The magic bit then followed by 8 bits that constitutes the salt and optionally is terminated by another "$". Between this and the next "$", you will find the actual password hash.

Almost all modern Linux systems these days do NOT store the passwords in the world-readable /etc/passwd. Instead the passwords are shadowed in /etc/shadow where only root is allowed read permission. If the shadowed password scheme in use, the /etc/passwd file shows a character such as '*', or 'x' instead of the password.

The format of a typical password in /etc/shadow would looks like this:

$a:$b:$c:$e:$f:$g:$h:$i

Where:

$a: username

$b: salt and hashed password (as explained above). If this is "NP" or "!" or null then it means that the account has no password. "LK" or "*" means the account is locked and the user will be unable to log-in. "!!" means that the password has expired

$c: Days since epoch of last password change

$d: Days until change allowed

$e: Days before change required

$f: Days warning for expiration

$g: Days before account inactive

$h: Days since epoch when account expires

$i: Reserved for future use.

An example of a shadowed password file could be found at: http://configuration.logfish.net/index.php/etc/shadow

References:

crypt(3) - Linux man page

Why shadow your passwd file?

Understanding Linux Password Hashes

Shadow password on wikipedia

Try using the PHP crypt function.