{"id":11421,"library":"node-forge","title":"Node Forge Cryptography and TLS Library","description":"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.","status":"active","version":"1.4.0","language":"javascript","source_language":"en","source_url":"https://github.com/digitalbazaar/forge","tags":["javascript","aes","asn","asn.1","cbc","crypto","cryptography","csr","des"],"install":[{"cmd":"npm install node-forge","lang":"bash","label":"npm"},{"cmd":"yarn add node-forge","lang":"bash","label":"yarn"},{"cmd":"pnpm add node-forge","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Node Forge is primarily a CommonJS module. While `import forge from 'node-forge'` works via default interop in ESM contexts, direct named imports like `import { pki } from 'node-forge'` are not supported. In browser environments, a global `forge` object is exposed when using the UMD bundles.","wrong":"import { forge } from 'node-forge';","symbol":"forge","correct":"import forge from 'node-forge';\n// or for CommonJS:\nconst forge = require('node-forge');"},{"note":"Sub-modules like `pki` (Public Key Infrastructure) are properties of the main `forge` object and must be accessed after importing the main library. They are not top-level exports.","wrong":"import { pki } from 'node-forge';","symbol":"pki","correct":"import forge from 'node-forge';\nconst pki = forge.pki;"},{"note":"Message digest algorithms are accessed via the `forge.md` object. Individual algorithm instances are created using `.create()` on the specific algorithm function (e.g., `forge.md.sha256`). Direct imports from internal paths are discouraged and not guaranteed to be stable.","wrong":"import { sha256 } from 'node-forge/lib/sha256';","symbol":"md.sha256","correct":"import forge from 'node-forge';\nconst sha256 = forge.md.sha256.create();"}],"quickstart":{"code":"import forge from 'node-forge';\n\nasync function generateAndExportRSAKeypair() {\n  console.log('Generating RSA key pair...');\n  const keys = await new Promise((resolve) => {\n    forge.pki.rsa.generateKeyPair({ bits: 2048, workers: -1 }, (err, keypair) => {\n      if (err) throw err;\n      resolve(keypair);\n    });\n  });\n\n  const publicKeyPem = forge.pki.publicKeyToPem(keys.publicKey);\n  const privateKeyPem = forge.pki.privateKeyToPem(keys.privateKey);\n\n  console.log('\\n--- Public Key PEM ---');\n  console.log(publicKeyPem);\n  console.log('\\n--- Private Key PEM ---');\n  console.log(privateKeyPem);\n\n  // Example of creating a self-signed certificate\n  const cert = forge.pki.createCertificate();\n  cert.publicKey = keys.publicKey;\n  cert.serialNumber = '01';\n  cert.validity.notBefore = new Date();\n  cert.validity.notAfter = new Date();\n  cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 1);\n\n  const attrs = [\n    { name: 'commonName', value: 'example.org' },\n    { name: 'countryName', value: 'US' },\n    { shortName: 'ST', value: 'Virginia' },\n    { name: 'organizationName', value: 'Example' }\n  ];\n  cert.setSubject(attrs);\n  cert.setIssuer(attrs);\n  cert.setExtensions([\n    { name: 'basicConstraints', cA: true },\n    { name: 'keyUsage', digitalSignature: true, keyEncipherment: true, dataEncipherment: true },\n    { name: 'extKeyUsage', serverAuth: true, clientAuth: true, codeSigning: true, emailProtection: true },\n    { name: 'nsCertType', sslCPS: true, sslBSS: true, emailCA: true },\n    { name: 'subjectAltName', altNames: [{ type: 6, value: 'http://example.org/' }, { type: 7, ip: '127.0.0.1' }]},\n    { name: 'subjectKeyIdentifier' }\n  ]);\n\n  // Sign the certificate with the private key\n  cert.sign(keys.privateKey, forge.md.sha256.create());\n\n  const pem = forge.pki.certificateToPem(cert);\n  console.log('\\n--- Self-Signed Certificate PEM ---');\n  console.log(pem);\n}\n\ngenerateAndExportRSAKeypair().catch(console.error);\n","lang":"typescript","description":"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."},"warnings":[{"fix":"Upgrade to `node-forge@^1.0.0` and update `require`/`import` statements to access modules via the main `forge` object. Review the 1.x API documentation for specific changes.","message":"Node Forge transitioned from a monolithic 0.6.x branch with standalone files to a CommonJS module structure in 1.x. The 0.6.x branch is no longer regularly updated or maintained, and new projects should use the 1.x series. Code written for 0.6.x will require import and API adjustments.","severity":"breaking","affected_versions":"<1.0.0"},{"fix":"Read the 'Security Considerations' in the official documentation. Use strong, cryptographically secure random number generators (CSPRNGs) provided by the library. Consult security experts for sensitive applications.","message":"As a cryptographic library, it is critical to consult and thoroughly understand the 'Security Considerations' section of the documentation. Misuse of cryptographic primitives can lead to severe security vulnerabilities. Always use recommended best practices and ensure randomness sources are truly secure.","severity":"gotcha","affected_versions":">=0.6.0"},{"fix":"Always use `import forge from 'node-forge';` for ESM, and then access sub-modules (e.g., `forge.pki`, `forge.util`) as properties of the `forge` object. For CommonJS, use `const forge = require('node-forge');`.","message":"Node Forge uses a CommonJS module structure for Node.js. When used in an ESM context (`'type': 'module'` or `.mjs` files), it typically requires `import forge from 'node-forge';` (default import interop). Direct named imports are not available, which can be a common source of confusion for modern JavaScript developers.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Be aware of the global `forge` object in browser environments. If integrating into a larger application, consider wrapping the script or using a module loader if possible to isolate the scope, or rename the global variable if the build process allows.","message":"When using Node Forge in web browsers via CDN or bundled files, it synchronously creates a global `forge` object. This can potentially conflict with other scripts or lead to unintended global pollution if not managed carefully.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure `forge` is correctly imported as a default export (`import forge from 'node-forge';`) or required (`const forge = require('node-forge');`). Submodules are then accessed via `forge.pki`.","cause":"Attempting to access a submodule (like `pki`) before the main `forge` object has been correctly imported or initialized.","error":"TypeError: Cannot read properties of undefined (reading 'pki')"},{"fix":"For browsers, use the UMD bundles via a `<script>` tag (e.g., `<script src=\"https://cdn.jsdelivr.net/npm/node-forge@1.0.0/dist/forge.min.js\"></script>`). For ESM Node.js, use `import forge from 'node-forge';`.","cause":"Attempting to use `require('node-forge')` in a browser environment without a module bundler like Webpack or Rollup, or in an ESM-only Node.js context without proper configuration.","error":"ReferenceError: require is not defined"},{"fix":"Ensure you are calling `.create()` on the *algorithm factory* itself, e.g., `forge.md.sha256.create()`. Also verify the algorithm name is correct and supported.","cause":"Incorrectly calling `create()` on the message digest object, or trying to use a method that doesn't exist on the specific digest.","error":"TypeError: forge.md.sha256.create is not a function"}],"ecosystem":"npm"}