英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论