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

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 网络科学导论,网络控制
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)