Wiki: Tutorial for generating X.509 certificate

TOP | static wiki | wiki | DOWNLOADS | TUTORIALS | API REFERENCE | DEMOS |

Here is a Node.JS sample code to generate a PEM string of X.509 certificate using getPEM method of Certificate class:

var rs = require("jsrsasign");

// STEP1. generate a key pair
var kp = rs.KEYUTIL.generateKeypair("EC", "secp256r1");
var prv = kp.prvKeyObj;
var pub = kp.pubKeyObj;
var prvpem = rs.KEYUTIL.getPEM(prv, "PKCS8PRV");
var pubpem = rs.KEYUTIL.getPEM(pub, "PKCS8PUB");

// STEP2. specify certificate parameters
var x = new rs.KJUR.asn1.x509.Certificate({
  version: 3,
  serial: {int: 4},
  issuer: {str: "/CN=UserCA"},
  notbefore: "201231235959Z",
  notafter:  "221231235959Z",
  subject: {str: "/CN=User1"},
  sbjpubkey: pub, // can specify public key object or PEM string
  ext: [
    {extname: "basicConstraints", cA: false},
    {extname: "keyUsage", critical: true, names:["digitalSignature"]},
    {extname: "cRLDistributionPoints",
     array: [{fulluri: 'http://example.com/a.crl'}]}
  ],
  sigalg: "SHA256withECDSA",
  cakey: prv // can specify private key object or PEM string
});

// you can modify any fields until the certificate is signed.
x.params.subject = {str: "/CN=User2"};

// STEP3. show PEM strings of keys and a certificate
console.log(prvpem);
console.log(pubpem);
console.log(x.getPEM()); // certificate object is signed automatically with "cakey" value.

As for available extensions specified by "ext" member, you may find the list of extensions in Extensions class API document. You can find another tutorial for extensions(Tutorial for extensions when generating certificate).

If you want to use existing CA private key and subject public key you can modify STEP1 as following:

var pubpem = "...PEM STRING OF PUBLIC KEY...";
var prvpem = "...PEM STRING OF PRIVATE KEY...";

Then specify "sbjpubkey" and "cakey" member value to "pubpem" and "prvpem" respectively.