E_WARNING php auth_error ai_generated true

警告:openssl_verify():提供的密钥参数无法转换为公钥,位置:/var/www/app/src/Auth/JwtValidator.php第42行

Warning: openssl_verify(): Supplied key param cannot be coerced into a public key in /var/www/app/src/Auth/JwtValidator.php on line 42

ID: php/openssl-key-format-mismatch

其他格式: JSON · Markdown 中文 · English
90%修复率
88%置信度
1证据数
2023-09-05首次发现

版本兼容性

版本状态引入弃用备注
PHP 7.4 active
PHP 8.0 active
PHP 8.1 active
PHP 8.2 active
PHP 8.3 active
OpenSSL 1.1.1 active
OpenSSL 3.0 active

根因分析

提供给openssl_verify()的公钥格式不受支持(例如PKCS#1而非PKCS#8,或缺少正确的PEM头),导致OpenSSL拒绝该密钥。

English

The public key provided to openssl_verify() is in an unsupported format (e.g., PKCS#1 instead of PKCS#8, or missing proper PEM headers), causing OpenSSL to reject the key.

generic

官方文档

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

解决方案

  1. Ensure the public key is in PKCS#8 PEM format. Convert if needed using OpenSSL CLI: `openssl pkey -in private_key.pem -pubout -out public_key.pem`. Then load it in PHP with `$key = file_get_contents('/path/to/public_key.pem');` and ensure no extra whitespace.
  2. Use `openssl_get_publickey()` instead of passing the key string directly; this function auto-detects and converts formats. Example: `$pubKey = openssl_get_publickey(file_get_contents('key.pem')); if ($pubKey === false) { echo openssl_error_string(); }`

无效尝试

常见但无效的做法:

  1. 90% 失败

    The issue is the key format structure (PEM headers, line breaks), not just encoding. A raw binary key without proper boundaries will fail the same way.

  2. 85% 失败

    Extra whitespace or BOM can corrupt the PEM header; OpenSSL requires exact format: `-----BEGIN PUBLIC KEY-----` on its own line.