Golang Base64 encoded SHA256 digest of the user’s password

11,112

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.

Share:
11,112
MrWizard54
Author by

MrWizard54

Product Manager at Splunk! working on App Certification. I'm also an occasional programmer and tinkerer. Trying to learn Golang and Python ATM.

Updated on June 04, 2022

Comments

  • MrWizard54
    MrWizard54 almost 2 years

    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.

  • alecbz
    alecbz almost 9 years
    FWIW b := h.Sum(nil) would also work for your first example.
  • Louie Miranda
    Louie Miranda over 4 years
    This is great. Just have one question, are the result already on digest?