How to Hash Passwords in Go with argon2

Web
Hash passwords in Go using the golang.org/x/crypto/argon2 package with Argon2id for secure storage.

Use the golang.org/x/crypto/argon2 package to hash passwords securely with the Argon2id algorithm.

package main

import (
	"crypto/rand"
	"encoding/hex"
	"fmt"

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

func hashPassword(password []byte) (string, error) {
	salt := make([]byte, 16)
	if _, err := rand.Read(salt); err != nil {
		return "", err
	}

	hash := argon2.IDKey(password, salt, 1, 64*1024, 4, 32)
	return hex.EncodeToString(hash), nil
}

func main() {
	hash, err := hashPassword([]byte("my_secure_password"))
	if err != nil {
		panic(err)
	}
	fmt.Println("Hash:", hash)
}

Install the dependency first:

go get golang.org/x/crypto/argon2