crypt

(PHP 4, PHP 5, PHP 7, PHP 8)

crypt单向字符串散列

警告

此函数(还)不能安全地适用于二进制对象!

说明

crypt(string $string, string $salt): string

crypt() 返回基于标准 UNIX DES 算法或替代算法的散列字符串。password_verify() 兼容 crypt()。因此,由 crypt() 创建的密码散列可以跟 password_verify() 一起使用。

在 PHP 8.0.0 之前,salt 参数是可选的。然而,如果没有 saltcrypt() 会创建弱散列。在没有它的情况下引发 E_NOTICE 级别的错误。为了更好的安全性,请确保指定足够强度的盐值。

password_hash() 使用了强散列,产生足够强的盐值,并自动应用合适的轮次。password_hash()crypt() 的简单封装,并且与现有的密码散列兼容。推荐使用 password_hash()

散列类型由盐值参数触发。如果没有提供盐值,PHP 将自动生成一个 2 个字符(DES)或者 12 个字符(MD5)的盐值 ,这取决于 MD5 crypt() 的可用性。PHP 设置了名为 CRYPT_SALT_LENGTH 的常量,用来表示可用散列允许的最长有效盐值。

基于标准 DES 算法的 crypt() 在输出内容的开始位置返回两个字符的盐值。它也只使用 string 的开始 8 个字符,所以更长的以相同 8 个字符开始的字符串也将生成相同的结果(当使用了相同的盐值时)。

支持以下散列类型:

  • CRYPT_STD_DES - 基于标准 DES 算法的散列使用 "./0-9A-Za-z" 字符中的两个字符作为盐值。在盐值中使用非法的字符将导致 crypt() 失败。
  • CRYPT_EXT_DES - 扩展的基于 DES 算法的散列。“sale” 为 9 个字符的字符串,由 1 个下划线后面跟着 4 字符循环次数和 4 字符盐值组成。这些 4 字符字符串都编码为 24 字节,最低有效位在前。值 063 被编码为 ./0-9A-Za-z。在盐值中使用非法的字符将导致 crypt() 失败。
  • CRYPT_MD5 - MD5 散列使用一个以 $1$ 开始的 12 字符的字符串盐值。
  • CRYPT_BLOWFISH - Blowfish 散列使用如下盐值:“$2a$”、“$2x$” 或 “$2y$”,两位 cost 参数,“$” 以及 22 位由 “./0-9A-Za-z” 中的字符组合而成的字符串。在盐值中使用此范围之外的字符将导致 crypt() 返回一个空字符串。两位 cost 参数是循环次数以 2 为底的对数,它的范围是 04-31,超出这个范围将导致 crypt() 失败。 “$2x$” 可能很弱,“$2x$” 散列对其兼容并增强安全性。对于新的散列,应该使用“$2y$”。
  • CRYPT_SHA256 - SHA-256 算法使用一个以 $5$ 开头的 16 字符字符串盐值进行散列。如果盐值字符串以 “rounds=<N>$” 开头,N 的数字值将被用来指定散列循环的执行次数,这点很像 Blowfish 算法的 cost 参数。默认的循环次数是 5000,最小是 1000,最大是 999,999,999。超出这个范围的 N 将会被转换为最接近的值。
  • CRYPT_SHA512 - SHA-512 算法使用一个以 $6$ 开头的 16 字符字符串盐值进行散列。如果盐值字符串以 “rounds=<N>$” 开头,N 的数字值将被用来指定散列循环的执行次数,这点很像 Blowfish 算法的 cost 参数。默认的循环次数是 5000,最小是 1000,最大是 999,999,999。超出这个范围的 N 将会被转换为最接近的值。

参数

string

待散列的字符串。

警告

使用 CRYPT_BLOWFISH 算法将导致 string 被裁剪为一个最长72 字节的字符串。

salt

盐值字符串。如果没有提供,算法行为将由不同的算法实现决定,并可能导致不可预料的结束。

返回值

返回散列后的字符串或一个少于 13 字符的字符串,从而保证在失败时与盐值区分开来。

警告

当校验密码时,应该使用一个不容易被时间攻击的字符串比较函数来比较crypt()的输出与之前已知的散列。出于这个目的,PHP 提供了hash_equals()

更新日志

版本 说明
8.0.0 salt不再可选。

范例

示例 #1 crypt() 范例

<?php
// 自动生成盐值;不推荐
$hashed_password crypt('mypassword');

/* 你应当使用 crypt() 得到的完整结果作为盐值进行密码校验,以此来避免使用不同散列算法导致的问题。(如上所述,基于标准 DES 算法的密码散列使用 2 字符盐值,但是基于 MD5 算法的散列使用 12 个字符盐值。)*/
if (hash_equals($hashed_passwordcrypt($user_input$hashed_password))) {
   echo 
"Password verified!";
}
?>

