Skip to content
</> Mücahit TopalA developer's notebook

Blog/PHP & MySQL

Encryption with PHP: Hashing

Mücahit Topal 6 min read 17,789 views TREN

Encryption with PHP: Hashing

To keep our data secure, we feel the need to encrypt our code or our data. In this post we will see how to get the digest of a piece of data, that is, its hash, with different algorithms in PHP.

PHP comes with many encryption libraries ready to use.

Let's Go Through Some of Them Together, with Examples.

I Will Cover Symmetric and Asymmetric Encryption in Another Post...

  1. password_hash()

This function can be used in two ways. The function's  most important feature is that it automatically uses the PHP 5 API Key, so by default it encrypts using the PHP 5 API Key defined specifically for you, and thanks to this the Decode function does not work on other computers. It also works on PHP 5.5 and all versions above it. I can say it is the most secure hash function, the one I recommend and the one recommended by PHP developers. Every time the function runs it produces a different result for you, and it always creates a 60-character string.

  • Default Mode : Its Simple Usage by Default
$MyPassword="mucahittopal.com";

$Password=password_hash($MyPassword, PASSWORD_DEFAULT);
var_dump($Password);

//string(60) "$2y$10$5LIS6fxo3fvgJX6A9Ewtye1AS30JvbMsPnzn8a6ZNg11nPEU69Vyu"
//string(60) "$2y$10$Ksbl3YmvfjNX3f6tKtpL6efQeYJRKSUgZt1wDV7/KydrEswG7oM7G"
//string(60) "$2y$10$NHyNpJwLvguhaf6kOPW/qenvF2AjGHyGR8Y4m2QVNlGimfshOsFYy"

//As you can see, it produces a different result for you every time it runs

 

  • BCRYPT Mode : You Can Encrypt the Same Text in 11 Different Ways.
$MyPassword='mucahittopal.com';
	
	// We specify how much the function may spend on the CPU
    // Note; the cost value cannot be less than 4 or greater than 31.
	// We create the variable as an array.
    $Secenekler = [
        'cost' => 12
    ];
    $MyHashedPassword= password_hash($MyPassword, PASSWORD_BCRYPT, $Secenekler);
	var_dump($MyHashedPassword);

//string(60) "$2y$12$X9HcJ/bqGhEmbRfna9wTUOeytJvnu1s8pfilc5WkdVv3fGMlcy2aK"
	$MyPassword='mucahittopal.com';
	
	// We specify how much the function may spend on the CPU
    // We generate the function's salt value randomly
    // Note; the cost value cannot be less than 4 or greater than 31.
    // Warning; entering a static salt value is not recommended, it is better for it to take a random value.
    $Secenekler = [
        'cost' => 8,
        'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM)
    ];
	
    $MyHashedPassword= password_hash($MyPassword, PASSWORD_BCRYPT, $Secenekler);
	var_dump($MyHashedPassword);
	
	//string(60) "$2y$08$B90YROPxCAzqXZhEXdf9U.CgfWdY4b2tFZVt3NeZUY/.i0M4K53Ny"

Now let's look at the details of the functions used for the Hash values we created, using the password_get_info() function. 

$MyHashedPassword='$2y$08$B90YROPxCAzqXZhEXdf9U.CgfWdY4b2tFZVt3NeZUY/.i0M4K53Ny';
	$MyHashedPassword_Info=password_get_info($MyHashedPassword);
	var_dump($MyHashedPassword_Info);
/*
array(3) {
 ["algo"]=> int(1)
 ["algoName"]=> string(6) "bcrypt" 
 ["options"]=> array(1) { 
          ["cost"]=> int(8)
  } 
}
*/

To check whether hashes you created in the past with functions like crypt() need to be regenerated, we can use the password_needs_rehash() function.

$MyHashedPassword='$2y$10$NHyNpJwLvguhaf6kOPW/qenvF2AjGHyGR8Y4m2QVNlGimfshOsFYy';   
    $Secenekler = [
        'cost' => 8,
        'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM)
    ];
    $Sonuc = password_needs_rehash($MyHashedPassword, PASSWORD_DEFAULT, $Secenekler);// Returns True || False
    if($Sonuc) {
        echo 'The hash value does not need to be regenerated.';
    } else {
        echo 'The hash value needs to be regenerated.';
    }

