2015-06-20 16:19
浏览 152

用户密码的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 (

func encrtyptPasswords(password string) string {
    h := sha256.New()
    return "{SHA256}" + 

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
    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

    b := h.Sum(nil)

    or just use sha256.Sum256

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


    点赞 评论