I'm using jsonwebtoken
to generate a bearer token.
Following the examples provided by the documentation my code looks like this
var privateKey = fs.readFileSync('src\\private.key'); //returns Buffer
let token = jwt.sign(myJsonContent, privateKey, { algorithm: 'RS256' });
This code returns this error in console
secretOrPrivateKey must be an asymmetric key when using RS256
I've tried including the key in my .env
file but the error is the same
I've also tried to declare privateKey
as a Buffer
but nothing changed.
Any solutions?
4 Answers
There was an answer to this post but it got deleted so I'm answering to my question again.
My code looks like this:
var privateKey = fs.readFileSync('src\\private.key', 'utf8');
let token = jwt.sign(myJsonContent, privateKey, { algorithm: 'RS256'});
The problem I was having was related to the privateKey not being asymmetric.
The problem was that the key needed to be written in a correct .PAM
format.
The .PAM
format looks like this:
-----BEGIN RSA PRIVATE KEY-----
encoded key etc
-----END RSA PRIVATE KEY-----
Unless you already have a key, you will need to generate it,
and to do so I used openssl
You can download it here
Once you download it open the bin folder and execute the file named "openssl.exe"
At this point paste this command
genrsa -out privateKey.key 2048
This will generate a file called privateKey.key
in the bin folder.
At this point you can either copy and paste the content of this file and use it as a key
or import the file in your project and use the readFileSync as I did.
This worked for me and fixed the problem I was having.
If you already have a key but you're having the same problem I suggest checking it with openssl
.
You can find many useful commands here that might help you.
crypto.createPrivateKey function is used to create an asymmetric key instance from the private key
const privateKey = crypto.createPrivateKey(privateKEY);
I was also facing the same issue when I upgraded my Ubuntu
from the 20.04.5
to the 22.04.2
version. It used to work well with the previous version. It seems that there is some system-related issue that occurs when we use it on Ubuntu 22.04.2
with Node 16.xx.xx
. It worked for me when I upgraded my Node.JS version from 16 to Node.JS 18
.
Solutions:
- Open the key file in any editor and simply delete the new line chat at the end of your file.
- Update the node version to current LTS (I had the same issue, this worked for me)
If you're using nvm, just try
nvm install 18.15.0
nvm use 18.15.0
You can specify the current LTS version of NODE. My case it was 18.15.0