oven-exporter/signed-policy/main.go

47 lines
1.1 KiB
Go
Raw Normal View History

package signedPolicy
import (
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"encoding/json"
"net/url"
)
type Policy struct {
URLExpire int `json:"url_expire"`
URLActivate int `json:"url_activate,omitempty"`
StreamExpire int `json:"stream_expire,omitempty"`
AllowIP string `json:"allow_ip,omitempty"`
}
func (p Policy) Encode() string {
str, err := json.Marshal(p)
if err != nil {
return ""
}
return base64.RawStdEncoding.EncodeToString(str)
}
func SignEncodedPolicy(url *url.URL, secretKey string) string {
hasher := hmac.New(sha1.New, []byte(secretKey))
hasher.Write([]byte(url.String()))
return base64.RawURLEncoding.EncodeToString(hasher.Sum(nil))
}
func (p Policy) Sign(url *url.URL, secretKey string) string {
query := url.Query()
query.Add("policy", p.Encode())
url.RawQuery = query.Encode()
return SignEncodedPolicy(url, secretKey)
}
func (p Policy) SignURL(url *url.URL, secretKey string) {
encode := p.Encode()
query := url.Query()
query.Add("policy", encode)
url.RawQuery = query.Encode()
signature := SignEncodedPolicy(url, secretKey)
query.Add("signature", signature)
url.RawQuery = query.Encode()
}