forked from shaj13/go-guardian
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hasher.go
47 lines (39 loc) · 1.01 KB
/
hasher.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
package internal
import (
"crypto"
"crypto/hmac"
"encoding/base64"
"hash"
"sync"
)
// Hasher represents a hash generator.
type Hasher interface {
Hash(string) string
}
// PlainTextHasher implements the hasher interface and return input as is without hashing it.
type PlainTextHasher struct{}
// Hash return str as is without hashing it.
func (p PlainTextHasher) Hash(str string) string { return str }
// HMACHasher implements the hasher interface and hash input using HMAC hashing alg.
type HMACHasher struct {
p *sync.Pool
}
// Hash str and return output as base64.
func (hm HMACHasher) Hash(str string) string {
h := hm.p.Get().(hash.Hash)
if _, err := h.Write([]byte(str)); err != nil {
// Write() on hash never fails
panic(err)
}
return base64.StdEncoding.EncodeToString(h.Sum(nil))
}
// NewHMACHasher return new hmac hasher instance.
func NewHMACHasher(h crypto.Hash, key []byte) *HMACHasher {
return &HMACHasher{
p: &sync.Pool{
New: func() interface{} {
return hmac.New(h.New, key)
},
},
}
}