-
Notifications
You must be signed in to change notification settings - Fork 0
/
password_helpers.go
48 lines (37 loc) · 1.06 KB
/
password_helpers.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 account
import (
"fmt"
"log"
"io"
"golang.org/x/crypto/bcrypt"
"crypto/rand"
)
var INTEGER_TABLE = [...]byte{'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'}
//EncodeToString is used to create a 6 digit verification code
func EncodeToString(max int) string {
b := make([]byte, max)
n, err := io.ReadAtLeast(rand.Reader, b, max)
if n != max {
panic(err)
}
for i := 0; i < len(b); i++ {
b[i] = INTEGER_TABLE[int(b[i])%len(INTEGER_TABLE)]
}
return string(b)
}
//HashPassword is used to encrypt the password before storage
func HashPassword(password string) string {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
if err != nil {
log.Panic(err)
}
return string(bytes)
}
//VerifyPassword checks the hashes of 2 passwords are equal
func VerifyPassword(userPassword string, providedPassword string) (bool, string) {
err := bcrypt.CompareHashAndPassword([]byte(providedPassword), []byte(userPassword))
if err != nil {
return false, fmt.Sprintf("login or password is incorrect")
}
return true, ""
}