drqyxkzbs21968684 2017-03-14 12:56
浏览 57
已采纳

使用AES-256加密时清空输出?

I have a string encrypted with AES 128 CBC, which I need to decrypt. I have the key which seems to work fine. The problem is with the initialization vector (IV).

The IV is 16 bytes long,

B409678003171307B8B8B8B8B8B8B8B8

but when I add it to my script, OpenSSL truncates it saying it's 32 long like so:

openssl_decrypt(): IV passed is 32 bytes long which is longer than the 16 expected by selected cipher, truncating

I guess it means it is 32 characters long - but how do I make it understand it's just 16 bytes?

UPDATE: using hex2bin on the IV solved the truncating - but my openssl_decrypt yields nothing. Also did the hex2bin on the key, still no output. Simplified the code to make it easier to find the problem:

<?php
$str = "7F53B967F1BF7C9EC26B0C405E453ABD";
$k = "F71D4590A6E6E219EBBE8BFE9D3DC21A";
$intv = "B409678003171307B8B8B8B8B8B8B8B8";
$key = hex2bin($k);
$iv = hex2bin($intv);
$plaintext = openssl_decrypt($str, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
print_r($plaintext);
?>

So, is the hex2bin the wrong way to go? Or is there something wrong in how I use the openssl_decrypt? There are NO errors in the PHP error_log.

Thanks in advance!

  • 写回答

1条回答 默认 最新

  • dongtang4019 2017-03-14 15:09
    关注

    OK this appears to achieve the same results as the web-based service linked by the OP. The key steps are a) in addition to $k and $intv, make sure you also convert the encrypted $str to binary from its hex representation b) supply the extra flag OPENSSL_ZERO_PADDING c) when you echo or var_dump or print_r the output, make sure you do a conversion back to hex so the output is readable

    $encrypted = "7F53B967F1BF7C9EC26B0C405E453ABD";
    $k = "F71D4590A6E6E219EBBE8BFE9D3DC21A";
    $intv = "B409678003171307B8B8B8B8B8B8B8B8";
    $str = hex2bin($encrypted);
    $key = hex2bin($k);
    $iv = hex2bin($intv);
    
    $decrypted = openssl_decrypt($str, 'AES-128-CBC', $key,  OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING, $iv);
    $str_decrypted = bin2hex($decrypted);
    var_dump($str_decrypted);
    

    output:

    string(32) "2f2f0c1335000000046d372b27230f15"
    

    NOTE: I can't be sure that this is in fact the decrypted form of the originally encrypted data. It just matches the web-based service. I'm assuming the value you linked is in fact the correct value. Simply adding the OPENSSL_ZERO_PADDING flag to your original code can get rid of the errors but the output will be different. Maybe try some experimenting.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于下拉菜单选项关联的问题
  • ¥15 如何修改pca中的feature函数
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R