【问题标题】:SHA256 in Go and PHP giving different resultsGo 和 PHP 中的 SHA256 给出不同的结果
【发布时间】:2013-04-13 06:25:53
【问题描述】:

我正在尝试通过 HTTP 将 SHA256 散列字符串发送到服务器,我想通过执行 SHA256 散列并验证两者匹配来进行身份验证。出于测试目的,我使用相同的字符串,但是我的结果不匹配。这可能是我的 base64_encode 调用的默认编码方案吗?谢谢。

在 PHP 中我正在做:

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

在 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 (base64.URLEncoding.EncodeToString(hasher.Sum(nil)))

【问题讨论】:

  • 在开始处理它们之前,请确保这两个字符串完全相同。您可以在其中一种语言的末尾有一个隐藏的字符(换行符、空格、制表符等),这将完全改变哈希值。
  • 确保使用相同的字符串编码。
  • 我在两边都使用了硬编码的“测试”这个词,以确保仍然无法正常工作。

标签: php go sha sha256


【解决方案1】:

过了一会我就明白了。我将两者都标准化为十六进制编码。为此,我将代码更改如下:

PHP:

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

去:

//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

【讨论】:

    猜你喜欢
    • 2017-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    • 1970-01-01
    • 2014-11-21
    相关资源
    最近更新 更多