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.
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.
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.
const pem = require("pem"); const fs = require("fs"); const pfx = fs. readFileSync(__dirname + "/test. pfx"); pem. readPkcs12(pfx, { p12Password: "password" }, (err, cert) => { console.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With