- npm i jose
node jwe.js
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"); | |
} | |
})(); |