dongsuishou8039 2015-06-20 16:19
浏览 317
已采纳

用户密码的Golang Base64编码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条回答 默认 最新

  • douzhi6365 2015-06-20 16:41
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料