github.com/goravel/framework@v1.13.9/hash/bcrypt.go (about) 1 package hash 2 3 import ( 4 "golang.org/x/crypto/bcrypt" 5 6 "github.com/goravel/framework/contracts/config" 7 ) 8 9 type Bcrypt struct { 10 rounds int 11 } 12 13 // NewBcrypt returns a new Bcrypt hasher. 14 func NewBcrypt(config config.Config) *Bcrypt { 15 return &Bcrypt{ 16 rounds: config.GetInt("hashing.bcrypt.rounds", 10), 17 } 18 } 19 20 // Make returns the hashed value of the given string. 21 func (b *Bcrypt) Make(value string) (string, error) { 22 hash, err := bcrypt.GenerateFromPassword([]byte(value), b.rounds) 23 if err != nil { 24 return "", err 25 } 26 27 return string(hash), nil 28 } 29 30 // Check checks if the given string matches the given hash. 31 func (b *Bcrypt) Check(value, hash string) bool { 32 err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(value)) 33 return err == nil 34 } 35 36 // NeedsRehash checks if the given hash needs to be rehashed. 37 func (b *Bcrypt) NeedsRehash(hash string) bool { 38 hashCost, err := bcrypt.Cost([]byte(hash)) 39 40 if err != nil { 41 return true 42 } 43 return hashCost != b.rounds 44 }