Home > Blockchain >  Nodejs with typescript TypeError: Passphrase required for encrypted key
Nodejs with typescript TypeError: Passphrase required for encrypted key

Time:05-28

I am trying to make authentication with JWT in node js and following this tutorial https://www.becomebetterprogrammer.com/jwt-authentication-middleware-nodejs-typescript/ but now I am getting this error and don't know how to solve it

import { sign, SignOptions } from 'jsonwebtoken';
import * as fs from 'fs';
import * as path from 'path';

export function generateToken() {
    // information to be encoded in the JWT
    const passphrase = 'shivamyadav';
    const payload = {
        id: 1,  
        email: '',
        role: '',
        iat: new Date().getTime(), // current time,
    };
    // read private key value
    const privateKey = fs.readFileSync(path.join(__dirname, '../../private.pem'), 'utf8');
    // sign with RSA SHA256
    const signInOptions: SignOptions = {
      // RS256 uses a public/private key pair. The API provides the private key
      // to generate the JWT. The client gets a public key to validate the
      // signature
      algorithm: 'RS256',
      expiresIn: '1h',
    };
    
    const token = sign(payload, privateKey, signInOptions);
  }

and error is

node:internal/crypto/sig:131
[1]   const ret = this[kHandle].sign(data, format, type, passphrase, rsaPadding,
[1]                             ^
[1]
[1] TypeError: Passphrase required for encrypted key
[1]     at Sign.sign (node:internal/crypto/sig:131:29)
[1]     at Object.sign (D:\projects\pro14\node_modules\jwa\index.js:152:45)
[1]     at Object.jwsSign [as sign] (D:\projects\pro14\node_modules\jws\lib\sign-stream.js:32:24)
[1]     at module.exports (D:\projects\pro14\node_modules\jsonwebtoken\sign.js:204:16)
[1]     at generateToken (D:\projects\pro14\dist\utils\jwt.utils.js:49:43)
[1]     at Server.<anonymous> (D:\projects\pro14\dist\app.js:25:57)
[1]     at Object.onceWrapper (node:events:509:28)
[1]     at Server.emit (node:events:390:28)
[1]     at emitListeningNT (node:net:1368:10)
[1]     at processTicksAndRejections (node:internal/process/task_queues:82:21) {
[1]   code: 'ERR_MISSING_PASSPHRASE'
[1] }

CodePudding user response:

Use

const privateKey = {
  key: fs.readFileSync(path.join(__dirname, '../../private.pem'), 'utf8'),
  passphrase: <passphrase>
};

where <passphrase> is the passphrase that was chosen when the private key was generated or exported. For example, the openssl genrsa command mentioned in the tutorial prompts you for a passphrase before generating a private key.

  • Related