Skip to content

Go Cryptographic Hashing

Cryptographic hashes are one-way functions that turn data into a fixed-length string of characters. Go's crypto package provides algorithms like SHA-256 and SHA-512.

1. SHA-256 Hashing

SHA-256 is the standard for most applications today (including blockchain and file verification).

package main

import (
    "crypto/sha256"
    "fmt"
)

func main() {
    s := "sha256 this string"

    // 1. Create a new hasher
    h := sha256.New()

    // 2. Write data to it
    h.Write([]byte(s))

    // 3. Get the final hash (Sum)
    bs := h.Sum(nil)

    // Output is usually shown in hex
    fmt.Printf("%x\n", bs)
}

2. Quick Hashing

For small pieces of data, you can use the Sum256 helper function directly.

1
2
3
data := []byte("hello")
hash := sha256.Sum256(data)
fmt.Printf("%x\n", hash)

3. Password Hashing (Warning!)

Never use SHA-256 or SHA-512 for passwords. They are too fast, making them easy to brute-force. Use slower, specialized algorithms like bcrypt or scrypt.

// Example using bcrypt (requires golang.org/x/crypto/bcrypt)
// hash, _ := bcrypt.GenerateFromPassword([]byte("pass"), bcrypt.DefaultCost)

Why use Cryptographic Hashing?

  1. Integrity: Check if a file was corrupted or tampered with.
  2. Uniqueness: Create a "fingerprint" for a piece of data.
  3. Security: Storing "signatures" of sensitive data without storing the data itself.

Important Notes

  • SHA-1 and MD5: These are considered "broken" and insecure. Don't use them for security purposes.
  • Salting: When hashing for security, always add a unique "salt" to the input to prevent rainbow table attacks.