-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcsrf.go
executable file
·42 lines (36 loc) · 1.06 KB
/
csrf.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
package campid
import (
"crypto/hmac"
"crypto/sha512"
"encoding/hex"
"github.com/influx6/npkg/nerror"
"github.com/influx6/npkg/nunsafe"
)
type CSRFManager struct {
Secret string
}
func NewCSRFManager(secret string) *CSRFManager {
var cm CSRFManager
cm.Secret = secret
return &cm
}
func (c CSRFManager) Validate(csrfMessage string, tokenNeedingValidation string) error {
var hasher = hmac.New(sha512.New, nunsafe.String2Bytes(c.Secret))
var _, err = hasher.Write(nunsafe.String2Bytes(csrfMessage))
if err != nil {
return nerror.WrapOnly(err)
}
var generatedToken = hex.EncodeToString(hasher.Sum(nil))
if generatedToken != tokenNeedingValidation {
return nerror.New("token is not valid, was not generated by us").Add("token", tokenNeedingValidation)
}
return nil
}
func (c CSRFManager) Create(csrfMessage string) (string, error) {
var hasher = hmac.New(sha512.New, nunsafe.String2Bytes(c.Secret))
var _, err = hasher.Write(nunsafe.String2Bytes(csrfMessage))
if err != nil {
return "", nerror.WrapOnly(err)
}
return hex.EncodeToString(hasher.Sum(nil)), nil
}