Golang Base64编码的用户密码的SHA256摘要

huangapple go评论85阅读模式
英文:

Golang Base64 encoded SHA256 digest of the user’s password

问题

我正在尝试完成Top Code Go Learning Challenges,以此作为学习Go语言的工具。我目前正在解决他们的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加密的标准库方法。

英文:

I am attempting to complete the Top Code Go Learning Challenges as a vehicle to learn go. I'm currently working on their Simple API Web Server problem. Part of that problem calls for you to encrypt a password string as such "‘{SHA256}’ + Base64 encoded SHA256 digest of the user’s password"

I've used the following code to do this, but the results don't match the test case provided.

import (
    "encoding/base64"
    "crypto/sha256"
)

func encrtyptPasswords(password string) string {
    h := sha256.New()
    return "{SHA256}" + 
       string(base64.StdEncoding.EncodeToString(h.Sum([]byte(password))))
}

For an input of abcd1234 it should encrypt to: {SHA256}6c7nGrky_ehjM40Ivk3p3-OeoEm9r7NCzmWexUULaa4=

But I get {SHA256}YWJjZDEyMzTjsMRCmPwcFJr79MiZb7kkJ65B5GSbk0yklZkbeFK4VQ== instead. I suspect I'm using the encryption libraries wrong, but I'm not sure what I should be using as this seems to be the standard library method of encryption to SHA256.

答案1

得分: 12

你误用了Sum方法。hash.Hash接口的文档明确说明了:

>Sum方法将当前哈希追加到b并返回结果切片。

(强调添加部分)

你需要将数据写入哈希并像这样使用h.Sum

h.Write([]byte(password))
b := h.Sum(nil)

或者直接使用sha256.Sum256

h := sha256.Sum256([]byte(password))

Playground: http://play.golang.org/p/oFBePRQzhN.

英文:

You're misusing the Sum method. The docs for the hash.Hash interface clearly say that

>Sum appends the current hash to b and returns the resulting slice.

(Emphasis added.)

You need to either write the data to the hash and use h.Sum like this

h.Write([]byte(password))
b := h.Sum(nil)

or just use sha256.Sum256

h := sha256.Sum256([]byte(password))

Playground: http://play.golang.org/p/oFBePRQzhN.

huangapple
  • 本文由 发表于 2015年6月21日 00:19:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/30956244.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定