Skip to content

Instantly share code, notes, and snippets.

@ardinusawan
Last active February 22, 2023 07:02
Show Gist options
  • Save ardinusawan/3269e36187c782ab903808ec33701d7c to your computer and use it in GitHub Desktop.
Save ardinusawan/3269e36187c782ab903808ec33701d7c to your computer and use it in GitHub Desktop.
JWE using JOSE with EdDSA algorithm in NodeJS

JWS & JWT using JOSE

How

  1. npm i jose

JWE using alg dir and A128GCM enc

node jwe.js

JWS using alg EdDSA and ed25519 enc

node jws.js
const jose = require('jose')
async function getJWK() {
const secret = await jose.generateSecret('A128GCM')
// const secret = { kty: 'oct', k: 'cJRCTtsXeCmGPtFFk9WJyA' } (or create secret by urself)
const jwk = await jose.importJWK(
secret,
'A128GCM',
)
return jwk
}
async function encryptJWT(jwk, payload) {
const jwe = await new jose.EncryptJWT(payload)
.setProtectedHeader({ alg: 'dir', enc: 'A128GCM' })
.setIssuedAt()
.setExpirationTime('12h')
.encrypt(jwk)
return jwe;
}
async function decryptJWT(jwk) {
const { plaintext, protectedHeader } = await jose.compactDecrypt(jwe, jwk)
// console.log("protectedHeader", protectedHeader)
return new TextDecoder().decode(plaintext);
}
(async() => {
let jwk = await getJWK();
content = { 'foo': 'bar'}
console.log('original content', content);
let jwe = await encryptJWT(jwk, content);
console.log(`\njwe: ${jwe}`);
let decryptedContent = await decryptJWT(jwk);
console.log(`\ndecrypted content: ${decryptedContent}`);
})();
const jose = require('jose')
const crypto = require('crypto')
async function getPrivateKey() {
const { publicKey, privateKey } = crypto.generateKeyPairSync('ed25519');
console.log("public key", publicKey.export({format:'pem',type:'spki'}))
console.log("private key", privateKey.export({format:'pem',type:'pkcs8'}))
return privateKey
}
async function signJWT(privateKey, payload) {
const jwt = await new jose.SignJWT(payload)
.setProtectedHeader({ alg: 'EdDSA' })
.setIssuedAt()
.setExpirationTime('12h')
.sign(privateKey)
return jwt;
}
(async() => {
let privateKey = await getPrivateKey()
payload = {
"foo": "bar"
}
jws = await signJWT(privateKey, payload);
console.log("jws", jws);
try {
// verify token
const { payload, protectedHeader } = await jose.jwtVerify(jws, privateKey);
// log values to console
console.log("\nresult:");
console.log("protectedHeader", protectedHeader);
console.log("payload", payload);
} catch (e) {
// token verification failed
console.log("Token is invalid");
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment