Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

node的crypto模块 #58

Open
Wscats opened this issue Oct 18, 2019 · 1 comment
Open

node的crypto模块 #58

Wscats opened this issue Oct 18, 2019 · 1 comment

Comments

@Wscats
Copy link
Owner

Wscats commented Oct 18, 2019

var crypto = require("crypto");
var token = {
	createToken: function(obj, timeout) {
		//后来加的时效性  token在30内都是有效的
		var timeout = 300000;
		
		console.log(parseInt(timeout) || 0);
		var obj2 = {
			data: obj, //payload
			created: parseInt(Date.now() / 1000), //token生成的时间的,单位秒
			exp: parseInt(timeout) || 10 //token有效期
		};
		//payload信息
		var base64Str = Buffer.from(JSON.stringify(obj2), "utf8").toString("base64");
		//添加签名,防篡改
		var secret = "piggyyao.com";
		var hash = crypto.createHmac('sha256', secret);
		hash.update(base64Str);
		var signature = hash.digest('base64');
		return base64Str + "." + signature;
	},
	decodeToken: function(token) {
		var decArr = token.split(".");
		if(decArr.length < 2) {
			//token不合法
			return false;
		}
		var payload = {};
		//将payload json字符串 解析为对象
		try {
			payload = JSON.parse(Buffer.from(decArr[0], "base64").toString("utf8"));
		} catch(e) {
			return false;
		}
		//检验签名
		var secret = "piggyyao.com";
		var hash = crypto.createHmac('sha256', secret);
		hash.update(decArr[0]);
		var checkSignature = hash.digest('base64');
		return {
			payload: payload,
			signature: decArr[1],
			checkSignature: checkSignature
		}
	},
	checkToken: function(token) {
		var resDecode = this.decodeToken(token);
		if(!resDecode) {

			return false;
		}
		//是否过期
		var expState = (parseInt(Date.now() / 1000) - parseInt(resDecode.payload.created)) > parseInt(resDecode.payload.exp) ? false : true;
		if(resDecode.signature === resDecode.checkSignature && expState) {
			return true;
		}
		return false;
	}
}
module.exports = exports = token;
@Heathy
Copy link

Heathy commented Nov 13, 2019

好像看姚先生写三十天免登入

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants