44 lines
899 B
Go
44 lines
899 B
Go
// Copyright (C) 2021 Marius Schellenberger
|
|
|
|
package server
|
|
|
|
import (
|
|
"crypto/hmac"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"git.giftfish.de/ston1th/gowiki/pkg/log"
|
|
)
|
|
|
|
const (
|
|
keySize = 16
|
|
fullSize = keySize * 2
|
|
)
|
|
|
|
func genKey(length int) (bytes []byte) {
|
|
bytes = make([]byte, length)
|
|
if _, err := rand.Reader.Read(bytes); err != nil {
|
|
log.Println("genKey:", err)
|
|
}
|
|
return
|
|
}
|
|
|
|
func newXsrf(secret []byte) string {
|
|
mac := hmac.New(sha256.New, secret)
|
|
rnd := genKey(keySize)
|
|
mac.Write(rnd)
|
|
return base64.RawURLEncoding.EncodeToString(append(rnd, mac.Sum(nil)[:keySize]...))
|
|
}
|
|
|
|
func checkXsrf(xsrf string, secret []byte) bool {
|
|
t, err := base64.RawURLEncoding.DecodeString(xsrf)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
if len(t) != fullSize {
|
|
return false
|
|
}
|
|
mac := hmac.New(sha256.New, secret)
|
|
mac.Write(t[:keySize])
|
|
return hmac.Equal(t[keySize:], mac.Sum(nil)[:keySize])
|
|
}
|