The crypt() function encrypts a string using DES, Blowfish, or MD5 algorithms.
Syntax for PHP crypt() function has the following syntax.
crypt(str,salt)
Parameter | Is Required | Description |
---|---|---|
str | Required. | String to be encoded |
salt | Optional. | A string used to make the encoding more secure. |
Returns the hashed string or a string that is shorter than 13 characters and is guaranteed to differ from the salt on failure.
Different operating systems support different one type of hash.
On systems where the crypt() function supports multiple hash types, the following constants are set to 0 or 1 depending on whether the given type is available:
You should pass the entire results of crypt() as the salt for comparing a password, to avoid problems when different hashing algorithms are used.
<?php $hashed_password = crypt('mypassword'); // let the salt be automatically generated if (crypt($user_input, $hashed_password) == $hashed_password) { echo "Password verified!"; } ?>
Using crypt() with htpasswd
<?php
// Set the password
$password = 'mypassword';
// Get the hash, letting the salt be automatically generated
$hash = crypt($password);
?>
<?php//from ww w . j av a2s . c om
if (CRYPT_STD_DES == 1) {
echo 'Standard DES: ' . crypt('PHP from java2s.com', 'st') . "\n";
}
if (CRYPT_EXT_DES == 1) {
echo 'Extended DES: ' . crypt('PHP from java2s.com', '123..java') . "\n";
}
if (CRYPT_MD5 == 1) {
echo 'MD5: ' . crypt('PHP from java2s.com', '$1$java2s.c$') . "\n";
}
if (CRYPT_BLOWFISH == 1) {
echo 'Blowfish: ' . crypt('PHP from java2s.com', '$2a$07$java2s.comfromPHP12345678$') . "\n";
}
if (CRYPT_SHA256 == 1) {
echo 'SHA-256: ' . crypt('PHP from java2s.com', '$5$rounds=5000$PHPfromjava2s.com12345678$') . "\n";
}
if (CRYPT_SHA512 == 1) {
echo 'SHA-512: ' . crypt('PHP from java2s.com', '$6$rounds=5000$PHPfromjava2s.comqwertyui$') . "\n";
}
?>
The code above generates the following result.