Generating the SHA hash of a string using golang

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

The package documentation at http://golang.org/pkg/crypto/sha1/ does have an example that demonstrates this. It's stated as an example of the New function, but it's the only example on the page and it has a link right near the top of the page so it is worth looking at. The complete example is,

Code:

h := sha1.New()
io.WriteString(h, "His money is twice tainted: 'taint yours and 'taint mine.")
fmt.Printf("% x", h.Sum(nil))

Output:

59 7f 6a 54 00 10 f9 4c 15 d7 18 06 a9 9a 2c 87 10 e7 47 bd


Go By Example has a page on sha1 hashing.

package main

import (
    "fmt"
    "crypto/sha1"
    "encoding/hex"
)

func main() {

    s := "sha1 this string"
    h := sha1.New()
    h.Write([]byte(s))
    sha1_hash := hex.EncodeToString(h.Sum(nil))

    fmt.Println(s, sha1_hash)
}

You can run this example on play.golang.org

Tags:

Hash

Go