// 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
}

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

  1. Zepto源码笔记(一)

    最近在研究Zepto的源码,这是第一篇分析,欢迎大家继续关注,第一次写源码笔记,希望大家多指点指点,第一篇文章由于首次分析原因不会有太多干货,希望后面的文章能成为各位大大心目中的干货. Zepto是一 ...

  2. redis源码笔记(一) —— 从redis的启动到command的分发

    本作品采用知识共享署名 4.0 国际许可协议进行许可.转载联系作者并保留声明头部与原文链接https://luzeshu.com/blog/redis1 本博客同步在http://www.cnblog ...

  3. AsyncTask源码笔记

    AsyncTask源码笔记 AsyncTask在注释中建议只用来做短时间的异步操作,也就是只有几秒的操作:如果是长时间的操作,建议还是使用java.util.concurrent包中的工具类,例如Ex ...

  4. Java Arrays 源码 笔记

    Arrays.java是Java中用来操作数组的类.使用这个工具类可以减少平常很多的工作量.了解其实现,可以避免一些错误的用法. 它提供的操作包括: 排序 sort 查找 binarySearch() ...

  5. Tomcat8源码笔记(八)明白Tomcat怎么部署webapps下项目

    以前没想过这么个问题:Tomcat怎么处理webapps下项目,并且我访问浏览器ip: port/项目名/请求路径,以SSM为例,Tomcat怎么就能将请求找到项目呢,项目还是个文件夹类型的? Tom ...

  6. Tomcat8源码笔记(七)组件启动Server Service Engine Host启动

    一.Tomcat启动的入口 Tomcat初始化简单流程前面博客介绍了一遍,组件除了StandardHost都有博客,欢迎大家指文中错误.Tomcat启动类是Bootstrap,而启动容器启动入口位于 ...

  7. Tomcat8源码笔记(六)连接器Connector分析

    根据 Tomcat8源码笔记(五)组件Container分析 前文分析,StandardService的初始化重心由 StandardEngine转移到了Connector的初始化,本篇记录下Conn ...

  8. Tomcat8源码笔记(五)组件Container分析

    Tomcat8源码笔记(四)Server和Service初始化 介绍过Tomcat中Service的初始化 最先初始化就是Container,而Container初始化过程是咋样的? 说到Contai ...

  9. Tomcat8源码笔记(四)Server和Service初始化

    上一章 简单说明下Tomcat各个组件: Server:服务器,Tomcat服务器,一个Tomcat只有一个Server组件; Service:业务层,是Server下最大的子容器,一个Server可 ...

  10. Tomcat8源码笔记(三)Catalina加载过程

    之前介绍过 Catalina加载过程是Bootstrap的load调用的  Tomcat8源码笔记(二)Bootstrap启动 按照Catalina的load过程,大致如下: 接下来一步步分析加载过程 ...

随机推荐

  1. Fullpage.js全屏滚动jQuery插件

    兼容性: 支持 IE8+ 及其他现代浏览器. 主要功能: 1.支持鼠标滚动: 2.支持前进后退键盘控制; 3.多个回调函数; 4.支持手机.移动设备; 5.支持窗口缩放自动调整; 6.可设置滚动宽度. ...

  2. Best Time to Buy and Sell Stock i

    Say you have an array for which the ith element is the price of a given stock on day i. If you were ...

  3. JFace dailog button事件中刷新透视图异常 Trying to execute the disabled command org.eclipse.ui.window.closePerspective

    报错的代码为 protected void buttonPressed(int buttonId) { Display.getDefault().syncExec(new Runnable() { p ...

  4. Spring3 MVC使用@ResponseBody的乱码问题及解决办法

    近日用Spring3的MVC写东西,深感其之于Webwork/Struts2的便利,但是在通过@ResponseBody这个annotation输出一个json字符串的时候,发现页面上获得的json字 ...

  5. C语言关键字register、extern、static、一些总结,及项目中使用的心得

    首先介绍两个概念: 一.变量的生存周期: 变量从建立到撤销的时间段成变量的生存周期.静态变量,从变量产生到整个程序执行结束.当函数使用变量结束后,变量的存储空间依然存在,变量的值也会随着函数的对其的使 ...

  6. java -- 对Map按键排序、按值排序

                             java  -- 对Map按键.按值排序 1.按键排序(sort by key) 直接上代码  ↓ public Map<String, Str ...

  7. SpringBoot开发案例从0到1构建分布式秒杀系统

    前言 ​最近,被推送了不少秒杀架构的文章,忙里偷闲自己也总结了一下互联网平台秒杀架构设计,当然也借鉴了不少同学的思路.俗话说,脱离案例讲架构都是耍流氓,最终使用SpringBoot模拟实现了部分秒杀场 ...

  8. Unite Beijing 2018 参会简要分享

    一. Training Day 主讲人:鲍建运 操作:马瑞 课程包括较为完整的功能,如灯光设置,角色动画控制,Cinemachine,Timeline,AI寻路,以及最新的Post Processin ...

  9. PAT1110:Complete Binary Tree

    1110. Complete Binary Tree (25) 时间限制 400 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN, Yue ...

  10. EXCEL解析之终极方法WorkbookFactory

    Selenium做自动化测试当然不能避免和Excel打交道. 由于Excel版本的关系,文件扩展名分xls和xlsx, 以往的经验都是使用HSSFWorkbook和XSSFWorkbook来分别处理. ...