MD5() - Genereate a hash string
E.g:
HASH_HMAC E.g:
<?php
$str= 'techsol99';
echo md5($str);
?>
OP: bae06a769ecb6bbaa0e85370eff0458d
Generate a keyed hash value using the HMAC method
Ensures authentication between 2 parties while sending data over URL as query params.
E.g:
Lets say 2 parties A and B. A wants send data to B as url query params. Then A needs to be generated hash string with query params and send hash string along with query params.
When B recieves the query params then generate hash string with query params without hash value. After that compare with Newly generated hash string with query param hash string.
NOTE: salt should be shared by 2 parties.
A's code:
<?php
$queryString = 'subId=123&chapId=345';
$salt = 'techsol';
echo hash_hmac('sha256', $queryString, $salt, false); // Result: 688a864a96c1280bf118394e1d131edb9a4d09d3e2120cc78b92735b2ceff333
?>
URL : http://xyz.com?subId=123&chapId=345&key=688a864a96c1280bf118394e1d131edb9a4d09d3e2120cc78b92735b2ceff333
B's code:
<?php
$urlQueryString = 'subId=123&chapId=345&key=688a864a96c1280bf118394e1d131edb9a4d09d3e2120cc78b92735b2ceff333';
parse_str($urlQueryString,$urlQueryArr);
$clientHash = $urlQueryArr['key'];
$pos = strpos($urlQueryString,'&key');
$queryString = substr($urlQueryString,0,$pos );
$salt = 'techsol';
$newHash = hash_hmac('sha256', $queryString, $salt, false);
if($clientHash != $newHash){
echo "Data has tampered";
} else {
echo "Not tampered";
}
?>
MCRYPT_DECRYPT:
NOTE: salt should be 16 char length.
function encryptStr($plainText) {
$salt = 'techsol99_php_me';
return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $salt, $plainText, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))));
}
function decryptStr($encText) {
$salt = 'techsol99_php_me';
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $salt, base64_decode($encText), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)));
}
E.g:
$plainText = 'techsol99';
echo $encText = encryptStr($plainText); OP: 0AHc0bAXOdP+XkaYpdoYcNmFvL9SVNugUiK4TIksPBE=
echo decryptStr($encText); //OP: techsol99
0 Comments