Sha256 hash discrepancy w/ nodejs

polaris · · 306 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Hey all, I&#39;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 &#34;fmt&#34; import &#34;crypto/hmac&#34; import &#34;crypto/sha256&#34; import &#34;encoding/hex&#34; func main() { s := &#34;hello world&#34; mac := hmac.New(sha256.New, []byte(&#34;&#34;)) mac.Write([]byte(s)) s = hex.EncodeToString(mac.Sum(nil)) fmt.Printf(&#34;%s\n&#34;, s) } </code></pre> <p>in node:</p> <pre><code>const crypto = require(&#34;crypto&#34;); const a = &#34;hello world&#34;; const r = crypto.createHash(&#39;sha256&#39;).update(a).digest(&#39;hex&#39;); 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(&#34;&#34;)).</p></pre>mdwhatcott: <pre><pre><code>package main import &#34;fmt&#34; import &#34;crypto/sha256&#34; import &#34;encoding/hex&#34; func main() { s := &#34;hello world&#34; h := sha256.New() h.Write([]byte(s)) s = hex.EncodeToString(h.Sum(nil)) fmt.Printf(&#34;%s\n&#34;, s) // b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9 } </code></pre></pre>dadleyy: <pre><p>Awesome, thank you!</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

306 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传