let myJwt = {
sign(content,secret){
let r = crypto.createHmac(‘sha256’,secret).update(content).digest(‘base64’);
return this.base64urlEscape®
},
base64urlEscape(str){
return str.replace(/+/g, ‘-’).replace(///g, ‘’).replace(/=/g, ‘’);
},
toBase64(content){
return this.base64urlEscape(Buffer.from(JSON.stringify(content)).toString(‘base64’))
},
encode(username,secret){
let header = this.toBase64({ typ: ‘JWT’, alg: ‘HS256’ });
let content = this.toBase64(username);
let sign = this.sign([header,content].join(’.’),secret);
return [header,content,sign].join(’.’)
},
base64urlUnescape(str) {
str += new Array(5 - str.length % 4).join(’=’);
return str.replace(/-/g, ‘+’).replace(//g, ‘/’);
},
decode(token,secret){
let [header,content,sign] = token.split(’.’);
let newSign = this.sign([header,content].join(’.’),secret);
if(sign === newSign){
return Buffer.from(this.base64urlUnescape(content),‘base64’).toString();
}else{
throw new Error(‘被篡改’)
}
}
}
let myJwt = {
sign(content,secret){
let r = crypto.createHmac(‘sha256’,secret).update(content).digest(‘base64’);
return this.base64urlEscape®
},
base64urlEscape(str){
return str.replace(/+/g, ‘-’).replace(///g, ‘’).replace(/=/g, ‘’);
},
toBase64(content){
return this.base64urlEscape(Buffer.from(JSON.stringify(content)).toString(‘base64’))
},
encode(username,secret){
let header = this.toBase64({ typ: ‘JWT’, alg: ‘HS256’ });
let content = this.toBase64(username);
let sign = this.sign([header,content].join(’.’),secret);
return [header,content,sign].join(’.’)
},
base64urlUnescape(str) {
str += new Array(5 - str.length % 4).join(’=’);
return str.replace(/-/g, ‘+’).replace(//g, ‘/’);
},
decode(token,secret){
let [header,content,sign] = token.split(’.’);
let newSign = this.sign([header,content].join(’.’),secret);
if(sign === newSign){
return Buffer.from(this.base64urlUnescape(content),‘base64’).toString();
}else{
throw new Error(‘被篡改’)
}
}
}
base64urlUnescape的解码是固定写法,decode出base64的内容
最新推荐文章于 2023-12-26 14:16:26 发布