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.
You're misusing the
Sum
method. The docs for thehash.Hash
interface clearly say that(Emphasis added.)
You need to either write the data to the hash and use
h.Sum
like thisor just use
sha256.Sum256
Playground: http://play.golang.org/p/oFBePRQzhN.