//The hash value does not need to be regenerated.

 

So how are we going to check it, how will we determine that the result we hashed is correct?

For this, the password_verify() function comes into play. Let's take a quick look at how it is used.

$MyPassword='mucahittopal.com';
$MyHashedPassword='$2y$10$NHyNpJwLvguhaf6kOPW/qenvF2AjGHyGR8Y4m2QVNlGimfshOsFYy';

if(password_verify($MyPassword, $MyHashedPassword)) { //Returns True || False to Us
	echo "Hash Check Successful";
}else{
	echo "Hash Check Failed";
}

//We Get the Output Hash Check Successful...

 

  1. crypt()

In its simple usage it returns a string of 34 characters. It can also produce results for more than one algorithm.

  • Simple Usage - Returns a 34-character password.
  • CRYPT_STD_DES - Standard DES encryption using a 2-character salt.
  • CRYPT_EXT_DES - Extended DES encryption using a 9-character salt.
  • CRYPT_MD5 - 12-character MD5 encryption starting with $1$.
  • CRYPT_BLOWFISH - 16-character Blowfish encryption starting with $2$ or $2a$.
  • CRYPT_SHA256 - 16-character, starting with $5$
  • CRYPT_SHA512 - 
//Simple Usage

$MyPassword='mucahittopal.com';
	
	$Sonuc=crypt($MyPassword);
	var_dump($Sonuc);
//string(34) "$1$mP..134.$IqeCjTFgP.HoBhaqDUM.k0"


//CRYPT_STD_DES 
	
  if (CRYPT_STD_DES == 1)
    {
		$Sonuc=crypt($MyPassword,'mu');
		var_dump($Sonuc);
    }
	//string(13) "mugiuV2llrh52" 
	
	
//CRYPT_EXT_DES 
    if (CRYPT_EXT_DES == 1)
    {
		$Sonuc=crypt($MyPassword,'mucahitto');
		var_dump($Sonuc);
    }
	//string(13) "mugiuV2llrh52" 
	

//CRYPT_MD5 	
    if (CRYPT_MD5 == 1)
    {
		$Sonuc=crypt($MyPassword,'$1$mucahitt$');
		var_dump($Sonuc);
    }
	//string(34) "$1$mucahitt$g5DTXogTaKSXXjP2RbwVC1"
	

//CRYPT_BLOWFISH 	
    if (CRYPT_BLOWFISH == 1)
    {
		$Sonuc=crypt($MyPassword,'$2a$09$mucahittopal.commucahitto$');
		var_dump($Sonuc);
    }
	//string(60) "$2a$09$mucahittopal.commucaheZ9HbiGxBmHP7OvXhsjICFN3UhrUQUh."
	

//CRYPT_SHA256 	
    if (CRYPT_SHA256 == 1) 
    {
		$Sonuc=crypt($MyPassword,'$5$mucahittopal.commucahi$');
		var_dump($Sonuc);
    }
	//string(63) "$5$mucahittopal.com$5tNw8xUNvLBQl03BsxtWgVpOq7.ZX1kRFd5hrro/YR2"

	
//CRYPT_SHA512  	
    if (CRYPT_SHA512  == 1) 
    {
		$Sonuc=crypt($MyPassword,'$6$mucahittopal.commucahi$');
		var_dump($Sonuc);
    }
	//string(106) "$6$mucahittopal.com$kYsBPespOuU05pXB9HksQNvJjOtgUIDW3DzvgrXgRutqAyvx1gSa93bahCHnjw2TZbGUvqWBmEcYcHcud6vr7."

 

 

  1. md5()

This is the function generally used by everyone and regarded as the simplest one.

  • Case 1

If you optionally specify TRUE the MD5 digest is returned with a length of 16 bytes​.

	$MyPassword='mucahittopal.com';
		
	$Sonuc=md5($MyPassword,true);
	var_dump($Sonuc);
	//string(16) "±,\ƒÇþmãXâ¶Ô÷,Ñ"
  • Case 2

