1.下载安装openssl(用于生成秘钥颁发证书)
mac自带
2.生成CA证书,CA钥和CA公钥
生成CA私钥,并用des3算法进行加密:openssl genrsa -des3 -out ca-pri-key.pem 1024
生成CA公钥:openssl req -new -key ca-pri-key.pem -out ca-pub-key.pem
生成CA证书:openssl x509 -req -in ca-pub-key.pem -signkey ca-pri-key.pem -out ca-cert.crt
3.生成服务器公钥私钥
生成服服务私钥:openssl genrsa -out server-key.pem 1024
生成服务器公钥:openssl req -new -key server-key.pem -out server-scr.pem
4.机构颁发证书
openssl x509 -req -CA ca-cert.crt -CAkey ca-pri-key.pem -CAcreateserial -in server-scr.pem -out server-cert.crt
5.https配置
const http = require("https");
const url = require("url");
const path = require("path");
const fs = require("fs");
/**
* 返回文件状态
* @param {*} filename
* @returns
*/
async function getStat(filename) {
try {
return await fs.promises.stat(filename);
} catch {
return null;
}
}
/**
* 得到要处理的文件内容
*/
async function getFileContent(url1) {
const urlObj = url.parse(url1);
let filename; //要处理的文件路径
filename = path.resolve(__dirname, "public", urlObj.pathname.substr(1));//得到请求文件路径
let stat = await getStat(filename); //得到文件状态
if (!stat) {
//文件不存在
return null;
} else if (stat.isDirectory()) {
//文件是一个目录
filename = path.resolve(
__dirname,
"public",
urlObj.pathname.substr(1),
"index.html"
);
stat = await getStat(filename); //重新获取index.html文件状态
if (!stat) {
return null;
} else {
return await fs.promises.readFile(filename); //返回文件
}
} else {
return await fs.promises.readFile(filename); //不是目录返回文件
}
}
const server = http.createServer({
key:fs.readFileSync(path.resolve(__dirname,"./server-key.pem")),
cert:fs.readFileSync(path.resolve(__dirname,"./server-cert.crt"))
},async (req, reps) => {
const url = req.url;
const content = await getFileContent(url);
if (content) {
reps.write(content);
}else{
reps.statusCode = 404;
reps.write("Not Found");
}
reps.end();
})
server.listen(443);
server.on("listening", () => {
console.log("监听端口443");
})