How to securely hash and compare passwords for user authentication in Go?

To securely hash and compare passwords for user authentication in Go, you can follow the steps below:

  1. Use a strong cryptographic hash function: Go's crypto package provides various hash functions like sha256, sha512, etc. Choose an appropriate hash function based on your security requirements.

  2. Generate a random salt: A salt is a random value that adds complexity to the password hashing process. It ensures that even if two users have the same password, their hashed passwords will be different. Use Go's crypto/rand package to generate a random salt.

  3. Hash the password with the salt: Combine the password and salt, then hash the result using the selected hash function. You can use the crypto package's functions like hash.Write to write the combined value, and then retrieve the hashed result.

import ( "crypto/rand" "crypto/sha256" "encoding/base64" ) func hashPassword(password string, salt []byte) string { hash := sha256.New() hash.Write([]byte(password)) hash.Write(salt) hashedPwd := hash.Sum(nil) return base64.URLEncoding.EncodeToString(hashedPwd) }
  1. Store the hashed password and salt: Save the hashed password and salt in your user database. Never store the actual password.

  2. Compare passwords during authentication: To verify a user's password during the login process, retrieve the hashed password and salt from the user database. Then, hash the provided password with the salt and compare it with the stored hashed password.

func comparePasswords(storedPwd, salt, providedPwd string) bool { hashedPwd := hashPassword(providedPwd, []byte(salt)) return storedPwd == hashedPwd }

Note: The base64.URLEncoding.EncodeToString method is used to encode the binary hashed password into a string representation, suitable for storage and comparison.

Remember to keep the salt value secret and unique for each user. Additionally, consider using more advanced techniques like key stretching with an algorithm like bcrypt or scrypt for better security.