forked from ory/fosite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hash_bcrypt_test.go
104 lines (91 loc) · 2.5 KB
/
hash_bcrypt_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
// Copyright © 2024 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package fosite
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"golang.org/x/crypto/bcrypt"
)
func TestCompare(t *testing.T) {
workfactor := 10
hasher := &BCrypt{Config: &Config{HashCost: workfactor}}
expectedPassword := "hello world"
expectedPasswordHash, err := hasher.Hash(context.TODO(), []byte(expectedPassword))
assert.NoError(t, err)
assert.NotNil(t, expectedPasswordHash)
testCases := []struct {
testDescription string
providedPassword string
shouldError bool
}{
{
testDescription: "should not return an error if hash of provided password matches hash of expected password",
providedPassword: expectedPassword,
shouldError: false,
},
{
testDescription: "should return an error if hash of provided password does not match hash of expected password",
providedPassword: "some invalid password",
shouldError: true,
},
}
for _, test := range testCases {
t.Run(test.testDescription, func(t *testing.T) {
hash, err := hasher.Hash(context.TODO(), []byte(test.providedPassword))
assert.NoError(t, err)
assert.NotNil(t, hash)
err = hasher.Compare(context.TODO(), expectedPasswordHash, []byte(test.providedPassword))
if test.shouldError {
assert.Error(t, err)
} else {
assert.NoError(t, err)
}
})
}
}
func TestHash(t *testing.T) {
validWorkFactor := 10
invalidWorkFactor := 1000 // this is an invalid work factor that will cause the call to Hash to fail!
password := []byte("bar")
testCases := []struct {
testDescription string
workFactor int
shouldError bool
}{
{
testDescription: "should succeed if work factor is valid",
workFactor: validWorkFactor,
shouldError: false,
},
{
testDescription: "should fail with error if work factor is invalid",
workFactor: invalidWorkFactor,
shouldError: true,
},
}
for _, test := range testCases {
t.Run(test.testDescription, func(t *testing.T) {
hasher := &BCrypt{Config: &Config{HashCost: test.workFactor}}
_, err := hasher.Hash(context.TODO(), password)
if test.shouldError {
assert.Error(t, err)
} else {
assert.NoError(t, err)
}
})
}
}
func TestDefaultWorkFactor(t *testing.T) {
b := &BCrypt{Config: &Config{}}
data := []byte("secrets")
hash, err := b.Hash(context.TODO(), data)
if err != nil {
t.Fatal(err)
}
cost, err := bcrypt.Cost(hash)
assert.NoError(t, err)
if cost != 12 {
t.Errorf("got cost factor %d", cost)
}
}