SHA256在Go和PHP中给出了不同的结果

huangapple go评论81阅读模式
英文:

SHA256 in Go and PHP giving different results

问题

我正在尝试通过HTTP将一个SHA256哈希字符串发送到服务器,我希望通过执行SHA256哈希并验证两者是否匹配来进行身份验证。为了测试目的,我正在使用相同的字符串,但是我的结果不匹配。这可能与我的base64_encode调用的默认编码方案有关吗?谢谢。

在PHP中,我这样做:

$sha = hash("sha256", $url, true);
$sha = base64_encode(urlencode($sha));

而在Go中,我这样做:

//将字符串转换为字节切片
converted := []byte(to_hash)

//对字节切片进行哈希并返回结果字符串
hasher := sha256.New()
hasher.Write(converted)
return (base64.URLEncoding.EncodeToString(hasher.Sum(nil)))
英文:

I'm trying to send a SHA256 hashed string over HTTP to a server, where I want to authenticate by performing a SHA256 hash and verifying the two match. For testing purposes I'm using the same string, however my results do not match up. Could this be something with default encoding schemes for my base64_encode calls? Thanks.

In PHP I'm doing:

$sha = hash("sha256", $url, true);
$sha = base64_encode(urlencode($sha));

And in Go I'm doing

//convert string to byte slice
converted := []byte(to_hash)

//hash the byte slice and return the resulting string
hasher := sha256.New()
hasher.Write(converted)
return (base64.URLEncoding.EncodeToString(hasher.Sum(nil)))

答案1

得分: 6

我过了一段时间后成功解决了。我将两者都标准化为十六进制编码。为了实现这一点,我按如下方式更改了代码:

PHP:

$sha = hash("sha256", $url, false); //false是默认值,返回十六进制
//$sha = base64_encode(urlencode($sha)); //已删除

Go:

//将字符串转换为字节切片
converted := []byte(to_hash)

//对字节切片进行哈希并返回结果字符串
hasher := sha256.New()
hasher.Write(converted)
return (hex.EncodeToString(hasher.Sum(nil))) //更改为十六进制并删除URLEncoding
英文:

I was able to figure it out after a while. I standardized both to hexadecimal encoding. To accomplish this I changed the code as follows:

PHP:

$sha = hash("sha256", $url, false); //false is default and returns hex
//$sha = base64_encode(urlencode($sha)); //removed

Go:

//convert string to byte slice
converted := []byte(to_hash)

//hash the byte slice and return the resulting string
hasher := sha256.New()
hasher.Write(converted)
return (hex.EncodeToString(hasher.Sum(nil))) //changed to hex and removed URLEncoding

huangapple
  • 本文由 发表于 2013年4月20日 03:02:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/16111754.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定