4

I am using the jsonwebtoken module for Node. How can I get a secret key for the jwt.sign function: jwt.sign(payload, secretOrPrivateKey, [options, callback])

According to the documentation:

secretOrPrivateKey is a string, buffer, or object containing either the secret for HMAC algorithms or the PEM encoded private key for RSA and ECDSA. In case of a private key with passphrase an object { key, passphrase } can be used (based on crypto documentation), in this case be sure you pass the algorithm option.

The key used in the example was 'shhhh', but that probably isn't secure: var jwt = require('jsonwebtoken'); var token = jwt.sign({ foo: 'bar' }, 'shhhhh');

How can I get/generate a better secret key?

Chidi Williams
  • 399
  • 6
  • 16

3 Answers3

7

To create "secure" random passwords I like to use: openssl rand -base64 60 on Linux.

11AND2
  • 1,067
  • 7
  • 10
5

At first you should generate private key and public key using openssl by following two steps in command line on linux

Step1

openssl genrsa -out private-key.pem 1024

Step2.

openssl rsa -in private-key.pem -out public-key.pem -outform PEM -pubout

Now you can write jwt code in this way.

const fs = require('fs');
const jwt = require('jsonwebtoken');
const path = require('path');
const jwtPrivateKey = path.resolve('') + '/keys/private_key.pem';
const jwtPublicKey = path.resolve('') + '/keys/public_key.pem';

module.exports.generateToken = async(id, name, type) => {
  const payload = {
    id: id,
    name: name,
    type: type
  };
  const token = await  jwtSign(payload);
  return token;
};

module.exports.verifyToken = async(token) => {
  const result = await jwtVerify(token);
  return result;
};

module.exports.getPayloadFromToken = async(token) => {
  const payload = await jwtVerify(token);
  return payload;
};

const jwtSign = (payload) => {
  const options = {
    algorithm: 'RS256',
    expiresIn: '24h'
  }
  return new Promise((resolve, reject) => {
    try {
      const cert = fs.readFileSync(jwtPrivateKey);
      const token = jwt.sign(payload, cert, options);
      resolve(token);
    } catch (err) {
      reject(err);
    }
  })
}

const jwtVerify = (token) => {
  const options = {
    algorithms: ['RS256']
  }
  return new Promise((resolve, reject) => {
    try {
      const cert = fs.readFileSync(jwtPublicKey);
      const result = jwt.verify(token, cert, options);
      resolve(result);
    } catch (err) {
      reject(err);
    }
  })
}
Md. Maidul Islam
  • 564
  • 6
  • 10
0

Generate JWT secret from terminal jwt-secret-key-gen

  1. node
  2. require('crypto').randomBytes(64).toString('hex')
Al Mamun Khan
  • 551
  • 6
  • 7