node-forge如何从文件中读取私有rsa密钥

时间:2017-04-19 17:18:50

标签: node.js encryption rsa

此问题与Issue using RSA encryption in javascript

有关

我有一个节点脚本,我试图从文件中读取PEM RSA私钥:

const forge = require('node-forge');
const fs = require('fs');
const path = require('path');
let pkey = fs.readFileSync(path.join(__dirname, 'test.key'), 'utf8');
//let pkeyDer = forge.util.decode64(pkey); // since it's not base64 encoded, i suppose don't need to decode
let pkeyAsn1 = forge.asn1.fromDer(pkey);
let privateKey = forge.pki.privateKeyFromAsn1(pkeyAsn1);

test.key文件的格式如下:

-----BEGIN RSA PRIVATE KEY-----
{mumbo jumbo line1}
{mumbo jumbo line2}
...
-----END RSA PRIVATE KEY-----

当我尝试导入文件时,该行在pkeyAsn1 = forge.asn1.fromDer(pkey);失败,出现此错误:   Too few bytes to read ASN.1 value.

我对文件格式不太了解,有人会帮助我吗?

我生成的私钥文件使用以下openssl命令: openssl rsa -in encrypted_test.key -out test.key我输入了密码来解密这样的rsa密钥。

2 个答案:

答案 0 :(得分:0)

我想我明白了。阅读私钥文件时,您必须包含---BEGIN RSA PRIVATE KEY------END RSA PRIVATE KEY---横幅。

答案 1 :(得分:0)

将pkey读取为字节,并使用forge.pki.privateKeyFromPem。

工作代码:

const forge = require('node-forge');
const fs = require('fs');
const path = require('path');
let pkey = fs.readFileSync(path.join(__dirname, 'test.key'));
let privateKey = forge.pki.privateKeyFromPem(pkey);