How to Get a SHA256 Hash from a String in Go

Created
Modified

Go implements several hash functions in various crypto/* packages.

Using Sum256 Function

The sha256.Sum256() function returns the SHA256 checksum of the data.

The following example should cover whatever you are trying to do:

package main

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

func main() {
  s := "Hello"

  sum := sha256.Sum256([]byte(s))

  fmt.Printf("%x\n", sum)
  fmt.Println(hex.EncodeToString(sum[:]))
}
185f8db32271fe25f561a6fc938b2e264306ec304eda518007d1764826381969
185f8db32271fe25f561a6fc938b2e264306ec304eda518007d1764826381969

Using New Function

New returns a new hash.Hash computing the SHA256 checksum.

For example,

package main

import (
  "crypto/sha256"
  "fmt"
)

func main() {
  h := sha256.New()
  h.Write([]byte("Hello"))
  h.Write([]byte("World"))

  fmt.Printf("%x\n", h.Sum(nil))
}
872e4e50ce9990d8b041330c47c9ddd11bec6b503ae9386a99da8584e9bb12c4

Generate SHA256 checksum of a file. See the following example:

package main

import (
  "crypto/sha256"
  "fmt"
  "io"
  "os"
)

func main() {
  f, err := os.Open("ins.txt")
  if err != nil {
    // log.Fatal(err)
  }
  defer f.Close()

  h := sha256.New()
  if _, err := io.Copy(h, f); err != nil {
    // log.Fatal(err)
  }

  fmt.Printf("%x\n", h.Sum(nil))
}
39866a50dfb27f5b96f075b3cbf9179096c87495983782427a0422c611a30e1e

Related Tags