七牛时间戳防盗链go语言实现

package main

import (
    "crypto/md5"
    "flag"
    "fmt"
    "net/url"
    "strings"
    "time"
)

func main() {
    fmt.Println("-----生成token    ./timetoken -t 3600 -key key  -url 'url'")
    fmt.Println("-----验证token    ./timetoken  -key key  -url 'url'\n")

    var t int64
    var key string
    var resUrl string
    flag.Int64Var(&t, "t", 0, "expire timestamp")
    flag.StringVar(&key, "key", "", "encrypt key")
    flag.StringVar(&resUrl, "url", "", "resource url")
    flag.Parse()

    if t == 0 || key == "" || resUrl == "" {
        tokenurl, terro := url.Parse(resUrl)
        if terro != nil {
            return
        }
        sign_sign := tokenurl.Query().Get("sign")
        sign_t := tokenurl.Query().Get("t")
        sign_path := tokenurl.EscapedPath()
        sign_key := key
        sign_token := fmt.Sprintf("%s%s%s", sign_key, sign_path, sign_t)
        sign_token = md5_time(sign_token)
        if sign_token == sign_sign {
            fmt.Println("签名正确")
            return
        }
        fmt.Println("签名不正确")
        return
    }

    expireTime := fmt.Sprintf("%x", time.Now().Unix()+t)

    resUri, pErr := url.Parse(resUrl)
    if pErr != nil {
        return
    }
    fmt.Println(resUri)
    path := resUri.EscapedPath()
    fmt.Println(path)
    rawStr := fmt.Sprintf("%s%s%s", key, path, expireTime)
    fmt.Println(rawStr)
    sign := md5_time(rawStr)
    var newUrl string
    if strings.Contains(resUrl, "?") {
        newUrl = fmt.Sprintf("%s&sign=%s&t=%s", resUrl, sign, expireTime)
    } else {
        newUrl = fmt.Sprintf("%s?sign=%s&t=%s", resUrl, sign, expireTime)
    }

    fmt.Println(newUrl)
}

func md5_time(str string) string {
    md5H := md5.New()
    md5H.Write([]byte(str))
    sign := fmt.Sprintf("%x", md5H.Sum(nil))
    return sign
}

你可能感兴趣的:(七牛时间戳防盗链go语言实现)