Encrypted json token decode

Hello,

I tried using the JWS and JWE decode lately and I found it to be unable to use them, I spent few hours trying understanding why they were not working, finally I resolved to create lambda function using jose library.

Has anyone experienced the same? My token was encrypted and signed with the decryptionkey had to be decoded in base64(in bytes),

In case anyone needs it this I post here the snippet I created. Hope it helps anyone facing the same challenge.

const input = {
    token: YOURJWT,
    decryptionKey: YOURDECRYPTIONKEY,
    signatureKey: YOURSIGNATUREKEY,
};

async function decryptAndVerifyJWE(input) {
    try {
        // Setting the keys
        const decryptionKey = await jose.importJWK({ kty: 'oct', k: input.decryptionKey }, 'A256GCM');
        const signatureKey = Buffer.from(input.signatureKey, 'utf8'); // Signature key as Buffer

        // Decrypting JWE
        const { plaintext, protectedHeader } = await jose.compactDecrypt(input.token, decryptionKey);

        // Converting plaintext in string
        const decodedText = Buffer.from(plaintext).toString('utf8');

        // Verifying signature (assuming decrypted payload is a JWS)
        try {
            const { payload, protectedHeader: signatureHeader } = await jose.compactVerify(decodedText, signatureKey);
            const verifiedPayload = Buffer.from(payload).toString('utf8');

            return {
                result: JSON.parse(verifiedPayload),
                protectedHeader: protectedHeader,
                signatureHeader: signatureHeader
            };
        } catch (signatureError) {
            return {
                error: `Error on signature validation: ${signatureError.message}`,
                decodedPayload: decodedText
            };
        }
    } catch (error) {
        return {
            error: `Error on decryption: ${error.message}`
        };
    }
}

// Function result
const result = await decryptAndVerifyJWE(input);
return result;
Security
4 replies