Skip to content

Commit

Permalink
raise bcrypt cost factor lower bound
Browse files Browse the repository at this point in the history
Users of this library can easily create the following:

hasher := fosite.BCrypt{}
hasher.Hash(..)

This is a problem because WorkFactor will default to 0 and x/crypto/bcrypt will default that to 4 (See https://godoc.org/golang.org/x/crypto/bcrypt).

Instead this should be some higher cost factor. Callers who need a lower WorkFactor can still lower the cost, if needed.

Signed-off-by: Adam Shannon <[email protected]>
  • Loading branch information
adamdecaf committed Oct 25, 2018
1 parent 211b43b commit 33fcf9c
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
2 changes: 1 addition & 1 deletion compose/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ func (c *Config) GetAccessTokenLifespan() time.Duration {
// GetAccessTokenLifespan returns how long a refresh token should be valid. Defaults to one hour.
func (c *Config) GetHashCost() int {
if c.HashCost == 0 {
return 12
return fosite.DefaultBCryptWorkFactor
}
return c.HashCost
}
Expand Down
5 changes: 5 additions & 0 deletions hash_bcrypt.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,17 @@ import (
"golang.org/x/crypto/bcrypt"
)

const DefaultBCryptWorkFactor = 12

// BCrypt implements the Hasher interface by using BCrypt.
type BCrypt struct {
WorkFactor int
}

func (b *BCrypt) Hash(ctx context.Context, data []byte) ([]byte, error) {
if b.WorkFactor == 0 {
b.WorkFactor = DefaultBCryptWorkFactor
}
s, err := bcrypt.GenerateFromPassword(data, b.WorkFactor)
if err != nil {
return nil, errors.WithStack(err)
Expand Down
15 changes: 15 additions & 0 deletions hash_bcrypt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import (
"testing"

"github.com/stretchr/testify/assert"
"golang.org/x/crypto/bcrypt"
)

func TestCompare(t *testing.T) {
Expand Down Expand Up @@ -110,3 +111,17 @@ func TestHash(t *testing.T) {
})
}
}

func TestDefaultWorkFactor(t *testing.T) {
b := &BCrypt{}
data := []byte("secrets")
hash, err := b.Hash(context.TODO(), data)
if err != nil {
t.Fatal(err)
}

cost, err := bcrypt.Cost(hash)
if cost != 12 {
t.Errorf("got cost factor %d", cost)
}
}

0 comments on commit 33fcf9c

Please sign in to comment.