Home >>PHP String Functions >PHP crypt() Function

PHP crypt() Function

PHP crypt() Function

PHP crypt() function is an in-built function of PHP. Crypt() function converts any given input string in to hash string. For the conversion, this function uses different algorithms like MD5, SHA256, or Blowfish. On different operating systems this crypt() function behaves differently.

The crypt() function doesn’t have any counter function for decryption.

Syntax :

crypt($string, $salt)

The $string parameter is the given input string which is to be hashed. This parameter is mandatory.The salt parameter is not mandatory, it’s optional but without this $salt crypt() function creates a weak password. So we try to give a strong salt value for strong security.

There are also some constants that are used With the crypt() function we also use some constants whose values are defined at the time of installation of PHP.

  • [CRYPT_SHA_512] - SHA-512 hash which has a 16 character salt starting with 66.
  • [CRYPT_MD5] - MD5 hashing which has a 12 character salt starting with 11.
  • [CRYPT_BLOWFISH] - Blowfish hashing which has a salt starting with 2x2x, or 2y2y, a two digit cost parameters "$", and 22 characters from the alphabet.
  • [CRYPT_SHA_256] - SHA-256 hash which has a 16 character salt starting with 55.
  • [CRYPT_STD_DES] - Standard DES-based hash which has two character salt from the alphabet.

Let's see an example for crypt() function:

<?php
if (CRYPT_STD_DES == 1)
{
echo "Standard DES: ".crypt('PHPTPOINT','st')."\n<br><br>";
}
else
{
echo "Standard DES not supported.\n<br>";
}

if (CRYPT_EXT_DES == 1)
{
echo "Extended DES: ".crypt('PHPTPOINT','_S4..some')."\n<br><br>";
}
else
{
echo "Extended DES not supported.\n<br>";
}

if (CRYPT_MD5 == 1)
{
echo "MD5: ".crypt('PHPTPOINT','$1$somethin$')."\n<br><br>";
}
else
{
echo "MD5 not supported.\n<br>";
}

if (CRYPT_BLOWFISH == 1)
{
echo "Blowfish: ".crypt('PHPTPOINT','$2a$09$anexamplestringforsalt$')."\n<br><br>";
}
else
{
echo "Blowfish DES not supported.\n<br>";
}

if (CRYPT_SHA512 == 1)
{
echo "SHA-512: ".crypt('PHPTPOINT','$6$rounds=5000$anexamplestringforsalt$')."\n<br><br>";
}
else
{
echo "SHA-512 not supported.";
}

if (CRYPT_SHA256 == 1)
{
echo "SHA-256: ".crypt('PHPTPOINT','$5$rounds=5000$anexamplestringforsalt$')."\n<br><br>"; }
else
{
echo "SHA-256 not supported.\n<br>";
}

?>
Output:
Standard DES:  stxmBiiYmh7pI
Extended DES:  _S4..somerDvmdD/PmC.
MD5:  $1$somethin$GA4ckKRuM3E5rq8U8mXDl.
Blowfish:  $2a$09$anexamplestringforsaleyquYOT6deAyd1trMgh1H1J150cnbQam
SHA-512:  $6$rounds=5000$anexamplestringf$HoJbnhS6A4T6v8RChpEYYWP1uHyLFViq.eGWVqwQVglkSC4jh0pt07AylxcSosNGu/c6mBhNwZ2s/ffIw5d3V0
SHA-256:  $5$rounds=5000$anexamplestringf$XNo5mypnz38N9LGTn3fvAwPevjbAEQwNOUT1uCG.et4

Popular Tutorials