【发布时间】:2020-05-08 15:50:45
【问题描述】:
我正在从多个字符串计算 sha256。我以特定方式将它们转换为字节片并将它们全部附加在一起,然后使用内置库计算散列。但是,取决于我是否在计算 sha256 之前打印出切片,我会奇怪地得到不同的结果。在操场上测试时,我无法重现它。
可以在https://play.golang.org/p/z8XKx-p9huG 上查看和运行经过测试的代码,在这两种情况下它实际上给出了相同的结果。
func getHash(input1 string, input2hex string, input3hex string, input4 string) (string, error) {
input1bytes := []byte(input1)
firstHalfinput1Bytes := input1bytes[:8]
secondHalfinput1Bytes := input1bytes[8:16]
input4Bytes := []byte(input4)
input3Bytes, err := hex.DecodeString(input3hex)
if err != nil {
fmt.Println("err " + err.Error())
}
input2Bytes, err := hex.DecodeString(input2hex)
if err != nil {
fmt.Println("err " + err.Error())
}
fullHashInputBytes := append(firstHalfinput1Bytes, input2Bytes...)
// THIS IS THE OPTIONAL PRINT WHICH CHANGES OUTPUT LOCALLY:
fmt.Println("fullHashInputBytes", fullHashInputBytes)
fullHashInputBytes = append(fullHashInputBytes, secondHalfinput1Bytes...)
fullHashInputBytes = append(fullHashInputBytes, input3Bytes...)
fullHashInputBytes = append(fullHashInputBytes, input4Bytes...)
sha256 := sha256.Sum256(fullHashInputBytes)
for i := 0; i < 8; i++ {
sha256[i+16] ^= sha256[i+24]
}
hash := hex.EncodeToString(sha256[:24])
fmt.Println("hash", hash)
return hash, nil
}
操场上的日志是
Hello, playground
fullHashInputBytes [84 72 73 83 73 83 78 79 30 0 22 121 57 203 102 148 210 196 34 172 210 8 160 7]
hash 0161d9de8dd815ca9f4e1c7bb8684562542cc24b1026321c
hash 0161d9de8dd815ca9f4e1c7bb8684562542cc24b1026321c
但如果我在本地运行完全相同的代码(只需将其复制粘贴到 main.go 并执行go run main.go 或go build . 和./test)我得到
Hello, playground
fullHashInputBytes [84 72 73 83 73 83 78 79 30 0 22 121 57 203 102 148 210 196 34 172 210 8 160 7]
hash 0161d9de8dd815ca9f4e1c7bb8684562542cc24b1026321c
hash d2de4ffb4e8790b8fd1ceeba726436fd97875a5740c27b47
我使用的是 go 版本 1.13.4,但与 1.10.4 有同样的问题。我在本地机器上和部署到我们的服务器时也遇到了同样的问题。
【问题讨论】:
-
您的问题有点“忙” - 所以让我问一下,在将数据中继到哈希器时是否使用了任何缓冲(例如
bytes.Buffer)?如果是这样,请确保刷新最终写入以确保您正在散列整个有效负载。 -
代码和你看到的完全一样,没有缓冲区。我用硬编码的字符串测试它(见操场链接)。但也许我可以删除几乎所有的问题,只需参考游乐场链接以使其更易于消化:)
-
删除了大部分文字并转而引用链接,希望它不那么忙!
-
问题应该在问题正文中包含相关代码,而不仅仅是在外部链接中。