HiveBrain v1.2.0
Get Started
← Back to all entries
patterngoCritical

Generating the SHA hash of a string using golang

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
generatingshatheusinggolanghashstring

Problem

Can someone show me a working example of how to generate a SHA hash of a string that I have, say myPassword := "beautiful", using Go?

Solution

An example :

import (
    "crypto/sha1"
    "encoding/base64"
)

func (ms *MapServer) storee(bv []byte) {
    hasher := sha1.New()
    hasher.Write(bv)
    sha := base64.URLEncoding.EncodeToString(hasher.Sum(nil))
        ...
}


In this example I make a sha from a byte array. You can get the byte array using

bv := []byte(myPassword)


Of course you don't need to encode it in base64 if you don't have to : you may use the raw byte array returned by the Sum function.

There seems to be some little confusion in comments below. So let's clarify for next users the best practices on conversions to strings:

  • you never store a SHA as a string in a database, but as raw bytes



  • when you want to display a SHA to a user, a common way is Hexadecimal



  • when you want a string representation because it must fit in an URL or in a filename, the usual solution is Base64, which is more compact

Code Snippets

import (
    "crypto/sha1"
    "encoding/base64"
)

func (ms *MapServer) storee(bv []byte) {
    hasher := sha1.New()
    hasher.Write(bv)
    sha := base64.URLEncoding.EncodeToString(hasher.Sum(nil))
        ...
}
bv := []byte(myPassword)

Context

Stack Overflow Q#10701874, score: 116

Revisions (0)

No revisions yet.