I am writing a small project using Node.JS and TypeScript, once of the requirements is to read a PFX certificate from a .pfx file and use this in the code to encrypt the payload body
I have a certificate public/private key file called cert1.pfx
, my code requires this certificate as below
...
const cert = loadPfx("cert1.pfx");
const p: Payload = new Payload();
p.addReaderCertificate(cert);
...
I have searched around but cannot find a way to load the PFX for my use case, I have seen examples of loading a PFX for HTTPS server or Express.JS, I looked a node-x509 but that is for BASE64 encoded CER or PEM certificates, I also looked at node-rsa but thats for encrypt/decrypt using public/private keys.
Does anyone know if this is possible? If so would appreciate some pointers on how to accomplish.
readFileSync(__dirname + "/test. pfx"); pem. readPkcs12(pfx, { p12Password: "password" }, (err, cert) => { console. log(cert); });
Start Windows Explorer and select and hold (or right-click) the . pfx file, then select Open to open the Certificate Import Wizard. Follow the procedure in the Certificate Import Wizard to import the code-signing certificate into the Personal certificate store.
The contents of a pfx file can be viewed in the GUI by right-clicking the PFX file and selecting Open (instead of the default action, Install). This will open mmc and show the pfx file as a folder. Open the pfx folder and the Certificates subfolder, and you will see the certificate(s) contained in the pfx.
It sounds like you only need to use Node's own https capabilities. Node can read the PFX file directly. (Https.createServer, SSL Options)
Example from Node.js site:
const https = require('https');
const fs = require('fs');
const options = {
pfx: fs.readFileSync('test/fixtures/test_cert.pfx'),
passphrase: 'sample'
};
https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);
So after a LOT of research and trawling the Google archives I came across a package called pem
and this has the following method:
pem.readPkcs12(bufferOrPath, [options], callback)
This can read a PKCS#12 file (or in other words a *.pfx
or *.p12
file) amongst other things, I must have missed this in my earlier research.
Usage:
const pem = require("pem");
const fs = require("fs");
const pfx = fs.readFileSync(__dirname + "/test.pfx");
pem.readPkcs12(pfx, { p12Password: "password" }, (err, cert) => {
console.log(cert);
});
Output:
{ cert: "...", ca: ["subca", "rootca"], key: "..." }
You can find more here and here.
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