<p>Hey all, I'm encountering a strange issue when building a sha256 hash of a string - the generated hex string differs from the equivalent in nodejs. Using the following code, I am receiving <code>c2ea634c993f050482b4e6243224087f7c23bdd3c07ab1a45e9a21c62fad994e</code>:</p>
<pre><code>package main
import "fmt"
import "crypto/hmac"
import "crypto/sha256"
import "encoding/hex"
func main() {
s := "hello world"
mac := hmac.New(sha256.New, []byte(""))
mac.Write([]byte(s))
s = hex.EncodeToString(mac.Sum(nil))
fmt.Printf("%s\n", s)
}
</code></pre>
<p>in node:</p>
<pre><code>const crypto = require("crypto");
const a = "hello world";
const r = crypto.createHash('sha256').update(a).digest('hex');
console.log(r);
</code></pre>
<p>I receive: <code>b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9</code>. </p>
<p>Does anyone see anything that would be causing this?</p>
<hr/>**评论:**<br/><br/>TheRealHellcat: <pre><p>My guess would be that in GO you create a HMAC while on the JS side you create a simple SHA256.</p>
<p>Try sha256.Sum() or just sha256.New() instead of hmac.New(sha256.New, []byte("")).</p></pre>mdwhatcott: <pre><pre><code>package main
import "fmt"
import "crypto/sha256"
import "encoding/hex"
func main() {
s := "hello world"
h := sha256.New()
h.Write([]byte(s))
s = hex.EncodeToString(h.Sum(nil))
fmt.Printf("%s\n", s) // b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9
}
</code></pre></pre>dadleyy: <pre><p>Awesome, thank you!</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传