示例 #2 利用 htpasswd 进行 crypt() 加密

<?php
// 设置密码
$password 'mypassword';

// 获取散列值,使用自动盐值;不推荐
$hash crypt($password);
?>

示例 #3 以不同散列类型使用 crypt()

<?php
/* These salts are examples only, and should not be used verbatim in your code.
   You should generate a distinct, correctly-formatted salt for each password.
*/
echo 'Standard DES: ',
    
crypt('rasmuslerdorf''rl'),
    
"\n";
echo 
'Extended DES: ',
    
crypt('rasmuslerdorf''_J9..rasm'),
    
"\n";
echo 
'MD5:          ',
    
crypt('rasmuslerdorf''$1$rasmusle$'),
    
"\n";
echo 
'Blowfish:     ',
    
crypt('rasmuslerdorf''$2a$07$usesomesillystringforsalt$'),
    
"\n";
echo 
'SHA-256:      ',
    
crypt('rasmuslerdorf''$5$rounds=5000$usesomesillystringforsalt$'),
    
"\n";
echo 
'SHA-512:      ',
    
crypt('rasmuslerdorf''$6$rounds=5000$usesomesillystringforsalt$'),
    
"\n";
?>

以上例程的输出类似于:

Standard DES: rl.3StKT.4T8M
Extended DES: _J9..rasmBYk8r9AiWNc
MD5:          $1$rasmusle$rISCgZzpwk3UhDidwXvin0
Blowfish:     $2y$07$usesomesillystringfore2uDLvp1Ii2e./U9C8sBjqp8I90dH6hi
SHA-256:      $5$rounds=5000$usesomesillystri$KqJWpanXZHKq2BOB43TSaYhEWsQ1Lr5QNyPCDH/Tp.6
SHA-512:      $6$rounds=5000$usesomesillystri$D4IrlXatmP7rx3P3InaxBeoomnAihCKRVQP22JZ6EY47Wc6BkroIuUUBOov1i.S5KPgErtP/EN5mcO.ChWQW21

注释

注意: 由于 crypt() 使用的是单向算法,因此不存在 decrypt 函数。

参见

  • hash_equals() - 可防止时序攻击的字符串比较
  • password_hash() - 创建密码的散列(hash)
  • md5() - 计算字符串的 MD5 散列值
  • 更多关于 crypt 函数的信息,请阅读 Unix man 页面

add a note add a note

User Contributed Notes 8 notes

up
63
bob dot orr at mailinator dot com
7 years ago
The #2 comment on this comments page (as of Feb 2015) is 9 years old and recommends phpass.  I have independently security audited this product and, while it continues to be recommended for password security, it is actually insecure and should NOT be used.  It hasn't seen any updates in years (still at v0.3) and there are more recent alternatives such as using the newer built-in PHP password_hash() function that are much better.  Everyone, please take a few moments to confirm what I'm saying is accurate (i.e. review the phpass code for yourself) and then click the down arrow to sink the phpass comment to the bottom.  You'll be increasing security across the Internet by doing so.

