Node Forge Cryptography and TLS Library

1.4.0 · active · verified Sun Apr 19

Node Forge is a comprehensive JavaScript library providing native implementations of cryptographic tools, network transports (like TLS, HTTP, SSH), and PKI components. It supports a wide array of ciphers (AES, DES), message digests (SHA-1, SHA-256, MD5), and PKI standards (X.509, PKCS# series). The current stable version is 1.4.0, which continues to build on its CommonJS module structure for Node.js and UMD bundles for browser environments. Its key differentiators include its entirely JavaScript-native implementation, which avoids native dependencies, and its extensive feature set for both client-side and server-side cryptographic operations, from generating RSA key pairs to parsing X.509 certificates.

Common errors

Warnings

Install

Imports

Quickstart

Generates an RSA key pair, exports public and private keys in PEM format, and then creates a self-signed X.509 certificate using these keys.

import forge from 'node-forge';

async function generateAndExportRSAKeypair() {
  console.log('Generating RSA key pair...');
  const keys = await new Promise((resolve) => {
    forge.pki.rsa.generateKeyPair({ bits: 2048, workers: -1 }, (err, keypair) => {
      if (err) throw err;
      resolve(keypair);
    });
  });

  const publicKeyPem = forge.pki.publicKeyToPem(keys.publicKey);
  const privateKeyPem = forge.pki.privateKeyToPem(keys.privateKey);

  console.log('\n--- Public Key PEM ---');
  console.log(publicKeyPem);
  console.log('\n--- Private Key PEM ---');
  console.log(privateKeyPem);

  // Example of creating a self-signed certificate
  const cert = forge.pki.createCertificate();
  cert.publicKey = keys.publicKey;
  cert.serialNumber = '01';
  cert.validity.notBefore = new Date();
  cert.validity.notAfter = new Date();
  cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 1);

  const attrs = [
    { name: 'commonName', value: 'example.org' },
    { name: 'countryName', value: 'US' },
    { shortName: 'ST', value: 'Virginia' },
    { name: 'organizationName', value: 'Example' }
  ];
  cert.setSubject(attrs);
  cert.setIssuer(attrs);
  cert.setExtensions([
    { name: 'basicConstraints', cA: true },
    { name: 'keyUsage', digitalSignature: true, keyEncipherment: true, dataEncipherment: true },
    { name: 'extKeyUsage', serverAuth: true, clientAuth: true, codeSigning: true, emailProtection: true },
    { name: 'nsCertType', sslCPS: true, sslBSS: true, emailCA: true },
    { name: 'subjectAltName', altNames: [{ type: 6, value: 'http://example.org/' }, { type: 7, ip: '127.0.0.1' }]},
    { name: 'subjectKeyIdentifier' }
  ]);

  // Sign the certificate with the private key
  cert.sign(keys.privateKey, forge.md.sha256.create());

  const pem = forge.pki.certificateToPem(cert);
  console.log('\n--- Self-Signed Certificate PEM ---');
  console.log(pem);
}

generateAndExportRSAKeypair().catch(console.error);

view raw JSON →