I am calculating a sha256 from multiple strings. I convert them to byte slices in a specific way and append them all together and then compute the hash using the built in library. However, depending on if I print out the slice before calculating the sha256 or not I wierdly get different results. When testing it in playground I cannot reproduce it.
The tested code can been seen and run on https://play.golang.org/p/z8XKx-p9huG where it actually gives the same result in both cases.
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
}
The logs on the playground are
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
but if I run EXACTLY the same code locally (just copy-paste it into a main.go and do go run main.go
or go build .
and ./test
) I get
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
I'm using go version 1.13.4
but had the same issue with 1.10.4
. I also get the same issue on both my local machine and when deployed to our server.