Jump to content

Php Aes-Cbc Issue


Hsnopi

Recommended Posts

So I am trying to get this simple encryption to work.

 

I am using AES-CBC. and I know the iv is supposed to be randomly generated each time but for our purposes here it will be fine to keep it as it. Below is the code. It seems to encrypt fine but does not decrypt correctly.

 

<?php
$iv='1234567890123456';
$key='9tmp7ifi6n03yAmu';
qrdecrypt(encrypt("test",$key,$iv),$key,$iv);


function encrypt($str, $key,$iv)
{
echo 'in encrypt<br>key:'.$key.'<br>iv:'.$iv.'<br>string:'.$str.'<br>';
$td = mcrypt_module_open("rijndael-128", "", "cbc",$iv);
mcrypt_generic_init($td, $key, $iv);
$encrypted = mcrypt_generic($td, $str);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
echo "result is:".bin2hex($encrypted).'<br>returning and calling decrypt...<br>';
return bin2hex($encrypted);
}


function qrdecrypt($code, $key, $iv)
{
echo 'in decrypt<br>key:'.$key.'<br>iv:'.$iv.'<br>payload:'.$code.'<br>';
//$code = $this->hex2bin($code);
$td = mcrypt_module_open("rijndael-128", "", "cbc", "");
try
{
mcrypt_generic_init($td, $key, $iv);
}
catch (Exception $e)
{
echo $e->getMessage();
}
$decrypted = mdecrypt_generic($td, $code);
$t=var_export($decrypted,true);
echo '<br>Decrypted is:'.$t.'<br>';
mcrypt_generic_deinit($td);
echo "deinitted<br>";
mcrypt_module_close($td);
echo utf8_encode(trim($decrypted));
}

 

this results in...

 

 

in encrypt

key:9tmp7ifi6n03yAmu

iv:1234567890123456

string:test

result is:12bc2512b0faea4e6d21368df17f87a6

returning and calling decrypt...

in decrypt

key:9tmp7ifi6n03yAmu

iv:1234567890123456

payload:12bc2512b0faea4e6d21368df17f87a6

 

Decrypted is:'ro"?�o��h�ȫ_.���̬<�9ptاـ�'

deinitted

ro"?Ëoð¶hÊÈ«_.ÈÈøÌ¬<ã9ptاÙ

 

 

Any help at all would be appreciated. I am thoroughly stuck at this point.

Link to comment
https://forums.phpfreaks.com/topic/271376-php-aes-cbc-issue/
Share on other sites

yeah. i saw that. but that led me to my actual problem. Which, what you mentioned IS an issue. you'll note the commented out

//$code = $this->hex2bin($code);

That is what I was trying to get to work. I was so friend I never realized I never actually WROTE hex2bin! Sleep is a good thing!

So, if I take out the bin2hex in the encrypt, it works, if I add hex2bin in, instead, and write the function, it also works! go me. thanks for the second pair of eyes.

Link to comment
https://forums.phpfreaks.com/topic/271376-php-aes-cbc-issue/#findComment-1396471
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.