Skip to content

Tutorial for generating X.509 certificate

Kenji Urushima edited this page Apr 27, 2021 · 10 revisions

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");

// 1. 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");

// 2. 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,
  ext: [
    {extname: "basicConstraints", cA: false},
    {extname: "keyUsage", critical: true, names:["digitalSignature"]},
    {extname: "cRLDistributionPoints",
     array: [{fulluri: 'http://example.com/a.crl'}]}
  ],
  sigalg: "SHA256withECDSA",
  cakey: prv
});

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

// 3. 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.
Clone this wiki locally