You can't use Node's crypto
to generate a certificate, from their API docs there aren't any functions for creating one (they suggest using openSSL). You could certainly sign a certificate but that requires external actions.
What you can do, if you'd like a solution that does all of it in JS (as suggested also by @robertklep), is using a native implementation in JavaScript like Forge.
In this code sample you create a certificate, self-sign it and export it in PEM format. Forge has everything you need for it, so crypto
isn't required.
var forge = require('node-forge');
var pki = forge.pki;
// generate a keypair or use one you have already
var keys = pki.rsa.generateKeyPair(2048);
// create a new certificate
var cert = pki.createCertificate();
// fill the required fields
cert.publicKey = keys.publicKey;
cert.serialNumber = '01';
cert.validity.notBefore = new Date();
cert.validity.notAfter = new Date();
cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 1);
// use your own attributes here, or supply a csr (check the docs)
var attrs = [{
name: 'commonName',
value: 'example.org'
}, {
name: 'countryName',
value: 'US'
}, {
shortName: 'ST',
value: 'Virginia'
}, {
name: 'localityName',
value: 'Blacksburg'
}, {
name: 'organizationName',
value: 'Test'
}, {
shortName: 'OU',
value: 'Test'
}];
// here we set subject and issuer as the same one
cert.setSubject(attrs);
cert.setIssuer(attrs);
// the actual certificate signing
cert.sign(keys.privateKey);
// now convert the Forge certificate to PEM format
var pem = pki.certificateToPem(cert);
console.log(pem);
The process is pretty straighforward with relatively low amounts of code needed. The forge readme lists all other options, like supplying a csr for attributes and extensions instead of doing it all in code.