[英]Encoding the data to JWT token with NodeJS getting error PEM routines:PEM_read_bio:no start line
I tried to encode the data with the secret key using the jsonwebtoken
package in nodejs and getting the following error:我尝试在 nodejs 中使用
jsonwebtoken
package 使用密钥对数据进行编码,但出现以下错误:
error:0906D06C:PEM routines:PEM_read_bio:no start line
错误:0906D06C:PEM 例程:PEM_read_bio:无起始行
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.当我使用算法
HS256
、 HS384
和HS512
时它工作正常但是当我使用算法RS256
、 RS384
和RS512
时出现此错误。
Can anyone help me out how to solve this issue?谁能帮我解决这个问题?
For the RSA-algorithms you need to provide a privateRSA key in PEM format to sign the token, and a public RSA key to verify it.对于 RSA 算法,您需要提供一个PEM 格式的RSA 私钥来签署令牌,并提供一个 RSA 公钥来验证它。 You can't just pass a simple string like you do it for the HSxxx algorithms.
您不能像为 HSxxx 算法那样只传递一个简单的字符串。
You can generate a public/private key pair with an online tool , or with openssl as described under that link or also down below.您可以使用在线工具或 openssl 生成公钥/私钥对,如该链接或下方所述。
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.对于 ESxxx 和 PSxxx 算法,它与 RSxxx 算法基本相同。 According to this you can generate and use the same key pair for RSxxx and Psxxx algorithms like this:
根据这个,您可以为 RSxxx 和 Psxxx 算法生成和使用相同的密钥对,如下所示:
openssl genrsa 2048 -out rsa-2048bit-key-pair.pem
For ES256 the keypair is different and would be generated like this:对于 ES256,密钥对不同,生成方式如下:
openssl ecparam -genkey -name prime256v1 -noout -out ec256-key-pair.pem
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.