NodeJS - How to generate certificate and private key with node-opcua-pki

2.6k Views Asked by At

I'm trying to establish an OPCUA connection between my NodeJS App (Client side) and an OPCUA server (not NodeJS based). I'm using the module node-opcua and I have no problem to connect to the OPCUA server with no encryption.

However I want my connection to be secured and encrypted. I'm trying to use the module node-opcua-pki to generate certificate & private key but I don't know how to use this module and where to run this command.

Do I have to run the command to generate my certificate and private key in the command line or in my NodeJS app?

Thanks in advance for your help!

1

There are 1 best solutions below

0
On

using the command line

$ npx node-opcua-pki certificate -o mycertificate.pem

this will create a self-signed certificate mycertificate.pem in the current folder.

this will also create a pki and the associated private key in .\certificates\PKI\own\private\private_key.pem if not exist already.

many options are available in the command line to let you specify the location of the pki or a specific subject string for the certificate.

$  npx node-opcua-pki certificate --help

programmatically

const certificateFolder = path.join(process.cwd(), "certificates");

const certificateFile = path.join(certificateFolder, "server_certificate.pem");

const certificateManager = new opcua.OPCUACertificateManager({
   rootFolder: certificateFolder,
});
await certificateManager.initialize();

if (!fs.existsSync(certificateFile)) {
   await certificateManager.createSelfSignedCertificate({
       subject: "/CN=MyCommonName;/L=Paris",
       startDate: new Date(),
       dns: [],
       validity: 365 * 5, // five year
       applicationUri: "Put you application URI here ",
       outputFile: certificateFile,
   });
}
const privateKeyFile = certificateManager.privateKey;
console.log("certificateFile =", certificateFile);
console.log("privateLeyFile =", privateKeyFile);