MrW*_*d54 2 hash cryptography sha256 go
我正在尝试完成Top Code Go学习挑战作为学习去的工具.我目前正在研究他们的Simple API Web Server问题.部分问题要求您加密密码字符串,如"'{SHA256}'+ Base64编码SHA256用户密码摘要"
我使用以下代码执行此操作,但结果与提供的测试用例不匹配.
import (
"encoding/base64"
"crypto/sha256"
)
func encrtyptPasswords(password string) string {
h := sha256.New()
return "{SHA256}" +
string(base64.StdEncoding.EncodeToString(h.Sum([]byte(password))))
}
Run Code Online (Sandbox Code Playgroud)
对于abcd1234的输入,它应加密到:{SHA256} 6c7nGrky_ehjM40Ivk3p3-OeoEm9r7NCzmWexUULaa4 =
但我得到{SHA256} YWJjZDEyMzTjsMRCmPwcFJr79MiZb7kkJ65B5GSbk0yklZkbeFK4VQ ==.我怀疑我使用加密库是错误的,但我不确定我应该使用什么,因为这似乎是SHA256的标准库加密方法.
你在滥用这种Sum方法.该文档的hash.Hash界面清楚地说,
Sum 将当前哈希附加到b并返回结果切片.
(重点补充.)
您需要将数据写入散列并使用h.Sum这样的方法
h.Write([]byte(password))
b := h.Sum(nil)
Run Code Online (Sandbox Code Playgroud)
或者只是使用 sha256.Sum256
h := sha256.Sum256([]byte(password))
Run Code Online (Sandbox Code Playgroud)
游乐场:http://play.golang.org/p/oFBePRQzhN.