【经典问题】openssl aes-256-cbc key不承认32字符的key?
这绝对是一个经典问题
问题
在进行加密的时候使用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
并且传递了128bits
key的时候才会出现这个问题。
求解
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论