Wednesday, 19 April 2017

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?



via WABBIT0111

No comments:

Post a Comment