​By default FALSE is specified. If you specify FALSE anyway, a 32-byte long result is returned.

	$MyPassword='mucahittopal.com';
		
	$Sonuc=md5($MyPassword,false);
	var_dump($Sonuc);
	//string(32) "b12c5c83c7fe6de35811e2b6d4f72cd1"

 

 

  1. sha1()

  • ​Case 1

If you optionally specify TRUE the sha1 digest is returned with a length of 20 bytes​.

	$MyPassword='mucahittopal.com';
		
	$Sonuc=sha1($MyPassword,true);
	var_dump($Sonuc);
	//string(20) "5ö‰0U¼0ÜŒ‹Œ¹Ìp–Šx"
  • Case 2

​By default FALSE is specified. If you specify FALSE anyway, a 40 byte long result is returned.

	$MyPassword='mucahittopal.com';
		
	$Sonuc=sha1($MyPassword,false);
	var_dump($Sonuc);
	//string(40) "35f68918305506bc30c39c8c8b8cb9cc70968a78"

 

 

  1. crc32()

This function returns the hash value as an integer.

	$MyPassword='mucahittopal.com';
		
	$Sonuc=crc32($MyPassword);
	var_dump($Sonuc);
	//int(1011593091)

 

  1. hash()

By default this function is used with 2 parameters. A 3rd parameter can be added if desired. Thanks to its internal structure, the hash function lets us use many algorithms by passing the algorithm name as a parameter. With hash_algos() we can see which algorithms are used.

print_r(hash_algos());

/*
Array
(
    [0] => md2
    [1] => md4
    [2] => md5
    [3] => sha1
    [4] => sha224
    [5] => sha256
    [6] => sha384
    [7] => sha512
    [8] => ripemd128
    [9] => ripemd160
    [10] => ripemd256
    [11] => ripemd320
    [12] => whirlpool
    [13] => tiger128,3
    [14] => tiger160,3
    [15] => tiger192,3
    [16] => tiger128,4
    [17] => tiger160,4
    [18] => tiger192,4
    [19] => snefru
    [20] => snefru256
    [21] => gost
    [22] => adler32
    [23] => crc32
    [24] => crc32b
    [25] => fnv132
    [26] => fnv164
    [27] => joaat
    [28] => haval128,3
    [29] => haval160,3
    [30] => haval192,3
    [31] => haval224,3
    [32] => haval256,3
    [33] => haval128,4
    [34] => haval160,4
    [35] => haval192,4
    [36] => haval224,4
    [37] => haval256,4
    [38] => haval128,5
    [39] => haval160,5
    [40] => haval192,5
    [41] => haval224,5
    [42] => haval256,5
)
*/

//Since I did not want to write and run each one individually, I wanted to run them with a small loop and show you.

       $MyPassword='mucahittopal.com';
		
		foreach (hash_algos() as $Algoritma) { 
        $Sonuc = hash($Algoritma, $MyPassword, false); 
        var_dump($Sonuc); 
	} 

