Skip to content

Instantly share code, notes, and snippets.

@tareqmamari
Created August 20, 2020 09:32
Show Gist options
  • Save tareqmamari/9e333639f9209beba97f7aca998339d5 to your computer and use it in GitHub Desktop.
Save tareqmamari/9e333639f9209beba97f7aca998339d5 to your computer and use it in GitHub Desktop.
Create Certs with forge npm module. Reference: https://github.com/digitalbazaar/forge#x509
var forge = require("node-forge");
var pki = forge.pki;
var asn1 = forge.asn1;
// generate a keypair and create an X.509v3 certificate
var keys = pki.rsa.generateKeyPair(2048);
var cert = pki.createCertificate();
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);
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'
}];
cert.setSubject(attrs);
cert.setIssuer(attrs);
cert.setExtensions([{
name: 'basicConstraints',
cA: true
}, {
name: 'keyUsage',
keyCertSign: true,
digitalSignature: true,
nonRepudiation: true,
keyEncipherment: true,
dataEncipherment: true
}, {
name: 'extKeyUsage',
serverAuth: true,
clientAuth: true,
codeSigning: true,
emailProtection: true,
timeStamping: true
}, {
name: 'nsCertType',
client: true,
server: true,
email: true,
objsign: true,
sslCA: true,
emailCA: true,
objCA: true
}, {
name: 'subjectAltName',
altNames: [{
type: 6, // URI
value: 'http://example.org/webid#me'
}, {
type: 7, // IP
ip: '127.0.0.1'
}]
}, {
name: 'subjectKeyIdentifier'
}]);
cert.sign(keys.privateKey);
// convert a Forge certificate to PEM
var pem = pki.certificateToPem(cert);
console.log(pem)
// convert a Forge certificate from PEM
var cert = pki.certificateFromPem(pem);
// convert an ASN.1 X.509x3 object to a Forge certificate
var inAsn1 = pki.certificateToAsn1(cert);
var inDer = asn1.toDer(inAsn1);
var outAsn1 = asn1.fromDer(inDer);
var outCert = pki.certificateFromAsn1(outAsn1);
// convert a Forge certificate to an ASN.1 X.509v3 object
var asn1Cert = pki.certificateToAsn1(outCert);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment