Go SHAKE Hash Code Example (Online Runner)
Go SHAKE128/SHAKE256 examples with variable digest length and runnable snippets.
Online calculator: use the site SHAKE text tool.
Note: This snippet requires locally installed dependencies and will not run in the online runner. Run it locally with:
go mod init shake-demo && go get golang.org/x/crypto/sha3 && go run shake_basic.go
Calculation method
SHAKE is an extendable-output function (XOF). You choose the output length in bytes.
Implementation notes
- Package:
golang.org/x/crypto/sha3. - Implementation: read
outputLenbytes from the SHAKE reader and hex-encode them. - Notes: SHAKE is unkeyed; use KMAC or HMAC if you need a key.
Text hashing example
go
package main
import (
"encoding/hex"
"fmt"
"golang.org/x/crypto/sha3"
)
func shake128Hex(text string, outLen int) string {
out := make([]byte, outLen)
h := sha3.NewShake128()
h.Write([]byte(text))
h.Read(out)
return hex.EncodeToString(out)
}
func main() {
fmt.Println(shake128Hex("hello", 32))
}File hashing example
go
package main
import (
"encoding/hex"
"fmt"
"io"
"os"
"golang.org/x/crypto/sha3"
)
func shake256File(path string, outLen int) (string, error) {
file, err := os.Open(path)
if err != nil {
return "", err
}
defer file.Close()
h := sha3.NewShake256()
if _, err := io.Copy(h, file); err != nil {
return "", err
}
out := make([]byte, outLen)
h.Read(out)
return hex.EncodeToString(out), nil
}
func main() {
file, err := os.CreateTemp("", "shake-example-*.bin")
if err != nil {
panic(err)
}
defer os.Remove(file.Name())
file.WriteString("example payload\n")
file.Close()
value, err := shake256File(file.Name(), 64)
if err != nil {
panic(err)
}
fmt.Println(value)
}Complete script (implementation + tests)
go
package main
import (
"encoding/hex"
"errors"
"fmt"
"golang.org/x/crypto/sha3"
)
type Variant string
const (
SHAKE128 Variant = "shake128"
SHAKE256 Variant = "shake256"
)
func shakeHex(data []byte, variant Variant, outputLen int) (string, error) {
if outputLen <= 0 {
return "", errors.New("output length must be positive")
}
out := make([]byte, outputLen)
switch variant {
case SHAKE128:
h := sha3.NewShake128()
h.Write(data)
h.Read(out)
case SHAKE256:
h := sha3.NewShake256()
h.Write(data)
h.Read(out)
default:
return "", errors.New("unsupported SHAKE variant")
}
return hex.EncodeToString(out), nil
}
func main() {
value, err := shakeHex([]byte("hello"), SHAKE128, 32)
if err != nil {
panic(err)
}
fmt.Println("shake128(hello, 32 bytes)=", value)
value256, err := shakeHex([]byte("hello"), SHAKE256, 64)
if err != nil {
panic(err)
}
fmt.Println("shake256(hello, 64 bytes)=", value256)
}