Skip to content

Instantly share code, notes, and snippets.

@wil92
Created January 26, 2020 11:55
Show Gist options
  • Save wil92/a484dbe5d0ddc0601f4f9587cc53f6e5 to your computer and use it in GitHub Desktop.
Save wil92/a484dbe5d0ddc0601f4f9587cc53f6e5 to your computer and use it in GitHub Desktop.
const crypto = require('crypto');
function createHash(text, key) {
return crypto.createHmac('sha256', key).update(text).digest('base64');
}
function createJwt(payload, key) {
const head = Buffer.from(JSON.stringify({alg: "HS256", typ: "JWT"})).toString('base64');
payload = Buffer.from(JSON.stringify({
...(payload || {}),
exp: new Date().getTime() + 180000
})).toString('base64');
const sign = createHash(`${head}.${payload}`, key);
return `${head}.${payload}.${sign}`;
}
function checkJwt(jwt, key) {
const splitJwt = jwt.split('.');
if (splitJwt.length === 3) {
try {
if (createHash(`${splitJwt[0]}.${splitJwt[1]}`, key) === splitJwt[2]) {
const payload = JSON.parse(Buffer.from(splitJwt[1], 'base64').toString());
return parseInt(payload.exp) > new Date().getTime();
}
} catch (ignore) {}
}
return false;
}
const JWT = createJwt({id: 'tmpId', name: 'guille'}, 'this-is-my-private-credential');
console.log(JWT);
console.log(checkJwt(JWT, 'this-is-my-private-credential'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment