zoukankan      html  css  js  c++  java
  • xsrftoken--源码笔记


    // Package xsrftoken provides methods for generating and validating secure XSRF tokens.
    package xsrftoken // import "golang.org/x/net/xsrftoken"

    import (
        "crypto/hmac"
        "crypto/sha1"
        "crypto/subtle"
        "encoding/base64"
        "fmt"
        "strconv"
        "strings"
        "time"
    )

    // 设置xsrf存活周期
    // 也许会设置和cookie生命周期一样
    const Timeout = 24 * time.Hour

    // 清理字符串中:替换为_ 。替换所有
    func clean(s string) string {
        return strings.Replace(s, ":", "_", -1)
    }

    // Generate returns a URL-safe secure XSRF token that expires in 24 hours.
    //返回一个安全且加密的url  默认存活周期为24小时
    // key  是应用程序的密钥.
    // userID  唯一标识符.
    // actionID 用户实际的动作(例如 :  访问的资源的地址).
    func Generate(key, userID, actionID string) string {
        return generateTokenAtTime(key, userID, actionID, time.Now())
    }

    // generateTokenAtTime is like Generate, but returns a token that expires 24 hours from now.
    func generateTokenAtTime(key, userID, actionID string, now time.Time) string {
        // now转化为毫秒
        milliTime := (now.UnixNano() + 1e6 - 1) / 1e6

        h := hmac.New(sha1.New, []byte(key))  //使用hmac进行加密
        fmt.Fprintf(h, "%s:%s:%d", clean(userID), clean(actionID), milliTime)

        // Get the padded base64 string then removing the padding.
        tok := string(h.Sum(nil))
        tok = base64.URLEncoding.EncodeToString([]byte(tok))
        tok = strings.TrimRight(tok, "=")

        return fmt.Sprintf("%s:%d", tok, milliTime)
    }

    // Valid reports whether a token is a valid, unexpired token returned by Generate.
    //验证 token 对应的key  userid  actionID  是否正确  并且在存活周期中
    func Valid(token, key, userID, actionID string) bool {
        return validTokenAtTime(token, key, userID, actionID, time.Now())
    }

    // validTokenAtTime reports whether a token is valid at the given time.
    func validTokenAtTime(token, key, userID, actionID string, now time.Time) bool {
        // Extract the issue time of the token.
        sep := strings.LastIndex(token, ":")
        if sep < 0 {
            return false
        }
        millis, err := strconv.ParseInt(token[sep+1:], 10, 64)
        if err != nil {
            return false
        }
        issueTime := time.Unix(0, millis*1e6)

        // Check that the token is not expired.
        if now.Sub(issueTime) >= Timeout {
            return false
        }

        // Check that the token is not from the future.
        // Allow 1 minute grace period in case the token is being verified on a
        // machine whose clock is behind the machine that issued the token.
        if issueTime.After(now.Add(1 * time.Minute)) {
            return false
        }

        expected := generateTokenAtTime(key, userID, actionID, issueTime)

        // Check that the token matches the expected value.
        // Use constant time comparison to avoid timing attacks.
        return subtle.ConstantTimeCompare([]byte(token), []byte(expected)) == 1
    }

  • 相关阅读:
    第三届“百越杯”福建省高校网络空间安全大赛Do you know upload?
    [百度杯-二月场](Misc-Web)爆破-3
    屌丝程序员的梦想 (一)
    屌丝程序员寻爱记(一)
    MYSQL里使用正则的速度快还是使用like模糊查询语句快?
    mybatis源码探究(-)MapperProxyFactory&MapperProxy
    设计模式-责任链模式在实际项目中的使用
    java8的正确使用姿势
    Guava EventBus集成spring
    jenkins中集成commander应用
  • 原文地址:https://www.cnblogs.com/zhangboyu/p/7452804.html
Copyright © 2011-2022 走看看