github.com/gramework/gramework@v1.8.1-0.20231027140105-82555c9057f5/grypto/providers/bcrypt/bcrypt_provider.go (about) 1 package bcrypt 2 3 import ( 4 gobcrypt "golang.org/x/crypto/bcrypt" 5 ) 6 7 const ( 8 DefaultCost = 13 9 ) 10 11 var ( 12 DefaultProvider = New() 13 ) 14 15 // Provider handles algorythm parameters 16 type Provider struct { 17 Cost uint8 18 } 19 20 // New returns new bcrypt provider 21 func New() *Provider { 22 return &Provider{ 23 Cost: DefaultCost, 24 } 25 } 26 27 // Hash returns scrypt hash of plaintext 28 func (p *Provider) Hash(plaintext []byte) []byte { 29 pw, _ := gobcrypt.GenerateFromPassword(plaintext, int(p.Cost)) 30 return pw 31 } 32 33 // HashString returns scrypt hash of plaintext 34 func (p *Provider) HashString(plaintext string) []byte { 35 return p.Hash([]byte(plaintext)) 36 } 37 38 // NeedsRehash checks if provided hash needs rehash 39 func (p *Provider) NeedsRehash(hash []byte) bool { 40 hashCost, err := gobcrypt.Cost(hash) 41 return err != nil || hashCost != int(p.Cost) 42 } 43 44 // Valid checks if provided plaintext is valid for given hash 45 func (p *Provider) Valid(hash, plain []byte) bool { 46 return gobcrypt.CompareHashAndPassword(hash, plain) == nil 47 }