Created
April 1, 2024 10:14
-
-
Save felladrin/a922a2f89045f117a9981c1b4b25150c to your computer and use it in GitHub Desktop.
Express HTTPS server running with self signed certificate generated with JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require("fs"); | |
const https = require("https"); | |
const express = require("express"); | |
const forge = require("node-forge"); | |
function generateCert(options) { | |
const keys = forge.pki.rsa.generateKeyPair(2048); | |
const cert = forge.pki.createCertificate(); | |
cert.publicKey = keys.publicKey; | |
cert.serialNumber = "01"; | |
cert.validity.notBefore = new Date(); | |
cert.validity.notAfter = new Date(); | |
cert.validity.notAfter.setFullYear( | |
cert.validity.notBefore.getFullYear() + options.validityDays, | |
); | |
const attrs = [ | |
{ | |
name: "commonName", | |
value: "localhost", | |
}, | |
]; | |
cert.setSubject(attrs); | |
cert.setIssuer(attrs); | |
cert.setExtensions([ | |
{ | |
name: "basicConstraints", | |
cA: true, | |
}, | |
{ | |
name: "keyUsage", | |
keyCertSign: true, | |
digitalSignature: true, | |
nonRepudiation: true, | |
keyEncipherment: true, | |
dataEncipherment: true, | |
}, | |
{ | |
name: "extKeyUsage", | |
serverAuth: true, | |
clientAuth: true, | |
codeSigning: true, | |
emailProtection: true, | |
timeStamping: true, | |
}, | |
{ | |
name: "nsCertType", | |
client: true, | |
server: true, | |
email: true, | |
objsign: true, | |
sslCA: true, | |
emailCA: true, | |
objCA: true, | |
}, | |
{ | |
name: "subjectAltName", | |
altNames: options.altNameIPs.map((ip) => ({ type: 7, ip: ip })), | |
}, | |
]); | |
cert.sign(keys.privateKey, forge.md.sha256.create()); | |
return { | |
privateKey: forge.pki.privateKeyToPem(keys.privateKey), | |
cert: forge.pki.certificateToPem(cert), | |
}; | |
} | |
const cert = generateCert({ | |
altNameIPs: ["127.0.0.1"], | |
validityDays: 1, | |
}); | |
const app = express(); | |
app.get("/", (req, res) => { | |
res.send("Hello, HTTPS World!"); | |
}); | |
const server = https.createServer( | |
{ | |
key: cert.privateKey, | |
cert: cert.cert, | |
}, | |
app, | |
); | |
server.listen(8443, () => { | |
console.log("HTTPS Server started at https://127.0.0.1:8443"); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment