-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexample_test.go
More file actions
113 lines (94 loc) · 2.41 KB
/
Copy pathexample_test.go
File metadata and controls
113 lines (94 loc) · 2.41 KB
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
105
106
107
108
109
110
111
112
113
package pwdhash_test
import (
"fmt"
"strings"
"github.com/allisson/go-pwdhash"
)
func ExampleNew() {
hasher, err := pwdhash.New()
if err != nil {
panic(err)
}
fmt.Printf("Default hasher created: %T\n", hasher)
// Output: Default hasher created: *pwdhash.PasswordHasher
}
func ExamplePasswordHasher_Hash() {
hasher, err := pwdhash.New(pwdhash.WithPolicy(pwdhash.PolicyInteractive))
if err != nil {
panic(err)
}
// Hash a password
encoded, err := hasher.Hash([]byte("s3cret"))
if err != nil {
panic(err)
}
// PHC hashes for Argon2id start with $argon2id$
fmt.Println(strings.HasPrefix(encoded, "$argon2id$"))
// Output: true
}
func ExamplePasswordHasher_Verify() {
hasher, err := pwdhash.New(pwdhash.WithPolicy(pwdhash.PolicyInteractive))
if err != nil {
panic(err)
}
password := []byte("s3cret")
// Generate a hash to verify
encoded, err := hasher.Hash(password)
if err != nil {
panic(err)
}
// Verify the correct password
ok, err := hasher.Verify([]byte("s3cret"), encoded)
if err != nil {
panic(err)
}
fmt.Println("Correct password:", ok)
// Verify an incorrect password
ok, err = hasher.Verify([]byte("wrong_password"), encoded)
if err != nil {
panic(err)
}
fmt.Println("Incorrect password:", ok)
// Output:
// Correct password: true
// Incorrect password: false
}
func ExamplePasswordHasher_NeedsRehash() {
// 1. Simulate an old hash created with the Interactive policy
oldHasher, err := pwdhash.New(pwdhash.WithPolicy(pwdhash.PolicyInteractive))
if err != nil {
panic(err)
}
encoded, err := oldHasher.Hash([]byte("s3cret"))
if err != nil {
panic(err)
}
// 2. Initialize a new hasher with a stronger Moderate policy
newHasher, err := pwdhash.New(pwdhash.WithPolicy(pwdhash.PolicyModerate))
if err != nil {
panic(err)
}
// 3. Check if the old hash needs to be upgraded using the new hasher
needsRehash, err := newHasher.NeedsRehash(encoded)
if err != nil {
panic(err)
}
fmt.Println("Needs rehash with stronger policy:", needsRehash)
// Output: Needs rehash with stronger policy: true
}
func ExampleWithPolicy() {
// Instantiate a hasher with a specific policy
hasher, err := pwdhash.New(
pwdhash.WithPolicy(pwdhash.PolicyModerate),
)
if err != nil {
panic(err)
}
// Use standard operations
encoded, err := hasher.Hash([]byte("my_secure_password"))
if err != nil {
panic(err)
}
fmt.Println(strings.HasPrefix(encoded, "$argon2id$"))
// Output: true
}