Guide Development Guide

Use of X509 certificates in fibjs

Background introduction

What is an x509 certificate

The x509 certificate is the most commonly used digital certificate format in the public key authentication service (PKI) system based on international standards. It can be used for authentication and encryption, and is widely used in SSL/TLS protocols and other types of network applications on the Internet. The x509 certificate uses a public key/private key authentication mechanism and can ensure the confidentiality, integrity and authenticity of data transmission.

In what scenarios is x509 certificate used?

On the Internet, the most commonly used scenario for x509 certificates is for certificate authentication in the TLS/SSL protocol to ensure that the data transmitted between the client and the server is encrypted using a secure channel and is verified. x509 certificates can also be used for identity authentication in application protocols based on public and private key encryption such as VPN/SSH.

fibjs supports x509 certificate processing

fibjs supports the processing of x509 certificates and provides classes such as X509Cert and X509Req in the crypto module to perform operations such as reading, creating, and signing certificates. You can use these classes to obtain the certificate's validity period, public key, issuer, subject name and other information, as well as perform operations such as signing and verifying the certificate. At the same time, fibjs also provides the HttpsServer class to support HTTPS certificate authentication and encrypted connections, making it easier to use x509 certificates in fibjs.

Introduction to X509 module

What is the X509 module?

In the crypto module of fibjs, classes such as X509Cert and X509Req are provided to perform operations such as reading, creating and signing x509 certificates. The X509 module is a module for processing x509 certificates, providing operations such as certificate parsing, creation and verification.

The function of X509 module

The function of the X509 module is to operate the x509 certificate. You can use this module to read the existing x509 certificate and obtain the validity period, public key, issuer, subject name and other information of the certificate. At the same time, the X509 module can also create x509 certificate requests and signing certificates, such as for certificate authentication in TLS/SSL protocols.

X509 module API

The following is a list of the more important APIs in the X509 module:

  • X509Cert: Class for reading and manipulating x509 certificates.
  • X509Req: Class used to create x509 certificate requests.
  • verify: Verify x509 certificate via CA certificate pair.
  • SslServer: A class that provides authentication services based on x509 certificates.
  • SslSocket: A class that provides socket sending and receiving data operations for authentication services based on x509 certificates.

Sample code

The following is sample code to read an x509 certificate and create an x509 certificate request:

1 2 3 4 5 6 7 8 9 10 11 12
const crypto = require('crypto'); // load the cert const cert = crypto.loadCert('server.crt'); console.log(cert.subject); // create x509 certificate request let pky = crypto.PKey.from(private_pem); let req = new crypto.X509Req("CN=localhost,O=fibjs", pky); let derReq = req.der(); let pemReq = req.pem(); console.log(pemReq);

The above sample code reads an existing x509 certificate through the X509Cert class and outputs the subject name of the certificate. At the same time, the sample code also demonstrates how to create an x509 certificate request through X509Req and outputs the request information in PEM format.

Usage of X509 module

Generate self-signed certificate

The process of generating a self-signed certificate is relatively simple. Generally, you need to complete the following steps:

  • Generate PKey (private key)
  • Generate X509Req (certificate request)
  • Use X509Req to generate X509Cert (formal certificate)
  • save certificate

Using these steps, you can generate your own x509 certificate for use in test and development environments. The following is the specific implementation:

Use the following code to create a PKey object. Among them, the from() method can create a PKey object through a PEM format string or a Buffer.

1 2
const crypto = require('crypto'); const pky = crypto.PKey.from(private_pem);

Use the following code to create an X509Req object. Among them, the first parameter of X509Req is the subject distinguished name (Subject Name), and the string format is key1=value1,key2=value2. The second parameter is the PKey object created previously, used for certificate signing. For example:

let xrq = new crypto.X509Req("CN=localhost,O=fibjs", pky);

Use the following code to create an X509Cert (official certificate). The specific operation is to call the sign() method of X509Req, which accepts three parameters: the name of the certificate authority, the PKey object used for signing, and other related information. For example, in the following example, the X509Req object is signed with a self-signed certificate, the signing authority is itself, and the certificate is valid for 10 years:

1 2 3 4 5
const opt = { notBefore: new Date(), notAfter: new Date(new Date().getTime() + 10 * 365 * 24 * 60 * 60 * 1000) }; const cert = xrq.sign("CN=localhost,O=fibjs", pky, opt);

Use the following code to save the PKey and X509Cert to a local file. Since the certificate is saved in PEM format, you can use the pem() method to convert the certificate object into a string and then save it directly to the file:

1 2 3 4 5
const fs = require('fs'); const ks = pky.pem(); // export pem format data of the private key const cs = cert.pem(); // export pem format data of the cert fs.writeFile('mycert.key', ks); // save the key fs.writeFile('mycert.pem', cs); // save the cert

The above code completes the entire process from generating a private key to storing a self-signed certificate. Security-related applications can be tested and developed with this certificate.

Load certificate

Loading the certificate is an important operation when using x509 certificates. The following describes how to load the certificate file and load the public and private keys.

In order to use an x509 certificate, the certificate file must first be read into memory and converted into an x509 certificate object. Here are the steps on how to load the certificate file:

In the fibjs JavaScript program, you can use the relevant API of the fs module to read files. For example, use the following code to read a certificate file in PEM format:

1 2
const fs = require('fs'); const certData = fs.readFile('server.crt');

After reading the file, the certificate file contents must be converted into an x509 certificate using the X509Cert object:

1 2
const crypto = require('crypto'); const cert = new crypto.X509Cert(certData);

After the above steps, you can load the local x509 certificate file. You can also use crypto.loadCert to read the certificate directly:

1 2
const crypto = require('crypto'); const cert = crypto.loadCert('server.crt');

The x509 certificate stores the public key and encrypted signature information. Therefore, when using the certificate, you need to parse the public key in the certificate to facilitate data encryption and decryption. The PKey class can convert public/private key strings in PEM format into public/private key objects. You can use the following code to read the public/private key string in PEM format and create a PKey object:

1 2
const privateKey = fs.readFile('private.pem'); // load the data from file const pKey = crypto.PKey.from(privateKey); // load from pem format data

Or use crypto.loadPKey to read directly:

1 2
const crypto = require('crypto'); const pKey = crypto.loadPKey('private.pem');

After the above steps, the public/private key file can be converted into a PKey object.

Parse certificate

Certificates are an important component of SSL/TLS interactions, used for authentication and encryption of data transmission. Now, let's learn how to parse a certificate in fibjs.

We can use the X509Cert class of the crypto module to construct a certificate object by reading a certificate file in DER/PEM format, and then obtain some basic information about the certificate, such as obtaining the certificate's subject name, issuer name, validity period, etc. .

The sample code is as follows:

1 2 3 4 5 6 7 8 9 10 11 12 13 14
const crypto = require('crypto'); const cert = crypto.loadCert('path/to/cert.pem'); const subjectName = cert.subject; const issuerName = cert.issuer; const validFromDate = cert.notBefore; const expirationDate = cert.notAfter; const serialNumber = cert.serial; console.log(`证书主题名称: ${subjectName}`); console.log(`证书颁发者名称: ${issuerName}`); console.log(`证书有效期: ${validFromDate.toLocaleString()} ~ ${expirationDate.toLocaleString()}`); console.log(`证书序列号: ${serialNumber}`);

When we need to use a certificate, we need to verify the legitimacy of the certificate. The key is to make sure that the certificate is issued by a trusted organization. You can use the verify method in X509Cert to check the validity of the certificate. A common verification method is to verify the certificate chain to ensure that the certificate is issued by a trusted CA.

The sample code is as follows:

1 2 3 4 5 6 7 8 9
const caCert = crypto.loadCert('path/to/ca.crt'); const verifyResult = cert.verify(caCert); if (verifyResult !== 0) { console.error('证书验证失败', verifyResult); } else { console.log('证书验证通过'); }

In this sample code, we first read the specified CA certificate, generate an X509Cert object, and then use the verify method on the certificate object to verify the certificate that needs to be verified, and obtain the verification result. You can determine whether the certificate is legitimate by comparing whether the verification result is equal to 0. If the verification result is not 0, it means the verification failed and the certificate should be stopped using.

Use certificate

When using an https server, you need to ensure that the certificate used has been added to the server. Here is a simple example of loading certificate and private key files via the crypto module:

1 2 3 4 5 6 7 8 9 10
const http = require("http"); const crypto = require("crypto"); const cert = crypto.loadCert("server.crt"); const key = crypto.loadPKey("server.key"); const server = new http.HttpsServer(cert, key, 8443, function(req) { req.response.write(`Hello, fibjs!`); }); server.start();

In the above example, we loaded the server.crt and server.key files through the loadCert and loadPKey functions, then created a service using the HttpsServer object and started the service with the loaded certificate and key files.

Notes on X509 module

Certificate security

The X509 module provides functions such as certificate creation and processing. The security of the certificate must be guaranteed. This requires special attention to the following points:

  • Security of private keys. The private key is an important part of the certificate and must be strictly protected. During the use of certificates, the private key should be stored in a safe place as much as possible, and access permissions should be set appropriately.
  • The transmission of certificates is secure. During the exchange and use of certificates, secure transmission methods must be used to prevent certificates from being stolen or tampered with.
  • Certificate verification is secure. Certificate verification is an important step in ensuring the validity and security of the certificate. Verification must be carried out in strict accordance with the certificate verification rules to avoid forged certificates misleading users.

Certificate validity period

The validity period of a certificate refers to the period from the certificate issuance date to the certificate expiration date. The validity period of the certificate limits the use time of the certificate. Before the certificate expires, the certificate holder can use the certificate, but after the certificate expires, the certificate will lose its validity.

Therefore, before using a certificate, you must check the validity period of the certificate to avoid using an expired certificate. At the same time, the certificate should be updated as soon as possible before it expires to ensure the availability of the certificate.

Certificate trust mechanism

The trust mechanism of the certificate is a key factor in whether the certificate can be trusted by the client or server. Typically, the client or server only trusts certificates signed and recognized by a trusted authority (CA).

Before using a certificate, you must determine the certificate's trust issues. You can determine whether a certificate is trustworthy by checking the issuing authority of the certificate, the subject distinguished name of the certificate, etc.

Certificate renewal mechanism

The certificate renewal mechanism is an important part of ensuring that the certificate remains valid and secure. Normally, certificate renewal mainly includes two aspects:

  • Renewal after certificate expiration. After the certificate expires, you must reapply for the certificate and sign and verify it according to the corresponding rules to ensure the validity of the certificate.
  • Certificate extensions and renewals. During the use of the certificate, if you need to extend or update the certificate information, you can do so by reapplying for the certificate and signing and verifying it.

To sum up, the X509 module provides certificate creation, processing and other functions, and is an important link to ensure the security, trustworthiness and validity of certificates. In the process of using and managing certificates, corresponding rules and requirements must be followed to ensure the validity and security of the certificate.

👉【Add native module