nestjspemjwkjosenode-rsa

Convert jwk to pem in nest.js


I have this jwk key that I wanto convert into pem:

const jwkey = {
  kty: 'RSA',
  kid: 'eecb0ced-4d49-4100-9547-841e4100b756',
  n: '...very long string',
  e: 'AQAB',
  alg: 'RS256',
  use: 'sig',
};

I have tried the libraries like jose, node-rsa and jwk-To-Pem but somehow all of them are failing and throws error here and there while configuring.

I literally have no idea how to configure it.

below is the example of node-rsa conversion:

const key = new NodeRSA();
key.importKey(
  {
    n: Buffer.from(jwkey.n, 'base64'),
    e: Buffer.from(jwkey.e, 'base64'),
  },
  'components'
);

 const pem = key.exportKey('pkcs1-private-pem');

Solution

  • You could use 'jwk-to-pem' module.

    const jwkToPem = require("jwk-to-pem")
    
    const jwkey = {
      kty: "RSA",
      alg: "RS512",
      kid: "26887d3ee3293c526c0e6dd05f122df53aa3f13d7dad06d25e266fa6f51db79fb52422aaf79f121476237e98dcd6640350fee47fec70e783544ec9a36e4605bc",
      use: "sig",
      n: "14m79mVwIE0JxQdKrgXVf7dVcBS90U0TvG7Yf7dG4NJocz1PNUrKrzGhe_FryOe0JahL_sjA2_rKw7NBCpuVx_zSPFRw6kqjewGicjXGus5Fmlf3zDuqwV4BWIFHyQexMPOly0agFfcM0M0MgBULXjINgBs9MwnRv7JVfRoGqXHsNM45djFDd3o4liu4LPlge_DquZUFLNu-BYAyAlWkz0H2TepZhGrN9VEPmxzQkNzXc1R4MpZvbxrRRgaAA2z094ik3hk86JhfyFq-LDcueZhtshmrYZ95LWgMlQ7PixkeK1HkeEYMt20lmNzR8B8KabimYmibxA4Ay9gpRwfp-Q",
      e: "AQAB",
    }
    
    console.log("jwkey : ", jwkey)
    
    const pem = jwkToPem(jwkey)
    
    console.log("create pem : ", pem)
    
    

    enter image description here