/*
string(38) "md2-->a4dda20fb8810fbfa4f4971c5365089c"
string(38) "md4-->11f8ec229c5b36251977f9a9de312c41"
string(38) "md5-->b12c5c83c7fe6de35811e2b6d4f72cd1"
string(47) "sha1-->35f68918305506bc30c39c8c8b8cb9cc70968a78"
string(65) "sha224-->c9f917c598840f0b44afb3136ce56382f5d308fed1d374f81d7170af"
string(73) "sha256-->4096a48b0892c1c8520d1c421d89cc6cd27c10aa13bc18ec5eada82f4f3205e5"
string(105) "sha384-->521042c7ca54c7e81a388c76e06f6d04165a1dde245d6a66d76c978380291213a4474e697a00c35c62780466aa34f2d5"
string(137) "sha512-->94df95f5ced4a7019dae865be789d0a12f5c72b64292afe71929187c8c70f197670ba465bf6a34c33028adda6f57af6217f7013b36ea2eeae9c65b6132cb1737"
string(44) "ripemd128-->520d108840fa0c53c601c58740c011f6"
string(52) "ripemd160-->8755491fc65d207fe9d8412a4f2e1ae463a174f8"
string(76) "ripemd256-->2594dd34ecb0031f2c3caf0269d6f6c885c353ec44817153c6ffc375c3704e7b"
string(92) "ripemd320-->b0fd61f0d3d2ea90bbabafa9dd356051d8f338e2410cdc0be3d982321833555880a635ee044a86ae"
string(140) "whirlpool-->13949d406e4317b9e221f6c498d174fe9d24def94706359f496cfb1273438ea766aeb20c973e4d9002e4b5a4de3d173a4b102dfb6f8dd1891366caee751ff10e"
string(45) "tiger128,3-->faf653e408b2805f5c0e81899174a628"
string(53) "tiger160,3-->faf653e408b2805f5c0e81899174a6286872c89d"
string(61) "tiger192,3-->faf653e408b2805f5c0e81899174a6286872c89d6db53716"
string(45) "tiger128,4-->a14f71150b48143000fd3a2d1fc6d3b1"
string(53) "tiger160,4-->a14f71150b48143000fd3a2d1fc6d3b1a2d86960"
string(61) "tiger192,4-->a14f71150b48143000fd3a2d1fc6d3b1a2d869602be6a118"
string(73) "snefru-->b81764a116f6ce9037b1939c0f482922cd1687f0c2d658e3f74bd03a1077beda"
string(76) "snefru256-->b81764a116f6ce9037b1939c0f482922cd1687f0c2d658e3f74bd03a1077beda"
string(71) "gost-->62b84bddf91f28fae45ea4553c369c13983acc482cfb2f85d338a91bf6673efe"
string(18) "adler32-->38270679"
string(16) "crc32-->2a8ebd10"
string(17) "crc32b-->3c4baf83"
string(17) "fnv132-->350081f1"
string(25) "fnv164-->f41986efea5ed531"
string(16) "joaat-->1b1238dd"
string(45) "haval128,3-->96a5eb4b0c43f79432a1c2e0acbdc754"
string(53) "haval160,3-->2a13e0c987806b9fd143cbc9af00715beab25faa"
string(61) "haval192,3-->4e7d04033314b827202682189580da3a18f729261061b312"
string(69) "haval224,3-->a4e06ef7257aca7eba1e61c841d0a49e200d98063b2877d45ef60708"
string(77) "haval256,3-->108f4c1296f748d189961737229850a9c33bc48ac9df1816ce1baf30d378ea4b"
string(45) "haval128,4-->738f553849f7876caf59e37d87f1464c"
string(53) "haval160,4-->0cd47051a612f17e311dd1581fdd60fae3a2a85c"
string(61) "haval192,4-->97c1dfd7184ec36ff6d3d1cd9e81d261ae6d811ac1cb0014"
string(69) "haval224,4-->dae6933f80dd813a91d8424fbcad3aae5f2142a4d3fe4024768e3608"
string(77) "haval256,4-->6a3f4c90b1b65959092afd0f518dab40c6255647a74302c7812c2a54701fffe7"
string(45) "haval128,5-->139958a7ec9ad2dc04da93d703f40cc7"
string(53) "haval160,5-->53ef16c74d34982fd9e365d9421445a2a476486a"
string(61) "haval192,5-->717de16e76bc0c9345faf325b152fd5b0c84a727428a744f"
string(69) "haval224,5-->0992ce75d95d395a20a7a9a79a3ab8e8c50e526e46a5a76f5a179563"
string(77) "haval256,5-->c1dd6fc748aa0c704632a792e3124736913eed59c92419a3ea0439b8af88ad87"
*/

       $MyPassword='mucahittopal.com';
		
		foreach (hash_algos() as $Algoritma) { 
        $Sonuc = hash($Algoritma, $MyPassword, true); 
        var_dump($Sonuc); 
	} 

