-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhash.go
52 lines (45 loc) · 1.11 KB
/
hash.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
package utils
import (
"crypto/sha256"
"encoding/json"
"fmt"
"golang.org/x/crypto/bcrypt"
)
// HashPassword returns hashed version of password
func HashPassword(password string, cost int) (string, error) {
// ensure cost is within allowed range
{
const MIN_COST = 4
const MAX_COST = 31
if cost < MIN_COST {
cost = MIN_COST
}
if cost > MAX_COST {
cost = MAX_COST
}
}
bytes, err := bcrypt.GenerateFromPassword([]byte(password), cost)
return string(bytes), err
}
// CheckPasswordHash compares hashes between password string
func CheckPasswordHash(password, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}
// Mapfields - returns subset map
func Mapfields[T map[string]any](d *T, fields *[]string) *T {
retme := make(T)
for _, field := range *fields {
retme[field] = (*d)[field]
}
return &retme
}
// Hashmap hashes a map using sha256 and returns the hash as string
func Hashmap[T map[string]any](d *T) (string, error) {
b, err := json.Marshal(d)
if err != nil {
return "", err
}
h := sha256.Sum256(b)
return fmt.Sprintf("%x", h), nil
}