index.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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 = new Date();
  49. cert.validity.notAfter = new Date();
  50. cert.validity.notAfter.setDate(cert.validity.notBefore.getDate() + (options.days || 365));
  51. attrs = attrs || [{
  52. name: 'commonName',
  53. value: 'example.org'
  54. }, {
  55. name: 'countryName',
  56. value: 'US'
  57. }, {
  58. shortName: 'ST',
  59. value: 'Virginia'
  60. }, {
  61. name: 'localityName',
  62. value: 'Blacksburg'
  63. }, {
  64. name: 'organizationName',
  65. value: 'Test'
  66. }, {
  67. shortName: 'OU',
  68. value: 'Test'
  69. }];
  70. cert.setSubject(attrs);
  71. cert.setIssuer(attrs);
  72. cert.publicKey = keyPair.publicKey;
  73. cert.setExtensions(options.extensions || [{
  74. name: 'basicConstraints',
  75. cA: true
  76. }, {
  77. name: 'keyUsage',
  78. keyCertSign: true,
  79. digitalSignature: true,
  80. nonRepudiation: true,
  81. keyEncipherment: true,
  82. dataEncipherment: true
  83. }, {
  84. name: 'subjectAltName',
  85. altNames: [{
  86. type: 6, // URI
  87. value: 'http://example.org/webid#me'
  88. }]
  89. }]);
  90. cert.sign(keyPair.privateKey, getAlgorithm(options && options.algorithm));
  91. const fingerprint = forge.md.sha1
  92. .create()
  93. .update(forge.asn1.toDer(forge.pki.certificateToAsn1(cert)).getBytes())
  94. .digest()
  95. .toHex()
  96. .match(/.{2}/g)
  97. .join(':');
  98. var pem = {
  99. private: forge.pki.privateKeyToPem(keyPair.privateKey),
  100. public: forge.pki.publicKeyToPem(keyPair.publicKey),
  101. cert: forge.pki.certificateToPem(cert),
  102. fingerprint: fingerprint,
  103. };
  104. if (options && options.pkcs7) {
  105. var p7 = forge.pkcs7.createSignedData();
  106. p7.addCertificate(cert);
  107. pem.pkcs7 = forge.pkcs7.messageToPem(p7);
  108. }
  109. if (options && options.clientCertificate) {
  110. var clientkeys = forge.pki.rsa.generateKeyPair(1024);
  111. var clientcert = forge.pki.createCertificate();
  112. clientcert.serialNumber = toPositiveHex(forge.util.bytesToHex(forge.random.getBytesSync(9)));
  113. clientcert.validity.notBefore = new Date();
  114. clientcert.validity.notAfter = new Date();
  115. clientcert.validity.notAfter.setFullYear(clientcert.validity.notBefore.getFullYear() + 1);
  116. var clientAttrs = JSON.parse(JSON.stringify(attrs));
  117. for(var i = 0; i < clientAttrs.length; i++) {
  118. if(clientAttrs[i].name === 'commonName') {
  119. if( options.clientCertificateCN )
  120. clientAttrs[i] = { name: 'commonName', value: options.clientCertificateCN };
  121. else
  122. clientAttrs[i] = { name: 'commonName', value: 'John Doe jdoe123' };
  123. }
  124. }
  125. clientcert.setSubject(clientAttrs);
  126. // Set the issuer to the parent key
  127. clientcert.setIssuer(attrs);
  128. clientcert.publicKey = clientkeys.publicKey;
  129. // Sign client cert with root cert
  130. clientcert.sign(keyPair.privateKey);
  131. pem.clientprivate = forge.pki.privateKeyToPem(clientkeys.privateKey);
  132. pem.clientpublic = forge.pki.publicKeyToPem(clientkeys.publicKey);
  133. pem.clientcert = forge.pki.certificateToPem(clientcert);
  134. if (options.pkcs7) {
  135. var clientp7 = forge.pkcs7.createSignedData();
  136. clientp7.addCertificate(clientcert);
  137. pem.clientpkcs7 = forge.pkcs7.messageToPem(clientp7);
  138. }
  139. }
  140. var caStore = forge.pki.createCaStore();
  141. caStore.addCertificate(cert);
  142. try {
  143. forge.pki.verifyCertificateChain(caStore, [cert],
  144. function (vfd, depth, chain) {
  145. if (vfd !== true) {
  146. throw new Error('Certificate could not be verified.');
  147. }
  148. return true;
  149. });
  150. }
  151. catch(ex) {
  152. throw new Error(ex);
  153. }
  154. return pem;
  155. };
  156. var keySize = options.keySize || 1024;
  157. if (done) { // async scenario
  158. return forge.pki.rsa.generateKeyPair({ bits: keySize }, function (err, keyPair) {
  159. if (err) { return done(err); }
  160. try {
  161. return done(null, generatePem(keyPair));
  162. } catch (ex) {
  163. return done(ex);
  164. }
  165. });
  166. }
  167. var keyPair = options.keyPair ? {
  168. privateKey: forge.pki.privateKeyFromPem(options.keyPair.privateKey),
  169. publicKey: forge.pki.publicKeyFromPem(options.keyPair.publicKey)
  170. } : forge.pki.rsa.generateKeyPair(keySize);
  171. return generatePem(keyPair);
  172. };