PHP Tutorial - PHP crypt() Function






Definition

The crypt() function encrypts a string using DES, Blowfish, or MD5 algorithms.

Syntax

Syntax for PHP crypt() function has the following syntax.

crypt(str,salt)

Parameter

ParameterIs RequiredDescription
strRequired.String to be encoded
saltOptional.A string used to make the encoding more secure.

Return

Returns the hashed string or a string that is shorter than 13 characters and is guaranteed to differ from the salt on failure.





Note

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:

  • CRYPT_STD_DES - Standard DES-based hash with a two character salt from the alphabet "./0-9A-Za-z".
  • CRYPT_EXT_DES - Extended DES-based hash.
  • CRYPT_MD5 - MD5 hashing with a twelve character salt starting with $1$
  • CRYPT_BLOWFISH - Blowfish hashing
  • CRYPT_SHA256 - SHA-256 hash with a sixteen character salt prefixed with $5$.
  • CRYPT_SHA512 - SHA-512 hash with a sixteen character salt prefixed with $6$.




Example

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!";
}
?>

Example 2

Using crypt() with htpasswd


<?php
// Set the password
$password = 'mypassword';

// Get the hash, letting the salt be automatically generated
$hash = crypt($password);
?>

Example 3


<?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.