首页 > 解决方案 > Go Sha256Sum Difference with Bash sha256sum

问题描述

My go code is producing different sha256sum values than bash commandline. I've read through various questions and answers and they all point to what I've already done, as this community asks me to do before posting

Here's my sha256sum code on go

sha256Key:=verifyEmail+":"+md5password+":"+dateStr
hasherSha256 := sha1.New()
hasherSha256.Write([]byte(sha256Key))
sha256Val:=hex.EncodeToString(hasherSha256.Sum(nil))

And here's my bash script code:

key=$( echo -n "$verifyEmail:$md5PWD:$pwTime" | sha256sum)
echo $key

Ive already validated that the keys are the same. One note, my dateStr variable inside go comes from date formatting:

now := time.Now().Unix()
rem := now % 3600
date := now-rem         
dateStr:=strconv.FormatInt(date,10)

Usually I get downvotes so I tried making this question as clear and concise as possible.

Please let me know if im missing anything.

Thanks

标签: bashgosha256

解决方案


你说你想计算 SHA-256 校验和,但你做了:

hasherSha256 := sha1.New()

那将是 SHA-1 哈希,而不是 SHA-256。而是这样做:

hasherSha256 := sha256.New()

另请注意,要计算某些数据的“一次性”摘要(准备在字节切片中),您可以使用如下sha256.Sum256()函数:

digest := sha256.Sum256([]byte(sha256Key))

请注意,这里digest将是一个数组(不是slice,在 Go 中它们完全不同),一个类型为 的数组[32]byte。要获得“它的”切片(类型为[]byte),请按如下方式切片:

digestSlice := digest[:]

推荐阅读