/*
string(22) "md2-->§›¢∏Åø§ÙóSeú"
string(22) "md4-->¯Ï"ú[6%w˘©fi1,A"
string(22) "md5-->±,\É«˛m„X‚∂‘˜,—"
string(27) "sha1-->5ˆâ0Uº0√úåãåπÃpñäx"
string(37) "sha224-->…˘≈òÑDØ≥lÂcÇı”˛—”t¯qpØ"
string(41) "sha256-->@ñ§ãí¡»RBâÃl“|™ºÏ^≠®/O2Â"
string(57) "sha384-->RB« T«Ë8åv‡omZfi$]jf◊lóÉÄ)§GNiz√\bxf™4Ú’"
string(73) "sha512-->îflïıŒ‘ßùÆÜ[Áâ–°/\r∂BíØÁ)|åpÒógeøj4√0(≠⁄oWØb˜;6Í.ÍÈ∆[a2À7"
string(28) "ripemd128-->Rà@˙S∆≈á@¿ˆ"
string(32) "ripemd160-->áUI∆] ÈÿA*O.‰c°t¯"
string(44) "ripemd256-->%î›4Ï∞,<Øi÷ˆ»Ö√SÏDÅqS∆ˇ√u√pN{"
string(52) "ripemd320-->∞˝a”“Íꪴة›5`QÿÛ8‚A‹„ŸÇ23UXĶ5ÓJÜÆ"
string(76) "whirlpool-->îù@nCπ‚!ˆƒò—t˛ù$fi˘G5üIl˚sCéßfÆ≤ó>Mꉵ§fi=:K-˚oç—âf ÓuÒ"
string(29) "tiger128,3-->˙ˆS‰≤Ä_\Åâët¶("
string(33) "tiger160,3-->˙ˆS‰≤Ä_\Åâët¶(hr»ù"
string(37) "tiger192,3-->˙ˆS‰≤Ä_\Åâët¶(hr»ùmµ7"
string(29) "tiger128,4-->°OqH0˝:-∆”±"
string(33) "tiger160,4-->°OqH0˝:-∆”±¢ÿi`"
string(37) "tiger192,4-->°OqH0˝:-∆”±¢ÿi`+ʰ"
string(41) "snefru-->∏d°ˆŒê7±ìúH)"Õá¬÷X„˜K–:wæ⁄"
string(44) "snefru256-->∏d°ˆŒê7±ìúH)"Õá¬÷X„˜K–:wæ⁄"
string(39) "gost-->b∏K›˘(˙‰^§U<6úò:ÃH,˚/Ö”8©ˆg>˛"
string(14) "adler32-->8'y"
string(12) "crc32-->*éΩ"
string(13) "crc32b-->5ÅÒ"
string(17) "fnv164-->ÙÜÔÍ^’1"
string(12) "joaat-->8›"
string(29) "haval128,3-->ñ•ÎKC˜î2°¬‡¨Ω«T"
string(33) "haval160,3-->*‡…áÄkü—CÀ…Øq[Í≤_™"
string(37) "haval192,3-->N}3∏' &ÇïÄ⁄:˜)&a≥"
string(41) "haval224,3-->§‡n˜%z ~∫a»A–§ûò;(w‘^ˆ"
string(45) "haval256,3-->èLñ˜H—âñ7"òP©√;ƒä…flŒØ0”xÍK"
string(29) "haval128,4-->sèU8I˜álØY„}áÒFL"
string(33) "haval160,4-->‘pQ¶Ò~1—X›`˙„¢®\"
string(37) "haval192,4-->ó¡fl◊N√oˆ”—ÕûÅ“aÆmÅ¡À"
string(41) "haval224,4-->⁄Êì?Ä›Å:ëÿBOº≠:Æ_!B§”˛@$vé6"
string(45) "haval256,4-->j?Lê±∂YY	*˝Qç´@∆%VGßC«Å,*TpˇÁ"
string(29) "haval128,5-->ôXßÏö“‹⁄ì◊Ù«"
string(33) "haval160,5-->SÔ«M4ò/Ÿ„eŸBE¢§vHj"
string(37) "haval192,5-->q}·nvºìE˙Û%±R˝[Ñß'BätO"
string(41) "haval224,5-->	íŒuŸ]9Z ß©ßö:∏Ë≈RnF•ßoZïc"
string(45) "haval256,5-->¡›o«H™pF2ßí„G6ë>ÌY…$£Í9∏Øà≠á"
*/

 

I Hope This Has Been a Useful Post. Stay with Love...

,,,,,,,,,

Share X Facebook LinkedIn WhatsApp

More from this category

Comments 0

No comments yet.

Leave a comment

Comments appear after approval.