Win10使用OpenSSL生成证书的详细步骤(NodeJS Https服务器源码) ...

打印 上一主题 下一主题

主题 892|帖子 892|积分 2676

长途开启硬件权限,会用到SSL证书。
以下是Win10系统下用OpenSSL生成测试用证书的步骤。
Step 1. 下载OpenSSL,一般选择64位的MSI
Win32/Win64 OpenSSL Installer for Windows - Shining Light Productions    
一起点下来,假如后续请你捐款,可以不选择。
win10下很大概的安装路径为: C:\Program Files\OpenSSL-Win64
Step 2. 将 C:\Program Files\OpenSSL-Win64\bin这个路径添加到系统环境变量中。
Step 3. 新建一个目次,例如我的: D:\dev\openssl\
新建一个文件夹是防止系统环境下有读写权限限制问题。
Step 4. 在这个目次下新建一个 openssl.cnf 文件生存为utf-8格式。
文件内容为:
  1. #
  2. # OpenSSL configuration file.
  3. #
  4. # Establish working directory.
  5. dir                         = .
  6. [ ca ]
  7. default_ca                  = CA_default
  8. [ CA_default ]
  9. serial                      = $dir/serial
  10. database                    = $dir/certindex.txt
  11. new_certs_dir               = $dir/certs
  12. certificate                 = $dir/cacert.pem
  13. private_key                 = $dir/private/cakey.pem
  14. default_days                = 365
  15. default_md                  = md5
  16. preserve                    = no
  17. email_in_dn                 = no
  18. nameopt                     = default_ca
  19. certopt                     = default_ca
  20. policy                      = policy_match
  21. [ policy_match ]
  22. countryName                 = match
  23. stateOrProvinceName         = match
  24. organizationName            = match
  25. organizationalUnitName      = optional
  26. commonName                  = supplied
  27. emailAddress                = optional
  28. [ req ]
  29. default_bits                = 1024          # Size of keys
  30. default_keyfile             = key.pem       # name of generated keys
  31. default_md                  = md5               # message digest algorithm
  32. string_mask                 = nombstr       # permitted characters
  33. distinguished_name          = req_distinguished_name
  34. req_extensions              = v3_req
  35. [ req_distinguished_name ]
  36. # Variable name             Prompt string
  37. #-------------------------    ----------------------------------
  38. 0.organizationName          = Organization Name (company)
  39. organizationalUnitName      = Organizational Unit Name (department, division)
  40. emailAddress                = Email Address
  41. emailAddress_max            = 40
  42. localityName                = Locality Name (city, district)
  43. stateOrProvinceName         = State or Province Name (full name)
  44. countryName                 = Country Name (2 letter code)
  45. countryName_min             = 2
  46. countryName_max             = 2
  47. commonName                  = Common Name (hostname, IP, or your name)
  48. commonName_max              = 64
  49. # Default values for the above, for consistency and less typing.
  50. # Variable name             Value
  51. #------------------------     ------------------------------
  52. 0.organizationName_default  = My Company
  53. localityName_default        = My Town
  54. stateOrProvinceName_default = State or Providence
  55. countryName_default         = US
  56. [ v3_ca ]
  57. basicConstraints            = CA:TRUE
  58. subjectKeyIdentifier        = hash
  59. authorityKeyIdentifier      = keyid:always,issuer:always
  60. [ v3_req ]
  61. basicConstraints            = CA:FALSE
  62. subjectKeyIdentifier        = hash
复制代码
感谢: Unable to load config info from /usr/local/ssl/openssl.cnf on Windows - Stack Overflow
Step 5. 在新建的D:\dev\openssl\文件夹下,打开cmd窗口,设置openssl.cnf路径环境变量,下令如下:
  1. set OPENSSL_CONF=D:\dev\openssl\openssl.cnf
复制代码
假如没有正确指定这个环境变量,则会报如下错误:
Unable to load config info from /z/extlib/_openssl_/ssl/openssl.cnf
Step 6. 在下令行中创建privateKey.pem
  1. openssl.exe genrsa -out privateKey.pem 4096
复制代码
执行成功,打印如下:
  1. Generating RSA private key, 4096 bit long modulus
  2. ..............................................................................................................................................++
  3. ............................................................................++
  4. e is 65537 (0x10001)
复制代码
感谢: openssl - Unable to load Private Key. (PEM routinesEM_read_bio:no start line:pem_lib.c:648:Expecting: ANY PRIVATE KEY) - Stack Overflow
Step7. 生成证书,下令如下:
  1. openssl.exe req -new -x509 -nodes -days 3600 -key privateKey.pem -out caKey.pem
复制代码
会提示你输入构造名称,email地址,接洽地址、所属国家等信息,正常输入就ok了。
假如没有正确生成 privateKey.pem或者找不到这个文件,则会报错:
req: Can't open "privateKey.key" for writing, Permission denied
Step 8. 恭喜,搞定。

Step 9. 在用NodeJS写一个简单的https Server试试。代码如下:
  1. // server.js
  2. const https = require('https');
  3. const fs = require('fs');
  4. const options = {
  5.   key: fs.readFileSync('privateKey.pem'),
  6.   cert: fs.readFileSync('caKey.pem')
  7. };
  8. const app = function (req, res) {
  9.   res.writeHead(200);
  10.   res.end("hello world\n");
  11. }
  12. https.createServer(options, app).listen(9000);
复制代码
Step 10. 在欣赏器中输入 https://localhost:9000/就能访问。假如是chrome欣赏器,会提示这是不安全链接,必要你在当前页面里点击高级,然后选择继承访问。成功访问的话,会在页面中表现:
hello world
Step 11. 再来一个功能更丰富的Sever。
  1. const https = require('https');
  2. const fs = require('fs');
  3. const path = require('path');
  4. const options = {
  5.   key: fs.readFileSync('privateKey.pem'),
  6.   cert: fs.readFileSync('./caKey.pem')
  7. };
  8. var serverPort = 9100;
  9. https.createServer(options, (req, res) => {
  10.   const filePath = '.' + req.url;
  11.   const extname = path.extname(filePath);
  12.   let contentType = 'text/html';
  13.   switch (extname) {
  14.     case '.js':
  15.       contentType = 'text/javascript';
  16.       break;
  17.     case '.css':
  18.       contentType = 'text/css';
  19.       break;
  20.     case '.json':
  21.       contentType = 'application/json';
  22.       break;
  23.     case '.png':
  24.       contentType = 'image/png';
  25.       break;
  26.     case '.jpg':
  27.       contentType = 'image/jpg';
  28.       break;
  29.     case '.wav':
  30.       contentType = 'audio/wav';
  31.       break;
  32.   }
  33.   fs.readFile(filePath, (error, content) => {
  34.     if (error) {
  35.       if (error.code == 'ENOENT') {
  36.         fs.readFile('./404.html', (error, content) => {
  37.           res.writeHead(200, { 'Content-Type': contentType });
  38.           res.end(content, 'utf-8');
  39.         });
  40.       } else {
  41.         res.writeHead(500);
  42.         res.end('Sorry, check with the site admin for error: ' + error.code + ' ..\n');
  43.         res.end();
  44.       }
  45.     } else {
  46.       res.writeHead(200, { 'Content-Type': contentType });
  47.       res.end(content, 'utf-8');
  48.     }
  49.   });
  50. }).listen(serverPort);
  51. console.log(`Server running at https://127.0.0.1:${serverPort}/`);
复制代码


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

钜形不锈钢水箱

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表