create a password in go

To create a secure password in Go, you should not store the raw password in the database because if the database is compromised, the attacker can easily read all the passwords in plain text. Instead, you should store a salted hash of the password.

Here's an example code to hash a password using Go's crypto package:

main.go
import (
   "crypto/rand"
   "crypto/sha256"
   "encoding/base64"
   "fmt"
)

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

   // Append the password to the salt
   saltedPassword := []byte(password + string(salt))

   // Hash the salted password using SHA256
   hash := sha256.Sum256(saltedPassword)

   // Append the salt to the hash
   hashWithSalt := append(hash[:], salt...)

   // Encode the hash with salt to base64 string
   hashedPassword := base64.URLEncoding.EncodeToString(hashWithSalt)

   return hashedPassword, nil
}
671 chars
30 lines

To verify a password, you need to retrieve the salt from the database for the user and generate the hash of the password with the retrieved salt, and compare the hash with the stored hashed password.

main.go
func verifyPassword(password, hashedPassword string) (bool, error) {
   // Decode the hashed password string
   hashedBytes, err := base64.URLEncoding.DecodeString(hashedPassword)
   if err != nil {
      return false, err
   }

   // Retrieve the salt from the stored hash
   salt := hashedBytes[len(hashedBytes)-16:]

   // Generate the hash of the provided password with the retrieved salt
   hashedPasswordToCheck, err := hashPassword(password+string(salt))
   if err != nil {
      return false, err
   }

   // Compare the two hashes
   return hashedPassword == hashedPasswordToCheck, nil
}
597 chars
20 lines

Keep in mind that this is just an example, and there are more secure and efficient ways to store passwords, such as using a dedicated password hashing library like bcrypt or scrypt.

gistlibby LogSnag