46 lines
1.1 KiB
Go
46 lines
1.1 KiB
Go
package publicasset
|
|
|
|
import (
|
|
"crypto/hmac"
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"fmt"
|
|
"strings"
|
|
)
|
|
|
|
func SignObjectKey(objectKey string, secret string) string {
|
|
encodedKey := base64.RawURLEncoding.EncodeToString([]byte(objectKey))
|
|
mac := hmac.New(sha256.New, []byte(strings.TrimSpace(secret)))
|
|
_, _ = mac.Write([]byte(objectKey))
|
|
signature := base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
|
|
return fmt.Sprintf("%s.%s", encodedKey, signature)
|
|
}
|
|
|
|
func ParseObjectKeyToken(token string, secret string) (string, bool) {
|
|
objectKey, ok := ObjectKeyFromToken(token)
|
|
if !ok {
|
|
return "", false
|
|
}
|
|
expected := SignObjectKey(objectKey, secret)
|
|
if !hmac.Equal([]byte(expected), []byte(strings.TrimSpace(token))) {
|
|
return "", false
|
|
}
|
|
return objectKey, true
|
|
}
|
|
|
|
func ObjectKeyFromToken(token string) (string, bool) {
|
|
parts := strings.Split(strings.TrimSpace(token), ".")
|
|
if len(parts) != 2 {
|
|
return "", false
|
|
}
|
|
objectKeyBytes, err := base64.RawURLEncoding.DecodeString(parts[0])
|
|
if err != nil {
|
|
return "", false
|
|
}
|
|
objectKey := strings.TrimSpace(string(objectKeyBytes))
|
|
if objectKey == "" {
|
|
return "", false
|
|
}
|
|
return objectKey, true
|
|
}
|