Go bcrypt Hash Code Example (Online Runner)
Go bcrypt examples with cost control and password verification to match the bcrypt tool.
Online calculator: use the site bcrypt text tool.
Note: This snippet requires locally installed dependencies and will not run in the online runner. Run it locally with:
go mod init bcrypt-demo && go get golang.org/x/crypto/bcrypt && go run bcrypt_basic.go
Calculation method
Use golang.org/x/crypto/bcrypt to generate and verify bcrypt hashes with a configurable cost.
Implementation notes
- Package:
golang.org/x/crypto/bcrypt. - Implementation:
GenerateFromPasswordreturns the full bcrypt hash string (including salt and cost). - Notes: use a cost that balances security and performance; higher costs are slower.
Text hashing example
go
package main
import (
"fmt"
"golang.org/x/crypto/bcrypt"
)
func main() {
hash, err := bcrypt.GenerateFromPassword([]byte("password"), 10)
if err != nil {
panic(err)
}
fmt.Println(string(hash))
}Complete script (implementation + tests)
go
package main
import (
"fmt"
"golang.org/x/crypto/bcrypt"
)
func main() {
password := "correct horse battery staple"
cost := 12
hash, err := bcrypt.GenerateFromPassword([]byte(password), cost)
if err != nil {
panic(err)
}
fmt.Println("bcrypt hash=", string(hash))
if err := bcrypt.CompareHashAndPassword(hash, []byte(password)); err != nil {
panic("password verification failed")
}
fmt.Println("bcrypt verification passed")
}