Skip to content

Instantly share code, notes, and snippets.

@henno
Created October 22, 2021 11:00
Show Gist options
  • Select an option

  • Save henno/3ab9de92b6d1475cd77ad03d2a6c7737 to your computer and use it in GitHub Desktop.

Select an option

Save henno/3ab9de92b6d1475cd77ad03d2a6c7737 to your computer and use it in GitHub Desktop.
node-jose sign and verify
const {JWK, JWS} = require('node-jose')
const fs = require('fs')
const {join} = require('path')
const jwkToPem = require('jwk-to-pem')
const jwt = require('jsonwebtoken')
const certDir = '.cert'
const keystoreFile = join(certDir, 'keystore.json')
async function getKeystore() {
const keystore = JWK.createKeyStore();
if (!fs.existsSync(keystoreFile)) {
if (!fs.existsSync(certDir)) {
fs.mkdirSync(certDir)
}
console.log('generate keystore')
await keystore.generate('RSA', 2048, {alg: 'RS256', use: 'sig'})
fs.writeFileSync(keystoreFile, JSON.stringify(keystore.toJSON(true)))
} else {
console.log('import keystore')
const ks = fs.readFileSync(join('.cert', 'keystore.json'))
return await JWK.asKeyStore(ks.toString())
}
}
async function getSigningKey() {
// Get keystore
const keystore = await getKeystore();
// Use first sig key
return keystore.all({use: 'sig'})[0]
}
async function getToken(dataToBeSigned, key) {
return await JWS.createSign({
compact: true,
jwk: key,
fields: {typ: 'jwt'}
}, key).update(JSON.stringify(dataToBeSigned)).final();
}
async function getV(signingKey, jwtString) {
return await JWS.createVerify(signingKey).verify(jwtString);
}
async function getDataFromJwt(jwtString, publicKey) {
return jwt.verify(jwtString, publicKey)
}
async function getPublicKey() {
const signingKey = await getSigningKey();
return jwkToPem(signingKey.toJSON())
}
async function start() {
// Sign
//const jwtString = await getToken({foo: "bar2"}, await getSigningKey())
const jwtString = "eyJ0eXAiOiJqd3QiLCJhbGciOiJSUzI1NiIsImtpZCI6IllhclE2anJXRG1GVVdEVGJ0NXdrSFhsaU1YYVlsbG1fbmZIdmVXeVBqTHMifQ.eyJmb28iOiJiYEIyIn0.WJ_gZGgXdVLR1tky49smb0UWvggSKH8xBIdqZ8ysWl_aTLNPnXHl8FmPkSEAATCzFwI6IOGFW6hVVlAjKLBEbfZG63xk-H3FQXlejR0jiIHeJ_VH0NpC0Gn3QJO6pIrQ0oYtpGdvLc_74_8QeL-ThDanN49HJAMN7xEvUHbz88ncI5kNIBdmUYlxeFE1Kl7b2JY49ghry7Ev28Ic6St2RbiOe2IkOCNIPpWKxSY1Zo_TLkb-48IeebSNgh4zh7-jBWNHHCAXd1z8jD-NlhqXn5umWEITUCD7X6w6p9tPGrsSiPCmol_IQkEgz-clZD5qosPC8K1AdVn2fHEoOtExGw"
console.log('JwtString:')
console.log(jwtString)
// Verify signature
const publicKey = await getPublicKey()
let data;
try {
data = await getDataFromJwt(jwtString, publicKey);
} catch (e) {
console.log('Viga: ' + e.message)
}
console.log(data)
}
start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment