index.js 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. var forge = require('node-forge');
  2. // a hexString is considered negative if it's most significant bit is 1
  3. // because serial numbers use ones' complement notation
  4. // this RFC in section 4.1.2.2 requires serial numbers to be positive
  5. // http://www.ietf.org/rfc/rfc5280.txt
  6. function toPositiveHex(hexString){
  7. var mostSiginficativeHexAsInt = parseInt(hexString[0], 16);
  8. if (mostSiginficativeHexAsInt < 8){
  9. return hexString;
  10. }
  11. mostSiginficativeHexAsInt -= 8;
  12. return mostSiginficativeHexAsInt.toString() + hexString.substring(1);
  13. }
  14. function getAlgorithm(key) {
  15. switch (key) {
  16. case 'sha256':
  17. return forge.md.sha256.create();
  18. default:
  19. return forge.md.sha1.create();
  20. }
  21. }
  22. /**
  23. *
  24. * @param {forge.pki.CertificateField[]} attrs Attributes used for subject and issuer.
  25. * @param {object} options
  26. * @param {number} [options.days=365] the number of days before expiration
  27. * @param {number} [options.keySize=1024] the size for the private key in bits
  28. * @param {object} [options.extensions] additional extensions for the certificate
  29. * @param {string} [options.algorithm="sha1"] The signature algorithm sha256 or sha1
  30. * @param {boolean} [options.pkcs7=false] include PKCS#7 as part of the output
  31. * @param {boolean} [options.clientCertificate=false] generate client cert signed by the original key
  32. * @param {string} [options.clientCertificateCN="John Doe jdoe123"] client certificate's common name
  33. * @param {function} [done] Optional callback, if not provided the generation is synchronous
  34. * @returns
  35. */
  36. exports.generate = function generate(attrs, options, done) {
  37. if (typeof attrs === 'function') {
  38. done = attrs;
  39. attrs = undefined;
  40. } else if (typeof options === 'function') {
  41. done = options;
  42. options = {};
  43. }
  44. options = options || {};
  45. var generatePem = function (keyPair) {
  46. var cert = forge.pki.createCertificate();
  47. cert.serialNumber = toPositiveHex(forge.util.bytesToHex(forge.random.getBytesSync(9))); // the serial number can be decimal or hex (if preceded by 0x)
  48. cert.validity.notBefore = options.notBeforeDate || new Date();
  49. var notAfter = new Date();
  50. cert.validity.notAfter = notAfter;
  51. cert.validity.notAfter.setDate(notAfter.getDate() + (options.days || 365));
  52. attrs = attrs || [{
  53. name: 'commonName',
  54. value: 'example.org'
  55. }, {
  56. name: 'countryName',
  57. value: 'US'
  58. }, {
  59. shortName: 'ST',
  60. value: 'Virginia'
  61. }, {
  62. name: 'localityName',
  63. value: 'Blacksburg'
  64. }, {
  65. name: 'organizationName',
  66. value: 'Test'
  67. }, {
  68. shortName: 'OU',
  69. value: 'Test'
  70. }];
  71. cert.setSubject(attrs);
  72. cert.setIssuer(attrs);
  73. cert.publicKey = keyPair.publicKey;
  74. cert.setExtensions(options.extensions || [{
  75. name: 'basicConstraints',
  76. cA: true
  77. }, {
  78. name: 'keyUsage',
  79. keyCertSign: true,
  80. digitalSignature: true,
  81. nonRepudiation: true,
  82. keyEncipherment: true,
  83. dataEncipherment: true
  84. }, {
  85. name: 'subjectAltName',
  86. altNames: [{
  87. type: 6, // URI
  88. value: 'http://example.org/webid#me'
  89. }]
  90. }]);
  91. cert.sign(keyPair.privateKey, getAlgorithm(options && options.algorithm));
  92. const fingerprint = forge.md.sha1
  93. .create()
  94. .update(forge.asn1.toDer(forge.pki.certificateToAsn1(cert)).getBytes())
  95. .digest()
  96. .toHex()
  97. .match(/.{2}/g)
  98. .join(':');
  99. var pem = {
  100. private: forge.pki.privateKeyToPem(keyPair.privateKey),
  101. public: forge.pki.publicKeyToPem(keyPair.publicKey),
  102. cert: forge.pki.certificateToPem(cert),
  103. fingerprint: fingerprint,
  104. };
  105. if (options && options.pkcs7) {
  106. var p7 = forge.pkcs7.createSignedData();
  107. p7.addCertificate(cert);
  108. pem.pkcs7 = forge.pkcs7.messageToPem(p7);
  109. }
  110. if (options && options.clientCertificate) {
  111. var clientkeys = forge.pki.rsa.generateKeyPair(options.clientCertificateKeySize || 1024);
  112. var clientcert = forge.pki.createCertificate();
  113. clientcert.serialNumber = toPositiveHex(forge.util.bytesToHex(forge.random.getBytesSync(9)));
  114. clientcert.validity.notBefore = new Date();
  115. clientcert.validity.notAfter = new Date();
  116. clientcert.validity.notAfter.setFullYear(clientcert.validity.notBefore.getFullYear() + 1);
  117. var clientAttrs = JSON.parse(JSON.stringify(attrs));
  118. for(var i = 0; i < clientAttrs.length; i++) {
  119. if(clientAttrs[i].name === 'commonName') {
  120. if( options.clientCertificateCN )
  121. clientAttrs[i] = { name: 'commonName', value: options.clientCertificateCN };
  122. else
  123. clientAttrs[i] = { name: 'commonName', value: 'John Doe jdoe123' };
  124. }
  125. }
  126. clientcert.setSubject(clientAttrs);
  127. // Set the issuer to the parent key
  128. clientcert.setIssuer(attrs);
  129. clientcert.publicKey = clientkeys.publicKey;
  130. // Sign client cert with root cert
  131. clientcert.sign(keyPair.privateKey);
  132. pem.clientprivate = forge.pki.privateKeyToPem(clientkeys.privateKey);
  133. pem.clientpublic = forge.pki.publicKeyToPem(clientkeys.publicKey);
  134. pem.clientcert = forge.pki.certificateToPem(clientcert);
  135. if (options.pkcs7) {
  136. var clientp7 = forge.pkcs7.createSignedData();
  137. clientp7.addCertificate(clientcert);
  138. pem.clientpkcs7 = forge.pkcs7.messageToPem(clientp7);
  139. }
  140. }
  141. var caStore = forge.pki.createCaStore();
  142. caStore.addCertificate(cert);
  143. try {
  144. forge.pki.verifyCertificateChain(caStore, [cert],
  145. function (vfd, depth, chain) {
  146. if (vfd !== true) {
  147. throw new Error('Certificate could not be verified.');
  148. }
  149. return true;
  150. });
  151. }
  152. catch(ex) {
  153. throw new Error(ex);
  154. }
  155. return pem;
  156. };
  157. var keySize = options.keySize || 1024;
  158. if (done) { // async scenario
  159. return forge.pki.rsa.generateKeyPair({ bits: keySize }, function (err, keyPair) {
  160. if (err) { return done(err); }
  161. try {
  162. return done(null, generatePem(keyPair));
  163. } catch (ex) {
  164. return done(ex);
  165. }
  166. });
  167. }
  168. var keyPair = options.keyPair ? {
  169. privateKey: forge.pki.privateKeyFromPem(options.keyPair.privateKey),
  170. publicKey: forge.pki.publicKeyFromPem(options.keyPair.publicKey)
  171. } : forge.pki.rsa.generateKeyPair(keySize);
  172. return generatePem(keyPair);
  173. };