Go和PHP中的SHA256给出了不同的结果 [英] SHA256 in Go and PHP giving different results

查看:176
本文介绍了Go和PHP中的SHA256给出了不同的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



在PHP中,我正在做:

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

在Go中,我正在做

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

//散列字节片段并返回结果字符串
hasher:= sha256.New()
hasher.Write(转换后的)
return(base64.URLEncoding.EncodeToString(hasher.Sum(nil)))

解决方案

过了一会儿,我才弄明白了。我将这两个标准都标准化为十六进制编码。为了实现这一点,我改变了代码如下:

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

前往:

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

//散列字节片并返回结果字符串
hasher:= sha256.New()
hasher.Write(转换)
返回(hex.EncodeToString(hasher.Sum(nil))))//更改为十六进制并删除URLEncoding


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

解决方案

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

这篇关于Go和PHP中的SHA256给出了不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