how to salt a password in go

To salt a password in Go, you can use the bcrypt package which is a popular choice for password hashing.

Here's an example code snippet to salt a password using bcrypt:

main.go
package main

import (
    "fmt"
    "golang.org/x/crypto/bcrypt"
)

func main() {
    password := "my_password"
    saltRounds := 10 // define the number of times to apply the hashing algorithm
    
    saltedPassword, err := bcrypt.GenerateFromPassword([]byte(password), saltRounds)
    if err != nil {
        fmt.Println(err)
    }
    
    fmt.Println(string(saltedPassword))
}
383 chars
19 lines

In this example, we define the password we want to salt, and specify the number of saltRounds to apply (the default value is usually around 10). We then use the bcrypt.GenerateFromPassword() function to generate a salted password, which returns a byte slice of the resulting hash.

Note that the generated saltedPassword includes both the salt and the hashed password, separated by a separator character.

gistlibby LogSnag