JSON Web Encryption (JWE) token - Encoding

node v18.11.0
version: 1.0.0
endpointsharetweet
This is demo runkit for creating JWE token using given asymmetric keys. Lets create RS2048 key pair pragrammitically to use in this demo.
const jose = require('node-jose'); // Generate a new RSA key pair // this is for convinienve of this demo, replace this with your key generation logic async function createKeysForSigning() { const keystore = jose.JWK.createKeyStore(); const props = { use: 'sig', alg: 'RSA-OAEP', }; const createdKey = await keystore.generate("RSA", 2048, props) const key = createdKey.toJSON(); // we are logging private key so we can use it in the decoding solution const privateKeyPem = createdKey.toPEM(true); console.log(privateKeyPem); // set key options key.use = "enc"; key.key_ops = ["encrypt", "verify", "wrap"]; // set the key to store store const signKey = await jose.JWK.asKey(key); return signKey; }
Following function generates JWE token using given keys
async function generateJWE(claims, signKey) { // token options const contentAlg = 'A256GCM'; var options = { zip: false, compact: true, contentAlg: contentAlg, fields: { "alg": signKey.alg, "kid": signKey.kid, "enc": contentAlg } }; // Create a JWE payload const payload = Buffer.from(JSON.stringify(claims)); // Create a JWE encrypter const encrypter = jose.JWE.createEncrypt( options, signKey ); // Encrypt the payload and create a JWE token const jweToken = await encrypter.update(payload).final(); console.log('Generated JWE token:', jweToken); }
Lets call the function to generate JWE token.
// token payload with sensitive information var dt = new Date(); var iat = Math.floor((dt.getTime() / 1000)); var exp = Math.floor(new Date(dt.getTime() + (20 * 60 * 1000)) / 1000); const claims = { "mobileNumber": "04000001", "customerId": "2011192232", "customerEmail": "abc@test.com", "sessionId": "3a600342-a7a3-4c66-bbd3-f67de5d7096f", exp, iat, nbf: iat, "jti": "f3902a08-0e24-4dcc-bed1-f4cd9611bfad" }; const signKey = await createKeysForSigning(); await generateJWE(claims, signKey);
Loading…

no comments

    sign in to comment