-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathhashing.go
More file actions
47 lines (41 loc) · 1.31 KB
/
hashing.go
File metadata and controls
47 lines (41 loc) · 1.31 KB
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 utils
import (
"EverythingSuckz/fsb/config"
"EverythingSuckz/fsb/internal/types"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"strconv"
"time"
)
func PackFile(fileName string, fileSize int64, mimeType string, fileID int64) string {
return (&types.HashableFileStruct{FileName: fileName, FileSize: fileSize, MimeType: mimeType, FileID: fileID}).Pack()
}
func GetShortHash(fullHash string) string {
return fullHash[:config.ValueOf.HashLength]
}
func CheckHash(inputHash string, expectedHash string) bool {
return inputHash == GetShortHash(expectedHash)
}
// SignURL generates a truncated HMAC-SHA256 signature for messageID:expiry.
func SignURL(messageID int, expiry int64) string {
payload := fmt.Sprintf("%d:%d", messageID, expiry)
mac := hmac.New(sha256.New, []byte(config.ValueOf.BotToken))
mac.Write([]byte(payload))
return hex.EncodeToString(mac.Sum(nil))[:config.ValueOf.HashLength]
}
func VerifyURL(sig string, messageID int, expiryStr string) (string, bool) {
expiry, err := strconv.ParseInt(expiryStr, 10, 64)
if err != nil {
return "invalid expiry", false
}
if expiry != 0 && time.Now().Unix() > expiry {
return "link has expired", false
}
expected := SignURL(messageID, expiry)
if !hmac.Equal([]byte(sig), []byte(expected)) {
return "invalid signature", false
}
return "", true
}