You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP的openssl_sign输出乱码而非预期SHA1哈希,如何解决?

Why You're Seeing "Gibberish" Instead of a SHA1 Hash

The issue here is super common—you’re getting raw binary data from openssl_sign() instead of the base64-encoded string you’re expecting.

When openssl_sign() runs, it writes raw binary bytes directly into the $signature variable. These bytes don’t correspond to readable ASCII characters, which is why you’re seeing that messy output. Your expected result is a base64-encoded version of this binary data—this is the standard way to represent cryptographic signatures as human-readable text.

Fixed Code

Here’s how to adjust your code to get the format you want:

$pkeyid = openssl_get_privatekey($priv_key); 
// Compute the raw binary signature
openssl_sign($data, $signature, $pkeyid, OPENSSL_ALGO_SHA1);
// Encode the binary signature to base64 for readable output
echo base64_encode($signature);
// Free the key from memory
openssl_free_key($pkeyid);

Quick Note on Verification

If you later need to verify this signature (using openssl_verify()), you’ll first need to decode the base64 string back to its original binary form:

// Assume $receivedSignature is the base64 string you generated
$binarySignature = base64_decode($receivedSignature);
$verificationResult = openssl_verify($data, $binarySignature, $pub_key, OPENSSL_ALGO_SHA1);

That should give you the clean, readable signature format you were expecting!

内容的提问来源于stack exchange,提问作者user1235861

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:33:10