Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node-forge how to read a private rsa key from file

This question is related to Issue using RSA encryption in javascript

I have a node script that I am trying to read a PEM RSA private key from a file:

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);

The test.key file has a format like this:

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

When I tried to import the file, the line fails at pkeyAsn1 = forge.asn1.fromDer(pkey);, giving this error: Too few bytes to read ASN.1 value.

I don't know too much about the file format, would somebody help me?

The private key file i generated is using the following openssl command: openssl rsa -in encrypted_test.key -out test.key and I entered my passphrase to decrypt such rsa key.

like image 347
WABBIT0111 Avatar asked Apr 19 '17 17:04

WABBIT0111


People also ask

How do I read a PEM file in node?

You can't require a PEM file - that's only used for JS & JSON files. The error is a complaint that the PEM file is not valid JS syntax. To read raw data from other files, including PEM, you can use the fs module: https://nodejs.org/api/fs.html. Save this answer.

What do I do with my RSA private key?

The RSA private key is used to generate digital signatures, and the RSA public key is used to verify digital signatures. The RSA public key is also used for key encryption of DES or AES DATA keys and the RSA private key for key recovery.

How do I read a PFX file in node JS?

const pem = require("pem"); const fs = require("fs"); const pfx = fs. readFileSync(__dirname + "/test. pfx"); pem. readPkcs12(pfx, { p12Password: "password" }, (err, cert) => { console.


1 Answers

Read pkey as bytes and use forge.pki.privateKeyFromPem.

Working code:

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);
like image 166
ArkadiBernov Avatar answered Oct 05 '22 10:10

ArkadiBernov