-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpassword.go
48 lines (42 loc) · 1.14 KB
/
password.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
package helper
import (
"crypto/rand"
"golang.org/x/crypto/bcrypt"
"math/big"
)
func HashPassword(password string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
return string(bytes), err
}
func CheckPasswordHash(hashVal, userPw string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hashVal), []byte(userPw))
if err != nil {
return false
} else {
return true
}
}
func GenerateRandomString(length int) string {
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
b := make([]rune, length)
for i := range b {
b[i] = randomRune(letters)
}
return string(b)
}
func GenerateRandomPassword(length int) string {
// generate a random password with string of letters, digits, and special characters
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()")
b := make([]rune, length)
for i := range b {
b[i] = randomRune(letters)
}
return string(b)
}
func randomRune(chars []rune) rune {
n, err := rand.Int(rand.Reader, big.NewInt(int64(len(chars))))
if err != nil {
panic(err)
}
return chars[n.Int64()]
}