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

- **ID:** `php/openssl-iv-length-mismatch`
- **领域:** php
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| php 8.1 | active | — | — |
| php 8.2 | active | — | — |
| php 8.3 | active | — | — |
| OpenSSL 3.0 | active | — | — |

## 解决方案

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.
   ```

## 无效尝试

- **Ignoring the warning and continuing execution** — Truncation of the IV can cause decryption failures or security vulnerabilities; the data may not be recoverable or may be improperly encrypted. (95% 失败率)
- **Using `openssl_random_pseudo_bytes` without specifying the correct length** — 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. (70% 失败率)
