JWT result: "invalid algorithm"

0

I'm securizing an application with "jsonwebtoken". The case is, after having managed to return the token correctly, I am about to verify.

'use strict'

const fs = require('fs'),
    jwt = require('jsonwebtoken'),
    moment = require('moment');


exports.createToken = (user) => {

    let payload = {
        sub: user._id,
        name: user.name,
        email: user.email,
        password: user.password,
        dateOfReg: user.dateOfReg,
        //expiresIn: moment().add(30, 'days').unix
    };

    let signOptions = {
        algorithm: 'RS256',
        expiresIn: "30d"
    };

    let privateKey = fs.readFileSync('./services/private.key', 'utf8');

    return  jwt.sign(payload, privateKey, signOptions);

}

As you can see, more or less, as proof, this works for me. But:

'use strict'

const jwt = require('jsonwebtoken'),
fs = require('fs'),
moment = require('moment');

exports.isAuth = (req, res, next) => {
    if(!req.headers.authorization){
        return res.status(200).send({message: 'Falta cabecera de autenticación.'});
    }

    let publicKey = fs.readFileSync('./services/public.pub', 'utf8');
    let token = req.headers.authorization.replace(/['"']+/g, '');

    let verifyOptions = {
        algorithms: ['RS256'],
        expiresIn: "30d"
    };

    try{
        jwt.verify(token, publicKey, verifyOptions, (err, decoded) => {
            if(err){ return res.send({message: 'Token no verificado', err: err}); }

            req.user = decoded;
        });
    }catch(e){
        return res.send({message: 'El token no es valido'});
    }

    next();

}

When I use this code as a middleware to verify, it gives me a result such as: "ivalid algorithm". I generated the keys through openssl with a command like this:

openssl genrsa -out private.key 256

and the public key extracting it from the private key:

openssl rsa -in private.key -pubout > public.pub

The case is that finally investigating a bit, I get to generate that same key, but this time as a parameter of the order instead of 256, I generate it with a length of 512 bits, that is, changing the parameter to 512 I proceed to perform the verification action, and it works correctly. I would like to know if there is someone capable of explaining this, or any place where I can find out. Because I get the feeling that I did not really know why it did not work before, and now with the 512-bit key, if it works perfectly. Greetings, thanks in advance.

    
asked by H. Díaz 31.07.2018 в 22:41
source

0 answers