Skip to content

Instantly share code, notes, and snippets.

@kentbrew
Created January 13, 2011 02:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kentbrew/777279 to your computer and use it in GitHub Desktop.
Save kentbrew/777279 to your computer and use it in GitHub Desktop.
How I got SSL working on Node
// works with node-0.2.4, not node-0.3.6; be SURE you got node to build with OpenSSL
//
// you will need working SSL key and cert, otherwise:
// openssl genrsa -out privatekey.pem 1024
// openssl req -new -key privatekey.pem -out certrequest.csr
// openssl x509 -req -in certrequest.csr -signkey privatekey.pem -out certificate.pem
//
// map port 8443 to 443 and 8080 to 80; see gist 776580 to do this on EC2
var http = require('http'), crypto = require('crypto'), fs = require("fs");
var privateKey = fs.readFileSync('path/to/privatekey.pem').toString();
var certificate = fs.readFileSync('path/to/certificate.pem').toString();
var credentials = crypto.createCredentials({key: privateKey, cert: certificate});
var writeReply = function(res, str) {
console.log(str);
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<!doctype html><html><head><title>' + str + '</title></head>');
res.write('<body>' + str + '</body></html>');
res.end();
}
var handleNormal = function(req, res) {
writeReply(res, 'plain old not-so-secure server is working');
};
var normal = http.createServer();
normal.addListener("request", handleNormal);
normal.listen(8080);
var handleSecure = function (req, res) {
writeReply(res, 'awesome secure server is working');
};
var secure = http.createServer();
secure.setSecure(credentials);
secure.addListener("request", handleSecure);
secure.listen(8443);
console.log('running on 8080 and 8443');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment