Guide Development Guide

Use of X509 certificate in fibjs

Method 1: Use a temporary self-signed certificate

1 2 3
const CYPT = require('crypto'); const SSLX = require('ssl'); const HTTP = require("http");

1. Create a key object and generate a 2048-bit RSA key pair

1 2
let pky = new CYPT.PKey(); pky.genRsaKey(2048);

2. Create a certificate request object, using the public key in pky above

1 2 3 4 5 6 7
let xrq = new CYPT.X509Req("CN=localhost,O=fibjs", pky); /** * CN=localhost 是证书的主题名称, 就是证书的使用者(一般是域名 * 可以加一些扩展内容, 比如 O=IBM,OU=IT,...(用逗号分隔)等项 */

3. To issue a certificate, use the private key in pky

1 2 3 4 5 6 7 8
let opt = { notBefore: new Date('2019-01-01') // 证书生效时间 ,notAfter: new Date('2029-12-31') // 证书失效时间 }; let crt = xrq.sign("CN=myy.mkx", pky, opt); // CN=myy.mkx 是证书的签发者, 同样可添加扩展 // opt 参数参见 fibjs 文档

4. Start the https service with a temporary certificate

1 2 3 4
var svr = new HTTP.HttpsServer(crt, pky, 443, (req)=> { req.response.write('<h1>fibjs https server</h1>'); }); svr.start();

5. The browser visit https://localhost/ test, because it is not an official certificate, the browser will not recognize it, you need to continue to access manually, click the certificate icon in the address bar to view the detailed information of the certificate.


Method 2: Generate and use self-signed certificate file

1. Generate certificate/private key file

1 2 3 4 5 6 7 8 9
const fs = require('fs'); //...(同上面方式一的1、2、3步骤, 省略)... let ks = pky.exportPem(); // 导出私钥文本 let cs = crt.dump(true)[0]; // 导出证书文本, 数组(只有一项) fs.writeTextFile('d:/mycert.key', ks); // 保存私钥 fs.writeTextFile('d:/mycert.pem', cs); // 保存证书

2. Use certificate/private key file

1 2 3 4 5 6 7 8 9 10 11 12 13 14
const CYPT = require('crypto'); const SSLX = require('ssl'); const HTTP = require("http"); let pky = new CYPT.PKey(); let crt = new CYPT.X509Cert(); pky.importFile('d:/mycert.key'); // 读取key文件 crt.loadFile('d:/mycert.pem'); // 读取pem文件 var svr = new HTTP.HttpsServer(crt, pky, 443, (req)=> { req.response.write('<h1>fibjs https server</h1>'); }); svr.start();

Method 3: Use an existing certificate

The above method of loading certificate files can also be used for official certificates, such as

  • 从阿里云申请的免费证书(下载other格式Alibaba从阿里云申请的免费证书(下载other格式, including two files xxx.pem and xxx.key).
  • The certificate obtained through certbot application.

Certificates in other formats may need to be converted, please refer to the fibjs documentation for details.