-
Notifications
You must be signed in to change notification settings - Fork 1
/
shared.go
52 lines (45 loc) · 1.16 KB
/
shared.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 websub
import (
"crypto/hmac"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"encoding/hex"
"hash"
"github.com/rs/zerolog"
)
var (
log = zerolog.New(zerolog.NewConsoleWriter()).With().Timestamp().Caller().Logger()
)
// Logger returns the logger the websub package uses
func Logger() zerolog.Logger {
return log
}
// calculates the hash using one of "sha1", "sha256", "sha384", or "sha512".
//
// If an unrecognized hash function is passed, "sha1" is used for compatability,
// and a warning is printed to the console.
func calculateHash(hashFunction_, secret string, content []byte) (hashResult string, hashFunction string) {
var hasher func() hash.Hash
hashFunction = hashFunction_
switch hashFunction_ {
case "sha1":
hasher = sha1.New
case "sha256":
hasher = sha256.New
case "sha384":
hasher = sha512.New384
case "sha512":
hasher = sha512.New
default:
log.Warn().
Str("hashFunction", hashFunction_).
Msg("hash function not recognized, using sha1")
hashFunction = "sha1"
hasher = sha1.New
}
mac := hmac.New(hasher, []byte(secret))
mac.Write(content)
hashResult = hex.EncodeToString(mac.Sum(nil))
return hashResult, hashFunction
}