Encoding the data to JWT token with NodeJS getting error PEM routines:PEM_read_bio:no start line

Viewed 2306

I tried to encode the data with the secret key using the jsonwebtoken package in nodejs and getting the following error:

error:0906D06C:PEM routines:PEM_read_bio:no start line Error while encode

The code that I used to encode the data using the secret key and algorithm is mention below:

var data = {
  sub: "1234567890",
  name: "John Doe"
};

var secretKey = "secret123";

var algorithm = { algorithm: "RS384" };

getJWTToken(data, secretKey, algorithm);

let getJWTToken = function(data, secretKey, algorithm) {
  console.log(token: jsonwebtoken.sign(data, secretKey, algorithm));  
};

It seems the problem is the algorithm. When I use the algorithm HS256, HS384 and HS512 it's working fine but when I used the algorithm RS256,RS384 and RS512 I am getting this error.

Can anyone help me out how to solve this issue?

1 Answers

For the RSA-algorithms you need to provide a private RSA key in PEM format to sign the token, and a public RSA key to verify it. You can't just pass a simple string like you do it for the HSxxx algorithms.

You can generate a public/private key pair with an online tool, or with openssl as described under that link or also down below.

And then read the key an sign the token like this (examples taken from the documentation):

// sign with RSA SHA256
var privateKey = fs.readFileSync('private.key');
var token = jwt.sign({ foo: 'bar' }, privateKey, { algorithm: 'RS256' });

and to verify with the public key:

// verify a token asymmetric
var cert = fs.readFileSync('public.pem');  // get public key
jwt.verify(token, cert, function(err, decoded) {
  console.log(decoded.foo) // bar
});

For ESxxx and PSxxx algorithms it's basically the same as for RSxxx algorithms. According to this you can generate and use the same key pair for RSxxx and Psxxx algorithms like this:

openssl genrsa 2048 -out rsa-2048bit-key-pair.pem  

For ES256 the keypair is different and would be generated like this:

openssl ecparam -genkey -name prime256v1 -noout -out ec256-key-pair.pem
Related