duanchuaiwan0063 2014-06-27 22:27
浏览 696
已采纳

Go SHA-256哈希与Java SHA-256哈希不同

If I generate the SHA-256 hash in the language "GO", I get a different byte-Array compared to the Java equivalent.

This is the GO version:

fmt.Println(getSha256([]byte("5nonce=5")))

The resulting array looks like:

41 79 186 235 199 123 95 226 16 59 51 161 112 245 192 50 21 66 180 250 179 109 153 18 233 148 16 237 156 69 163 150]

This one should do the same in Java code:

MessageDigest md = MessageDigest.getInstance("SHA-256");

md.update("5nonce=5".getBytes()); 
byte[] digest = md.digest();

But results in this byte array

[41, 79, -70, -21, -57, 123, 95, -30, 16, 59, 51, -95, 112, -11, -64, 50, 21, 66, -76, -6, -77, 109, -103, 18, -23, -108, 16, -19, -100, 69, -93, -106]

Why are they different? How do I need to change the java version to work exactly like the Go version?

  • 写回答

2条回答 默认 最新

  • dpw43061 2014-06-27 22:28
    关注

    Why are they different?

    They're not, really. They're the same bits. It's just that Java doesn't have unsigned bytes - so any byte with the top bit set is negative. In every case like that, you'll see that Java result = Go result - 256.

    If you convert both byte arrays to hex or base64, you'll see same results.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题