Go scrypt Hash Code Example (Online Runner)
Go scrypt examples with parameters, salt encoding, and derived key length matching the scrypt tool.
Online calculator: use the site scrypt text tool.
Note: This snippet requires locally installed dependencies and will not run in the online runner. Run it locally with:
go mod init scrypt-demo && go get golang.org/x/crypto/scrypt && go run scrypt_basic.go
Calculation method
Use golang.org/x/crypto/scrypt to derive a key with configurable N, r, p, salt, and output length.
Implementation notes
- Package:
golang.org/x/crypto/scrypt. - Implementation: the helper decodes salt (hex/base64/text) and returns hex output.
- Notes: N must be a power of two; use parameters appropriate for your environment.
Text hashing example
go
package main
import (
"encoding/hex"
"fmt"
"golang.org/x/crypto/scrypt"
)
func main() {
salt, _ := hex.DecodeString("73616c74")
key, err := scrypt.Key([]byte("password"), salt, 1<<15, 8, 1, 32)
if err != nil {
panic(err)
}
fmt.Println(hex.EncodeToString(key))
}Complete script (implementation + tests)
go
package main
import (
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"golang.org/x/crypto/scrypt"
)
type SaltEncoding string
const (
SaltHex SaltEncoding = "hex"
SaltBase64 SaltEncoding = "base64"
SaltText SaltEncoding = "text"
)
func decodeSalt(value string, encoding SaltEncoding) ([]byte, error) {
if value == "" {
return nil, errors.New("salt is required")
}
switch encoding {
case SaltHex:
return hex.DecodeString(value)
case SaltBase64:
return base64.StdEncoding.DecodeString(value)
case SaltText:
fallthrough
default:
return []byte(value), nil
}
}
func scryptKey(password string, salt string, saltEnc SaltEncoding, N, r, p, keyLen int) (string, error) {
saltBytes, err := decodeSalt(salt, saltEnc)
if err != nil {
return "", err
}
key, err := scrypt.Key([]byte(password), saltBytes, N, r, p, keyLen)
if err != nil {
return "", err
}
return hex.EncodeToString(key), nil
}
func main() {
dk, err := scryptKey("password", "73616c74", SaltHex, 1<<15, 8, 1, 32)
if err != nil {
panic(err)
}
fmt.Println("scrypt=", dk)
}