PHP实现SHA1十六进制字符串转Base64与在线工具结果不一致问题求助
Let's break down why your current PHP code isn't matching the online tool results, and how to fix it quickly.
The Root Problem
Right now, you're running base64_encode() directly on the hexadecimal string text ('69F13F8064D00D5CBAE0CADEB399B6E8A6C3314E'). But the online tools are doing two key steps:
- First, they decode the hex string into raw binary data (the actual bytes represented by the hex values)
- Then they encode that binary data into Base64.
Your code skips the critical hex-to-binary conversion step, so you're encoding the characters of the hex string itself instead of the underlying data. That's why your output is longer and doesn't match the expected result.
The Correct PHP Code
Use hex2bin() to convert the hex string to binary first, then apply base64_encode():
$hexStr = '69F13F8064D00D5CBAE0CADEB399B6E8A6C3314E'; $binaryData = hex2bin($hexStr); echo base64_encode($binaryData);
This will output exactly what the online tools give you: afE/gGTQDVy64Mres5m26KbDMU4=
For Older PHP Versions (Pre-5.4)
If hex2bin() isn't available (it was added in PHP 5.4), use pack('H*', $hexStr) instead—it does the same hex-to-binary conversion:
$hexStr = '69F13F8064D00D5CBAE0CADEB399B6E8A6C3314E'; $binaryData = pack('H*', $hexStr); echo base64_encode($binaryData);
This will produce the correct result too.
内容的提问来源于stack exchange,提问作者Abu Enejoh Christopher

