php runtime_error ai_generated true

警告:openssl_encrypt():传入的 IV 长度为 16 字节,超过了所选密码期望的 8 字节,将被截断,位于 /var/www/app/src/Crypto/Encryptor.php 第 23 行

Warning: openssl_encrypt(): IV passed is 16 bytes long which is longer than the 8 bytes expected by selected cipher, truncating in /var/www/app/src/Crypto/Encryptor.php on line 23

ID: php/openssl-iv-length-mismatch

其他格式: JSON · Markdown 中文 · English
90%修复率
87%置信度
1证据数
2024-01-10首次发现

版本兼容性

版本状态引入弃用备注
php 8.1 active
php 8.2 active
php 8.3 active
OpenSSL 3.0 active

根因分析

提供给 `openssl_encrypt` 或 `openssl_decrypt` 的初始化向量(IV)长度与所选密码方法所需的块大小不匹配(例如,AES-128-CBC 需要 16 字节,而 DES 需要 8 字节)。

English

The initialization vector (IV) length provided to `openssl_encrypt` or `openssl_decrypt` does not match the block size required by the selected cipher method (e.g., AES-128-CBC expects 16 bytes, but DES expects 8 bytes).

generic

官方文档

https://www.php.net/manual/en/function.openssl-encrypt.php

解决方案

  1. Use `openssl_cipher_iv_length($cipher)` to determine the correct IV length, then generate the IV accordingly: `$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));`
  2. Explicitly set the cipher method to match the IV length, e.g., change from `'des'` to `'aes-128-cbc'` if the IV is 16 bytes.

无效尝试

常见但无效的做法:

  1. Ignoring the warning and continuing execution 95% 失败

    Truncation of the IV can cause decryption failures or security vulnerabilities; the data may not be recoverable or may be improperly encrypted.

  2. Using `openssl_random_pseudo_bytes` without specifying the correct length 70% 失败

    The function defaults to 16 bytes, which may be incorrect for ciphers like DES (8 bytes) or RC4 (no IV); the length must match the cipher's block size.