Go SHA3-256 Hash Code Example (Online Runner)

Go SHA3-256 hashing code example with runnable snippets to calculate SHA3-256 for text and files.

Online calculator: use the site SHA3-256 text tool.

Note: This snippet requires locally installed dependencies and will not run in the online runner. Run it locally with: go mod init sha3-demo && go get golang.org/x/crypto/sha3 && go run sha3_256_basic.go

Calculation method

Use golang.org/x/crypto/sha3, hash UTF-8 bytes, and encode the 32-byte digest as hex.

Implementation notes

  • Package: golang.org/x/crypto/sha3.
  • Implementation: file hashing streams bytes to avoid loading large files into memory.
  • Notes: SHA3 is unkeyed; use HMAC or a password KDF when you need a secret.

Text hashing example

go
package main

import (
	"encoding/hex"
	"fmt"

	"golang.org/x/crypto/sha3"
)

func sha3_256Text(text string) string {
	sum := sha3.Sum256([]byte(text))
	return hex.EncodeToString(sum[:])
}

func main() {
	fmt.Println(sha3_256Text("hello world"))
}

File hashing example

go
package main

import (
	"encoding/hex"
	"fmt"
	"io"
	"os"

	"golang.org/x/crypto/sha3"
)

func sha3_256File(path string) (string, error) {
	file, err := os.Open(path)
	if err != nil {
		return "", err
	}
	defer file.Close()

	hash := sha3.New256()
	if _, err := io.Copy(hash, file); err != nil {
		return "", err
	}
	return hex.EncodeToString(hash.Sum(nil)), nil
}

func main() {
	file, err := os.CreateTemp("", "sha3-256-example-*.bin")
	if err != nil {
		panic(err)
	}
	defer os.Remove(file.Name())
	if _, err := file.Write([]byte("example payload\n")); err != nil {
		panic(err)
	}
	if err := file.Close(); err != nil {
		panic(err)
	}

	value, err := sha3_256File(file.Name())
	if err != nil {
		panic(err)
	}
	fmt.Println(value)
}

Complete script (implementation + tests)

go
package main

import (
	"encoding/hex"
	"fmt"
	"io"
	"os"

	"golang.org/x/crypto/sha3"
)

func sha3_256Hex(data []byte) string {
	sum := sha3.Sum256(data)
	return hex.EncodeToString(sum[:])
}

func sha3_256Text(text string) string {
	return sha3_256Hex([]byte(text))
}

func sha3_256File(path string) (string, error) {
	file, err := os.Open(path)
	if err != nil {
		return "", err
	}
	defer file.Close()

	hash := sha3.New256()
	if _, err := io.Copy(hash, file); err != nil {
		return "", err
	}
	return hex.EncodeToString(hash.Sum(nil)), nil
}

func main() {
	if got := sha3_256Text(""); got != "a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a" {
		panic("SHA3-256 test vector mismatch")
	}

	file, err := os.CreateTemp("", "sha3-256-example-*.bin")
	if err != nil {
		panic(err)
	}
	defer os.Remove(file.Name())
	if _, err := file.Write([]byte("example payload\n")); err != nil {
		panic(err)
	}
	if err := file.Close(); err != nil {
		panic(err)
	}

	fileHash, err := sha3_256File(file.Name())
	if err != nil {
		panic(err)
	}
	fmt.Println("sha3-256(file)=", fileHash)
	fmt.Println("SHA3-256 test vector passed.")
}