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

PHP实现SHA1十六进制字符串转Base64与在线工具结果不一致问题求助

Fixing PHP Base64 Encoding Mismatch with Hex Input

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:

  1. First, they decode the hex string into raw binary data (the actual bytes represented by the hex values)
  2. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 12:07:49