For those who want details:  md5() with microtime() are a fallback position within the source code of phpass.  Instead of terminating, it continues to execute code.  The author's intentions of trying to work everywhere are admirable but, when it comes to application security, that stance actually backfires.  The only correct answer in a security context is to terminate the application rather than fallback to a weak position that can potentially be exploited (usually by forcing that weaker position to happen).
up
16
Marten Jacobs
8 years ago
As I understand it, blowfish is generally seen a secure hashing algorithm, even for enterprise use (correct me if I'm wrong). Because of this, I created functions to create and check secure password hashes using this algorithm, and using the (also deemed cryptographically secure) openssl_random_pseudo_bytes function to generate the salt.

<?php
/*
* Generate a secure hash for a given password. The cost is passed
* to the blowfish algorithm. Check the PHP manual page for crypt to
* find more information about this setting.
*/
function generate_hash($password, $cost=11){
       
/* To generate the salt, first generate enough random bytes. Because
         * base64 returns one character for each 6 bits, the we should generate
         * at least 22*6/8=16.5 bytes, so we generate 17. Then we get the first
         * 22 base64 characters
         */
       
$salt=substr(base64_encode(openssl_random_pseudo_bytes(17)),0,22);
       
/* As blowfish takes a salt with the alphabet ./A-Za-z0-9 we have to
         * replace any '+' in the base64 string with '.'. We don't have to do
         * anything about the '=', as this only occurs when the b64 string is
         * padded, which is always after the first 22 characters.
         */
       
$salt=str_replace("+",".",$salt);
       
/* Next, create a string that will be passed to crypt, containing all
         * of the settings, separated by dollar signs
         */
       
$param='$'.implode('$',array(
               
"2y", //select the most secure version of blowfish (>=PHP 5.3.7)
               
str_pad($cost,2,"0",STR_PAD_LEFT), //add the cost in two digits
               
$salt //add the salt
       
));
      
       
//now do the actual hashing
       
return crypt($password,$param);
}

/*
* Check the password against a hash generated by the generate_hash
* function.
*/
function validate_pw($password, $hash){
       
/* Regenerating the with an available hash as the options parameter should
         * produce the same hash if the same password is passed.
         */
       
return crypt($password, $hash)==$hash;
}
?>
up
9
steve at tobtu dot com
9 years ago
To generate salt use mcrypt_create_iv() not mt_rand() because no matter how many times you call mt_rand() it will only have at most 32 bits of entropy. Which you will start seeing salt collisions after about 2^16 users. mt_rand() is seeded poorly so it should happen sooner.

For bcrypt this will actually generate a 128 bit salt:
<?php $salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.'); ?>

*** Bike shed ***
The last character in the 22 character salt is 2 bits.
base64_encode() will have these four character "AQgw"
bcrypt will have these four character ".Oeu"

You don't need to do a full translate because they "round" to different characters:
echo crypt('', '$2y$05$.....................A') . "\n";
echo crypt('', '$2y$05$.....................Q') . "\n";
echo crypt('', '$2y$05$.....................g') . "\n";
echo crypt('', '$2y$05$.....................w') . "\n";

$2y$05$......................J2ihDv8vVf7QZ9BsaRrKyqs2tkn55Yq
$2y$05$.....................O/jw2XygQa2.LrIT7CFCBQowLowDP6Y.
$2y$05$.....................eDOx4wMcy7WU.kE21W6nJfdMimsBE3V6
$2y$05$.....................uMMcgjnOELIa6oydRivPkiMrBG8.aFp.
up
7
kaminski at istori dot com
11 years ago
Here is an expression to generate pseudorandom salt for the CRYPT_BLOWFISH hash type:

<?php $salt = substr(str_replace('+', '.', base64_encode(pack('N4', mt_rand(), mt_rand(), mt_rand(), mt_rand()))), 0, 22); ?>

It is intended for use on systems where mt_getrandmax() == 2147483647.

The salt created will be 128 bits in length, padded to 132 bits and then expressed in 22 base64 characters.  (CRYPT_BLOWFISH only uses 128 bits for the salt, even though there are 132 bits in 22 base64 characters.  If you examine the CRYPT_BLOWFISH input and output, you can see that it ignores the last four bits on input, and sets them to zero on output.)

Note that the high-order bits of the four 32-bit dwords returned by mt_rand() will always be zero (since mt_getrandmax == 2^31), so only 124 of the 128 bits will be pseudorandom.  I found that acceptable for my application.
up
0
jette at nerdgirl dot dk
9 years ago
The crypt() function cant handle plus signs correctly. So if for example you are using crypt in a login function, use urlencode on the password first to make sure that the login procedure can handle any character:

<?php
$user_input
'12+#æ345';
$pass = urlencode($user_input));
$pass_crypt = crypt($pass);

if (
$pass_crypt == crypt($pass, $pass_crypt)) {
  echo
"Success! Valid password";
} else {
  echo
"Invalid password";
}
?>
up
-10
Anonymous
4 years ago
steve at tobtu dot com was right 4 years ago, but now mcrypt_create_iv()  (and bcrypt in general) is deprecated!

Use random_bytes() instead:

<?php
$salt
= base64_encode(random_bytes(16));
up
-15
ian+php dot net at eiloart dot ocm
8 years ago
If you're stuck with CRYPT_EXT_DES, then you'll want to pick a number of iterations: the 2nd-5th characters of the "salt".

My experimentation suggests that the 5th character is the most significant. A '.' is a zero and 'Z' is the highest value. Using all dots will create an error: all passwords will be encrypted to the same value.

Here are some encryption timings (in seconds) that I obtained, with five different iteration counts over the same salt, and the same password, on a quad core 2.66GHz Intel Xeon machine.

_1111 time: 0.15666794776917
_J9.Z time: 1.8860530853271
_J9.. time: 0.00015401840209961
_...Z time: 1.9095730781555
_ZZZZ time: 1.9124970436096
_...A time: 0.61211705207825

I think a half a second is reasonable for an application, but for the back end authentication? I'm not so sure: there's a significant risk of overloading the back end if we're getting lots of authentication requests.
up
-10
Joey
4 years ago
While the documentation says that crypt will fail for DES if the salt is invalid, this turns out to not be the case.

The crypt function will accept any string of two characters or more for DES as long as it doesn't match the pattern for any other hashing schema. The remaining characters will be ignored.
To Top