18.jwt加密
jwt 官网https://jwt.io/
jwt:json web token
jwt-simple: https://www.npmjs.com/package/jwt-simple
jsonwebtoken:https://www.npmjs.com/package/jsonwebtoken
express-jwt : https://www.npmjs.com/package/express-jwt
安装:
cnpm i -S jwt-simple
JWT的结构
JWT包含了使用.分隔的三部分: Header 头部 Payload 负载 Signature 签名
其结构看起来是这样的Header.Payload.Signature
传输方式:
1、get
2、post
3、headers
headers:{
Authorization: `Beare ${token}`
}
获取 req.headers["authorization"]
核心:base64
1、编码 Buffer.from(str/buffer).toString("base64");
2、解码 Buffer.from(str/buffer,"base64").toString();
exp1:
jwt-simple使用
jwt.js
1、
const jwt = require ("jwt-simple");
let payload = {username:"aaa"};
const secret = "secret";
const token = jwt.encode(payload,secret);
console.log("jwt toekn",token);
var decoded = jwt.decode(token,secret);
console.log(decoded);
2、
const jwt = require ("jwt-simple");
let payload = {username:"aaa"};
const secret = "secret";
let token = jwt.encode(payload,secret);
console.log("jwt toekn","|"+token+"|");
//token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybddmFtZSI6ImFhYSJ9.fTx6_s9QbdddSyt5zXqtdqBqmwIdmoN9ju0f8dpOf5oPlc ";
token ="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImFhYSJ9.fTx6_s9QbSyt5zXqtdqBqmwIdmoN9ju0f8dpOf5oPlc"
var decoded = jwt.decode(token,secret);
console.log(decoded);
base64:
图片转base64:
const fs = require("fs");
let data = fs.readFileSync("1.png");
let base64 = Buffer.from(data).toString("base64");
console.log(base64);
转base64:
let secret = "secret";//c2VjcmV0
let base64 = Buffer.from(secret).toString("base64");
console.log(base64);
解base64:
let base64 = "c2VjcmV0";// secret
let secret = Buffer.from(base64,"base64").toString();
console.log(secret);
自己写jwt=> myjwt.js
const crypto = require("crypto");
const jwt = {
encodeBase64(str){
return Buffer.from(str).toString("base64");
},
decodeBase64(str){
return Buffer.from(str,"base64").toString();
},
//编码
encode(payload,secret){
let header = {"typ":"JWT","alg":"HS256"};
let headerBase64 = this.encodeBase64(JSON.stringify(header));
let payloadBase64 = this.encodeBase64(JSON.stringify(payload));
let sign = this.sign([headerBase64,payloadBase64].join("."),secret);
return [headerBase64,payloadBase64,sign].join(".");
},
//解码
decode(token,secret){
let [header,payload,sign] = token.split(".");
return JSON.parse(this.decodeBase64(payload));
},
sign(str,secret){
return crypto.createHmac("sha256",secret).update(str).digest("base64");
}
}
let payload = {username:"aaa"};
let secret = "secret";
let token = jwt.encode(payload,secret);
console.log(token);
payload = jwt.decode(token,secret);
console.log(payload);