Skip to content

Instantly share code, notes, and snippets.

@AnsonT
Last active September 18, 2023 17:48
Show Gist options
  • Save AnsonT/73f659533317e429fcef09d5e0dbc20b to your computer and use it in GitHub Desktop.
Save AnsonT/73f659533317e429fcef09d5e0dbc20b to your computer and use it in GitHub Desktop.
Using Node-Jose to for RSA jwt with key store
import { JWE, JWK, JWS } from 'node-jose'
import fs from 'fs'
import { join } from 'path'
import jwkToPem from 'jwk-to-pem'
import jwt from 'jsonwebtoken'
const certDir = '.cert'
const keystoreFile = join(certDir, 'keystore.json')
const raw = {
iss: 'test',
exp: new Date().getTime() + 3600,
sub: {
test: 'This is a test',
},
}
async function start() {
var 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'))
keystore = await JWK.asKeyStore(ks.toString())
}
// Use first sig key
const key = keystore.all({ use: 'sig' })[0]
// Sign payload
const payload = JSON.stringify(raw)
const opt = { compact: true, jwk: key, fields: { typ: 'jwt' } }
const token = await JWS.createSign(opt, key)
.update(payload).final()
// Make JWT
console.log('JWT')
console.log(token)
// Verify Token
const v = await JWS.createVerify(keystore).verify(token)
console.log('Verify Token')
console.log(v.header)
console.log(v.payload.toString())
// Verify Token with jsonwebtoken
const publicKey = jwkToPem(key.toJSON())
const privateKey = jwkToPem(key.toJSON(true), {private: true})
console.log('public', publicKey)
console.log('private', privateKey)
const decoded = jwt.verify(token, publicKey)
console.log(decoded)
process.exit()
}
start()
@Brutalbeard
Copy link

Oh this is so what I needed!! Bless you!!

@andrehadianto
Copy link

It's 2021 and this code is still valid. Kudos to you!

@Taraawan
Copy link

Taraawan commented Oct 4, 2022

Any one working on RFC 7797 using nodejs please guide me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment