-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsecurity.go
65 lines (50 loc) · 1.18 KB
/
security.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
53
54
55
56
57
58
59
60
61
62
63
64
65
package discord
import (
"bytes"
"crypto/ed25519"
"encoding/hex"
"errors"
"io"
"net/http"
"os"
)
type RequestSignature struct {
Signature string
Timestamp string
}
func printSecurityCheck(verified bool) {
var result string
if verified {
result = "passed"
} else {
result = "failed"
}
println("Security check:", result)
}
func VerifySignature(r *http.Request) error {
signature := GetRequestSignature(r)
_rawBody, err := io.ReadAll(r.Body)
r.Body = io.NopCloser(bytes.NewBuffer(_rawBody))
if err != nil {
println("Fail to read body")
os.Exit(1)
}
message := []byte(signature.Timestamp + string(_rawBody))
publicKey := os.Getenv("DISCORD_PUBLIC_KEY")
hexPublicKey, _ := hex.DecodeString(publicKey)
hexSignature, _ := hex.DecodeString(signature.Signature)
verified := ed25519.Verify(hexPublicKey, message, hexSignature)
printSecurityCheck(verified)
if !verified {
return errors.New("invalid signature")
}
return nil
}
func GetRequestSignature(r *http.Request) RequestSignature {
signature := r.Header.Get("X-Signature-Ed25519")
timestamp := r.Header.Get("X-Signature-Timestamp")
return RequestSignature{
Signature: signature,
Timestamp: timestamp,
}
}