用户密码的 Golang Base64 编码 SHA256 摘要
Golang Base64 encoded SHA256 digest of the user’s password
我正在尝试完成 Top Code Go Learning Challenges 作为学习围棋的工具。我目前正在研究他们的 Simple API Web Server problem。该问题的一部分要求您加密密码字符串,例如“'{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))))
}
对于 abcd1234 的输入,它应该加密为:{SHA256}6c7nGrky_ehjM40Ivk3p3-OeoEm9r7NCzmWexUULaa4=
但我得到的是 {SHA256}YWJjZDEyMzTjsMRCmPwcFJr79MiZb7kkJ65B5GSbk0yklZkbeFK4VQ==。我怀疑我使用的加密库有误,但我不确定我应该使用什么,因为这似乎是 SHA256 加密的标准库方法。
您误用了 Sum
方法。 hash.Hash
接口的 docs 明确表示
Sum appends the current hash to b and returns the resulting slice.
(强调已添加。)
您需要将数据写入哈希并像这样使用 h.Sum
h.Write([]byte(password))
b := h.Sum(nil)
或者只使用 sha256.Sum256
h := sha256.Sum256([]byte(password))
我正在尝试完成 Top Code Go Learning Challenges 作为学习围棋的工具。我目前正在研究他们的 Simple API Web Server problem。该问题的一部分要求您加密密码字符串,例如“'{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))))
}
对于 abcd1234 的输入,它应该加密为:{SHA256}6c7nGrky_ehjM40Ivk3p3-OeoEm9r7NCzmWexUULaa4=
但我得到的是 {SHA256}YWJjZDEyMzTjsMRCmPwcFJr79MiZb7kkJ65B5GSbk0yklZkbeFK4VQ==。我怀疑我使用的加密库有误,但我不确定我应该使用什么,因为这似乎是 SHA256 加密的标准库方法。
您误用了 Sum
方法。 hash.Hash
接口的 docs 明确表示
Sum appends the current hash to b and returns the resulting slice.
(强调已添加。)
您需要将数据写入哈希并像这样使用 h.Sum
h.Write([]byte(password))
b := h.Sum(nil)
或者只使用 sha256.Sum256
h := sha256.Sum256([]byte(password))