Skip to content

Commit

Permalink
feat: add GenSign and VerifySign helper
Browse files Browse the repository at this point in the history
  • Loading branch information
fufuok committed Mar 8, 2024
1 parent 4ff40e0 commit b0e300a
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
38 changes: 38 additions & 0 deletions common/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ package common

import (
"net"
"strconv"

"github.com/fufuok/utils/xhash"
)

// LookupIPNetsString 从 IP 段集合中查询并返回对应数值
Expand All @@ -23,3 +26,38 @@ func LookupIPNets(ip net.IP, ipNets map[*net.IPNet]int64) (int64, bool) {
}
return 0, false
}

// GenSign 使用时间戳和密钥生成简单签名字符串
// 算法: md5(ts+key)
// 结果: ts+sign
func GenSign(ts int64, key string) string {
tss := strconv.FormatInt(ts, 10)
return GenSignString(tss, key)
}

// GenSignString 字符串类型的时间戳生成签名
func GenSignString(ts, key string) string {
if len(ts) != 10 || key == "" {
return ""
}
sign := xhash.MD5Hex(ts + key)
return ts + sign
}

// VerifySign 校验签名
func VerifySign(key, sign string) bool {
if key == "" || len(sign) != 42 {
return false
}
return sign == GenSignString(sign[:10], key)
}

// VerifySignTTL 校验签名及签名有效期(当前时间 **秒 范围内有效)
func VerifySignTTL(key, sign string, second int64) bool {
if ok := VerifySign(key, sign); !ok {
return false
}
ts, _ := strconv.ParseInt(sign[:10], 10, 64)
now := GTimestamp()
return ts >= now-second && ts <= now+second
}
17 changes: 17 additions & 0 deletions common/helper_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package common

import (
"testing"
"time"

"github.com/fufuok/utils"
"github.com/fufuok/utils/assert"
)

func TestGenSign(t *testing.T) {
key := utils.RandString(18)
ts := time.Now().Unix()
sign := GenSign(ts, key)
t.Log("sign:", sign)
assert.True(t, VerifySignTTL(key, sign, 1))
}

0 comments on commit b0e300a

Please sign in to comment.