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 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)