Node.js: how to generate a CSR and a private key

Node.js: how to generate a CSR and a private key

In Node.js, you can generate a CSR (Certificate Signing Request) and RSA private key using the built-in crypto module.

In Node.js, you can generate a CSR (Certificate Signing Request) and RSA private key using the built-in crypto module. The CSR is used to request a Secure Sockets Layer (SSL) certificate from a certificate authority, while the RSA private key is used to encrypt data transmitted over the SSL connection.

The solution is as follows:


'use strict';

const crypto = require('crypto');

const { privateKey } = crypto.generateKeyPairSync('rsa', {
    modulusLength: 2048,
    publicKeyEncoding: {
        type: 'pkcs1',
        format: 'pem'
    },
    privateKeyEncoding: {
        type: 'pkcs1',
        format: 'pem'
    }
});

const csr = crypto.createSign('RSA-SHA256');
const csrInfo = [
    '-----BEGIN CERTIFICATE REQUEST-----\n',
    'CN=example.com\n',
    'O=Example Organization\n', 
    'L=San Francisco\n',
    'ST=California\n',
    'C=US\n',
    '-----END CERTIFICATE REQUEST-----\n'
];
csr.update(csrInfo.join(''));
csr.end();
const csrData = csr.sign(privateKey, 'base64');


An RSA private key with a length of 2048 bits is first generated and encrypted in PEM format. Then a CSR is generated using the RSA-SHA256 signature algorithm. It is important to note that the CSR must contain information about the domain for which the SSL certificate is requested.

It is also very important to note that as an example we are using the synchronous methods for generating the CSR and the private key. In order not to block the Event Loop in the context of an application, one should always use the asynchronous methods of the crypto module.