创建证书,一般就是要生成 key.pem 和 cert.pem 两个文件。

方式1: 使用 openssl

  1. mkdir cert
  2. cd cert
  3. # 1、Generate a Private Key
  4. openssl genrsa -out key.pem
  5. # 2、Create a CSR ( Certificate Signing Request)
  6. openssl req -new -key key.pem -out csr.pem
  7. # 3、Generate the SSL Certificate
  8. openssl x509 -req -days 365 -in csr.pem -signkey key.pem -out cert.pem
  9. # in cert folder, you will have cert.pem and key.pem

在 nodejs 中使用创建的证书:

  1. const express = require('express')
  2. const https = require("https") // https module to create a ssl enabled server
  3. const path = require("path") // path module
  4. const fs = require("fs") //file system module
  5. const app =express()
  6. app.use("/",(req,res,next)=>{
  7. res.send("hello from ssl secured server!!")
  8. })
  9. const options ={
  10. key:fs.readFileSync(path.join(__dirname,'./certs/key.pem')),
  11. cert:fs.readFileSync(path.join(__dirname,'./certs/cert.pem'))
  12. }
  13. const sslserver =https.createServer(options,app)
  14. sslserver.listen(port,()=>{console.log(`Secure Server is listening on port ${port}`)});

然后可以访问:https://localhost:3000
image.png

方式2: 使用 node-forge

  1. const forge = require('node-forge');
  2. const makeNumberPositive = (hexString) => {
  3. let mostSignificativeHexDigitAsInt = parseInt(hexString[0], 16);
  4. if (mostSignificativeHexDigitAsInt < 8) return hexString;
  5. mostSignificativeHexDigitAsInt -= 8
  6. return mostSignificativeHexDigitAsInt.toString() + hexString.substring(1)
  7. }
  8. // Generate a random serial number for the Certificate
  9. const randomSerialNumber = () => {
  10. return makeNumberPositive(forge.util.bytesToHex(forge.random.getBytesSync(20)));
  11. }
  12. // Get the Not Before Date for a Certificate (will be valid from 2 days ago)
  13. const getCertNotBefore = () => {
  14. let twoDaysAgo = new Date(Date.now() - 60*60*24*2*1000);
  15. let year = twoDaysAgo.getFullYear();
  16. let month = (twoDaysAgo.getMonth() + 1).toString().padStart(2, '0');
  17. let day = twoDaysAgo.getDate();
  18. return new Date(`${year}-${month}-${day} 00:00:00Z`);
  19. }
  20. // Get Certificate Expiration Date (Valid for 90 Days)
  21. const getCertNotAfter = (notBefore) => {
  22. let ninetyDaysLater = new Date(notBefore.getTime() + 60*60*24*90*1000);
  23. let year = ninetyDaysLater.getFullYear();
  24. let month = (ninetyDaysLater.getMonth() + 1).toString().padStart(2, '0');
  25. let day = ninetyDaysLater.getDate();
  26. return new Date(`${year}-${month}-${day} 23:59:59Z`);
  27. }
  28. // Get CA Expiration Date (Valid for 100 Years)
  29. const getCANotAfter = (notBefore) => {
  30. let year = notBefore.getFullYear() + 100;
  31. let month = (notBefore.getMonth() + 1).toString().padStart(2, '0');
  32. let day = notBefore.getDate();
  33. return new Date(`${year}-${month}-${day} 23:59:59Z`);
  34. }
  35. const DEFAULT_C = 'Australia';
  36. const DEFAULT_ST = 'Victoria';
  37. const DEFAULT_L = 'Melbourne';
  38. class CertificateGeneration {
  39. static CreateRootCA() {
  40. // Create a new Keypair for the Root CA
  41. const { privateKey, publicKey } = forge.pki.rsa.generateKeyPair(2048);
  42. // Define the attributes for the new Root CA
  43. const attributes = [{
  44. shortName: 'C',
  45. value: DEFAULT_C
  46. }, {
  47. shortName: 'ST',
  48. value: DEFAULT_ST
  49. }, {
  50. shortName: 'L',
  51. value: DEFAULT_L
  52. }, {
  53. shortName: 'CN',
  54. value: 'My Custom Testing RootCA'
  55. }];
  56. const extensions = [{
  57. name: 'basicConstraints',
  58. cA: true
  59. }, {
  60. name: 'keyUsage',
  61. keyCertSign: true,
  62. cRLSign: true
  63. }];
  64. // Create an empty Certificate
  65. const cert = forge.pki.createCertificate();
  66. // Set the Certificate attributes for the new Root CA
  67. cert.publicKey = publicKey;
  68. cert.privateKey = privateKey;
  69. cert.serialNumber = randomSerialNumber();
  70. cert.validity.notBefore = getCertNotBefore();
  71. cert.validity.notAfter = getCANotAfter(cert.validity.notBefore);
  72. cert.setSubject(attributes);
  73. cert.setIssuer(attributes);
  74. cert.setExtensions(extensions);
  75. // Self-sign the Certificate
  76. cert.sign(privateKey, forge.md.sha512.create());
  77. // Convert to PEM format
  78. const pemCert = forge.pki.certificateToPem(cert);
  79. const pemKey = forge.pki.privateKeyToPem(privateKey);
  80. // Return the PEM encoded cert and private key
  81. return { certificate: pemCert, privateKey: pemKey, notBefore: cert.validity.notBefore, notAfter: cert.validity.notAfter };
  82. }
  83. static CreateHostCert(hostCertCN, validDomains, rootCAObject) {
  84. if (!hostCertCN.toString().trim()) throw new Error('"hostCertCN" must be a String');
  85. if (!Array.isArray(validDomains)) throw new Error('"validDomains" must be an Array of Strings');
  86. if (!rootCAObject || !rootCAObject.hasOwnProperty('certificate') || !rootCAObject.hasOwnProperty('privateKey')) throw new Error('"rootCAObject" must be an Object with the properties "certificate" & "privateKey"');
  87. // Convert the Root CA PEM details, to a forge Object
  88. let caCert = forge.pki.certificateFromPem(rootCAObject.certificate);
  89. let caKey = forge.pki.privateKeyFromPem(rootCAObject.privateKey);
  90. // Create a new Keypair for the Host Certificate
  91. const hostKeys = forge.pki.rsa.generateKeyPair(2048);
  92. // Define the attributes/properties for the Host Certificate
  93. const attributes = [{
  94. shortName: 'C',
  95. value: DEFAULT_C
  96. }, {
  97. shortName: 'ST',
  98. value: DEFAULT_ST
  99. }, {
  100. shortName: 'L',
  101. value: DEFAULT_L
  102. }, {
  103. shortName: 'CN',
  104. value: hostCertCN
  105. }];
  106. const extensions = [{
  107. name: 'basicConstraints',
  108. cA: false
  109. }, {
  110. name: 'nsCertType',
  111. server: true
  112. }, {
  113. name: 'subjectKeyIdentifier'
  114. }, {
  115. name: 'authorityKeyIdentifier',
  116. authorityCertIssuer: true,
  117. serialNumber: caCert.serialNumber
  118. }, {
  119. name: 'keyUsage',
  120. digitalSignature: true,
  121. nonRepudiation: true,
  122. keyEncipherment: true
  123. }, {
  124. name: 'extKeyUsage',
  125. serverAuth: true
  126. }, {
  127. name: 'subjectAltName',
  128. altNames: validDomains.map(domain => { return { type: 2, value: domain } })
  129. }];
  130. // Create an empty Certificate
  131. let newHostCert = forge.pki.createCertificate();
  132. // Set the attributes for the new Host Certificate
  133. newHostCert.publicKey = hostKeys.publicKey;
  134. newHostCert.serialNumber = randomSerialNumber();
  135. newHostCert.validity.notBefore = getCertNotBefore();
  136. newHostCert.validity.notAfter = getCertNotAfter(newHostCert.validity.notBefore);
  137. newHostCert.setSubject(attributes);
  138. newHostCert.setIssuer(caCert.subject.attributes);
  139. newHostCert.setExtensions(extensions);
  140. // Sign the new Host Certificate using the CA
  141. newHostCert.sign(caKey, forge.md.sha512.create());
  142. // Convert to PEM format
  143. let pemHostCert = forge.pki.certificateToPem(newHostCert);
  144. let pemHostKey = forge.pki.privateKeyToPem(hostKeys.privateKey);
  145. return { certificate: pemHostCert, privateKey: pemHostKey, notAfter: newHostCert.validity.notBefore, notAfter: newHostCert.validity.notAfter };
  146. }
  147. }
  148. let CA = CertificateGeneration.CreateRootCA();
  149. /* The following certificate:
  150. - Will be called 'testing.com'.
  151. - Will be valid for 'testing.com' and 'test.com'.
  152. - Will be signed by the CA we just created above.
  153. */
  154. let hostCert = CertificateGeneration.CreateHostCert('testing.com', ['testing.com', 'test.com'], CA);
  155. console.log(CA.certificate);
  156. console.log(hostCert.certificate);