I'm writing an encryption to my application and website, but I don't know how to correctly encrypt the string in php. Decryption is already done by this code:
function decrypt_blowfish($data,$key){
$iv=pack("H*" , substr($data,0,16));
$key=pack("H*" , $key);
$x =pack("H*" , substr($data,16));
$res = mcrypt_decrypt(MCRYPT_BLOWFISH, $key, $x , MCRYPT_MODE_CBC, $iv);
return $res;
}
I tried with simple:
function encrypt_blowfish($data,$key){
$iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$crypttext = mcrypt_encrypt(MCRYPT_BLOWFISH, $key, $data, MCRYPT_MODE_CBC, $iv);
return $crypttext;
}
But it returns strang ASCI chars instead of correct blowfish code. Could somebody explain me why, and what am I doing wrong? Thanks in advance
C.H.
function decrypt_blowfish($data,$key){
$iv=pack("H*" , substr($data,0,16));
$x =pack("H*" , substr($data,16));
$res = mcrypt_decrypt(MCRYPT_BLOWFISH, $key, $x , MCRYPT_MODE_CBC, $iv);
return $res;
}
function encrypt_blowfish($data,$key){
$iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$crypttext = mcrypt_encrypt(MCRYPT_BLOWFISH, $key, $data, MCRYPT_MODE_CBC, $iv);
return bin2hex($iv . $crypttext);
}
$string = encrypt_blowfish('hello world', 'abc123');
echo 'ENCRYPTED: ' . $string . "\n";
echo 'DECRYPTED: ' . decrypt_blowfish($string, 'abc123');
Try that. In the decryption function you are converting from hex to binary, so it is expecting a hex value to be passed. Your encryption function is outputting binary, so you need to convert it to hex with the above change.