WABBIT0111
WABBIT0111

Reputation: 2313

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.

Upvotes: 10

Views: 12011

Answers (2)

ArkadiBernov
ArkadiBernov

Reputation: 578

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

Upvotes: 7

WABBIT0111
WABBIT0111

Reputation: 2313

I think i figured it out. When reading a private key file, you must include the ---BEGIN RSA PRIVATE KEY--- and ---END RSA PRIVATE KEY--- banner.

Upvotes: 0

Related Questions