PHP的openssl_sign输出乱码而非预期SHA1哈希,如何解决?
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

