【经典问题】openssl aes-256-cbc key不承认32字符的key?

发布于 2022-09-05 08:18:39 字数 2034 浏览 18 评论 0

这绝对是一个经典问题

问题

在进行加密的时候使用openssl_encrypt 使用的加密算法是AES-256-CBC,并且将key的长度加长到了256 即 32个字符的长度,但是这个时候,缺报错:

PHP Warning:  openssl_encrypt(): IV passed is 32 bytes long which is longer than the 16 expected by selected cipher

Demo

<?php

class Demo {

    const METHOD = 'AES-256-CBC';

    static function encrypt($text, $key) {
        $iv = md5($key);
        var_dump($iv);
        return openssl_encrypt($text, self::METHOD, $key, false, $iv);
    }

    static function decrypt($text, $key) {
        $iv = md5($key);
        $opensslDecrypt = openssl_decrypt($text, self::METHOD, $key, false, $iv);
        return $opensslDecrypt;
    }
}


$hash_str = 'abcdefghi';
$key = '112358';


// 加密
$token = Demo::encrypt($hash_str, $key);
var_dump($token);

// 解密
$result = Demo::decrypt($token, $key);
var_dump($result);

/*
string(32) "e44f8cf63970db5c2df0a18153bcdf49"

PHP Warning:  openssl_encrypt(): IV passed is 32 bytes long which is longer than the 16 expected by selected cipher, truncating in /Users/sun.huajie/Desktop/test2.php on line 10

string(24) "1pxTRg6n4ejzdrVKxxzhuQ=="

PHP Warning:  openssl_decrypt(): IV passed is 32 bytes long which is longer than the 16 expected by selected cipher, truncating in /Users/sun.huajie/Desktop/test2.php on line 15
string(9) "abcdefghi"
*/

疑惑的地方

To verify the length/format of your IV, you can provide strings of different lengths and check the error log. For example, in PHP 5.5.9 (Ubuntu 14.04 LTS), providing a 32 byte hex string (which would represent a 16 byte binary IV) throws an error.
"IV passed is 32 bytes long which is longer than the 16 expected by the selected cipher" (cipher chosen was 'aes-256-cbc' which uses an IV of 128 bits, its block size). Alternatively, you can use openssl_cipher_iv_length().

按照官方手册上来的话,只有在使用高位算法AES-256-CBC并且传递了128bitskey的时候才会出现这个问题。

求解

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文