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
}
				
时间: 2024-08-14 23:24:18

xsrftoken--源码笔记的相关文章

jquery 源码笔记:

1.使用了jquery,但是觉得了解 jquery的源码才能 更容易知道怎么使用,所以在网上找了一些 jquery的源码 笔记 还有看了 妙味课堂 的 一部分视频,现在写一些总结. 一.  jquery的 总体架构: 1.jquery 有良好的对外接口,  window.jQuery = window.$ = jQuery; 现在 是 通过jquery 2.0.3 源码的分析: (21,94)  21—94行, 定义了一些变量和函数,   jQuery = function(); (96,283

Backbone Events 源码笔记

用了backbone一段时间了,做一些笔记和总结,看的源码是1.12 backbone有events,model,collection,histoty,router,view这些模块,其中events是最基础的,其他的模块的prototype全部都扩展了他,所以events是非常重要的,真的很重要,还好代码比较简单,也比较好理解 这个里面的代码是从backbone里面剥离出来,然后一点一点研究和调试出来的,可以单独运行,依赖underscore 1 (function(){ 2 this.Bac

spark源码笔记

1.国际化 如添加朋友Friends是英文,可以找着相关的类,并在国际化配置文件中添加key 在项目中全局搜索"Friends",将得到的结果集全部展开,找到这两个文件: 在国际化配置文件spark_i18n_zh_CN.properties 中增加 custum.friends=朋友 修改代码为: groupBox.addItem(Res.getString("custum.friends")); spark源码笔记,码迷,mamicode.com

转载:Pixhawk源码笔记四:学习RC Input and Output

转自:新浪@WalkAnt 第五部分 学习RC Input and Output 参考:http://dev.ardupilot.com/wiki/learning-ardupilot-rc-input-output/ RC Input,也就是遥控输入,用于控制飞行方向.改变飞行模式.控制摄像头等外围装置.ArduPilot支持集中不同RC input(取决于具体的硬件飞控板): 1. PPMSum – on PX4, Pixhawk, Linux and APM2 2. SBUS – on P

backbone.Model 源码笔记

backbone.Model backbone的model(模型),用来存储数据,交互数据,数据验证,在view里面可以直接监听model来达到model一改变,就通知视图. 这个里面的代码是从backbone里面剥离出来,然后一点一点研究和调试出来的,可以单独运行,依赖underscore,jquery或者是zepto  event.js是剥离出来的Backbone.Events <!DOCTYPE html> <html> <head> <meta chars

【源码笔记】BlogEngine.Net 中的权限管理

BlogEngine.Net 是个功能点很全面的开源博客系统,容易安装和实现定制,开放接口支持TrackBack,可以定义主题配置数据源等等.可谓五脏俱全,这里先记录一下它基于Membership的权限管理(一般只说到角色就没了). Membership是.net2.0的时候就出来了,现在的最新版本是Identity(微软已经将这个Asp.net项目开源 https://github.com/aspnet/Identity ).权限管理就是处理用户.角色.和具体权限的关系.用户和角色是多对多的关

转载:Pixhawk源码笔记三:串行接口UART和Console

转自:新浪@WalkAnt 第四部分 串行接口UART和Console 详细参考:http://dev.ardupilot.com/wiki/learning-ardupilot-uarts-and-the-console/ UART很重要,用于调试输出,数传.GPS模块等. 1.5个UART 目前共定义了5个UART,他们的用途分别是: uartA – 串行终端,通常是Micro USB接口,运行MAVLink协议. uartB – GPS1模块. uartC – 主数传接口,也就是Pixha

转载:Pixhawk源码笔记二:APM线程

  转自:新浪@WalkAnt Pixhawk源码笔记一:APM代码基本结构,参见: http://blog.sina.com.cn/s/blog_402c071e0102v59r.html 这里,我们对 APM 线程进行讲解.如有问题,可以交流[email protected].新浪@WalkAnt,转载本博客文章,请注明出处,以便更大范围的交流,谢谢. 第三部分 APM线程 详细参考:http://dev.ardupilot.com/wiki/learning-ardupilot-threa

backbone.Collection源码笔记

Backbone.Collection backbone的Collection(集合),用来存储多个model,并且可以多这些model进行数组一样的操作,比如添加,修改,删除,排序,插入,根据索引取值,等等,数组有的方法,他基本上都有 源码注释 <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <meta name="viewport" content=

STL源码笔记(15)—堆和优先级队列(二)

STL源码笔记(15)-堆和优先级队列 优先级队列的源码实现基于heap的操作,底层容器默认是vector. 优先级队列简介 优先级队列跟队列类似,一端插入一端删除,不同的是,优先级队列的元素入队后会根据其优先级进行调整,默认情况下优先级高的将优先出队,在SGI STL中,优先级队列的功能保证由heap实现:stl_heap.h中,heap的分析见:STL堆源码分析 优先级队列构造函数 默认情况下,优先级队列使用vector作为底层容器,使用less作为比较函数,其在源码中的定义声明如下: te