sohaib
sohaib

Reputation: 766

How to decrypt JWE via RSA private key in next js?

We have a JWE token that we want to decrypt using a given RSA private key. If the token is valid, we will grant access to the website; otherwise, the user will be redirected to https://example.com. I have used the node-jose and jose libraries, but I am unsure how to implement this in Next.js.

Here is my middelware.js:

import cookie from 'cookie';
import { NextResponse } from 'next/server';
import jose from 'node-jose';
import { Buffer } from 'buffer';
// Your private key in PEM format

const privateKey = `-----BEGIN RSA PRIVATE KEY-----
// key here
-----END RSA PRIVATE KEY-----`;


export async function middleware(req) {
 const token = 'token here'; // Sample token
  if (!token) {
    console.log('No token found, redirecting...');
    return NextResponse.redirect('https://www.example.com');
  }
  try {
    // Create a keystore and add the private key
    const keystore = jose.JWK.createKeyStore();
    await keystore.add(privateKey, 'pem');
    console.log('Key added to keystore:', keystore);
    // Define the allowed algorithms for decryption
    const opts = {
      algorithms: ['RSA-OAEP', 'A256GCM']
    };
    // Decrypt the JWE token
    const decryptedToken = await jose.JWE.createDecrypt(keystore, opts).decrypt(token);
    // Decode and parse the payload
    const decodedPayload = JSON.parse(decryptedToken.plaintext.toString());
    console.log('Decoded payload:', decodedPayload);
    // Check token expiry
    if (decodedPayload.exp < Math.floor(Date.now() / 1000)) {
      console.log('Token expired, redirecting...');
      return NextResponse.redirect('https://www.example.com');
    }
    console.log('Token is valid, continuing request...');
    return NextResponse.next();
  } catch (err) {
    console.error('Token decryption failed:', err);
    return NextResponse.redirect('https://www.example.com');
  }

Upvotes: 0

Views: 138

Answers (1)

Filip Skokan
Filip Skokan

Reputation: 211

Here's a snippet using a different module.

You'll need to encode your private key as PKCS#8 instead of PKCS#1, or just use JWK format and importJWK.

import * as jose from 'jose';

// key needs to be in PKCS#8 format, not PKCS#1
const privateKeyPem = `-----BEGIN PRIVATE KEY-----
// key here
-----END PRIVATE KEY-----`;

const alg = 'RSA-OAEP'
const enc = 'A256GCM'

const privateKey = await jose.importPKCS8(privateKeyPem, alg)

export async function middleware(req) {
 const token = 'token here'; // Sample token
  if (!token) {
    console.log('No token found, redirecting...');
    return NextResponse.redirect('https://www.example.com');
  }
  try {
    await jose.jwtDecrypt(token, privateKey, {
      keyManagementAlgorithms: [alg],
      contentEncryptionAlgorithms: [enc]
    })
    console.log('Token is valid and not expired, continuing request...');
    return NextResponse.next();
  } catch (err) {
    if (err.code === 'ERR_JWT_EXPIRED') {
      console.log('Token is expired');
    }
    console.error('Token decryption failed:', err);
    return NextResponse.redirect('https://www.example.com');
  }
}

It is worth noting that if you issue these tokens yourself for yourself to consume then you're using the wrong cipher suite. With the one you've chosen anyone (presumably given the encryption is done with a PUBLIC key) can make their own tokens for your API to accept. If you issue these tokens yourself for yourself to consume then alg: dir and enc: A256CBC-HS512 would be a far more appropriate suite to use and it uses a 64 byte symmetric secret as a key.

Upvotes: 1

Related Questions