CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-node-forge

JavaScript implementations of network transports, cryptography, ciphers, PKI, message digests, and various utilities.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

asymmetric-cryptography.mddocs/

Asymmetric Cryptography

RSA and Ed25519 implementations for key generation, encryption/decryption, and digital signatures. Node-forge provides comprehensive asymmetric cryptography support with both pure JavaScript implementations and native optimizations where available.

Capabilities

RSA Key Generation

Generate RSA key pairs for encryption and digital signatures.

/**
 * Generate an RSA key pair
 * @param bits - Key size in bits (recommended: 2048, 3072, or 4096)
 * @param e - Public exponent (default: 0x10001 = 65537)
 * @param options - Generation options
 * @param callback - Optional callback for async generation
 * @returns Key pair object or void if callback provided
 */
forge.pki.rsa.generateKeyPair(
  bits: number, 
  e?: number, 
  options?: KeyGenerationOptions, 
  callback?: (err: Error | null, keypair: KeyPair) => void
): KeyPair | void;

interface KeyPair {
  /** RSA private key for decryption and signing */
  privateKey: PrivateKey;
  /** RSA public key for encryption and verification */
  publicKey: PublicKey;
}

interface KeyGenerationOptions {
  /** Custom PRNG for key generation */
  prng?: any;
  /** Prime generation algorithm (default: 'PRIMEINC') */
  algorithm?: string;
  /** Number of workers for async generation */
  workers?: number;
  /** Work load size per worker */
  workLoad?: number;
}

Usage Examples:

const forge = require('node-forge');

// Synchronous key generation
const keypair = forge.pki.rsa.generateKeyPair(2048);
console.log('Generated key pair:', keypair);

// Asynchronous key generation (recommended for larger keys)
forge.pki.rsa.generateKeyPair(4096, 0x10001, (err, keypair) => {
  if (err) {
    console.error('Key generation failed:', err);
    return;
  }
  console.log('Generated key pair async:', keypair);
});

// Custom options
const customKeypair = forge.pki.rsa.generateKeyPair(2048, 0x10001, {
  algorithm: 'PRIMEINC',
  prng: forge.random.createInstance()
});

RSA Public Key Operations

Encrypt data and verify signatures using RSA public keys.

interface PublicKey {
  /** RSA modulus (n) */
  n: any;
  /** Public exponent (e) */
  e: any;
  
  /**
   * Encrypt data using RSA public key
   * @param data - Binary data to encrypt
   * @param scheme - Padding scheme ('RSAES-PKCS1-V1_5', 'RSA-OAEP')
   * @param schemeOptions - Options for padding scheme
   * @returns Encrypted data as binary string
   */
  encrypt(data: string, scheme?: string, schemeOptions?: any): string;
  
  /**
   * Verify a signature using RSA public key
   * @param digest - Message digest that was signed
   * @param signature - Signature to verify as binary string
   * @param scheme - Signature scheme ('RSASSA-PSS', 'RSASSA-PKCS1-V1_5')
   * @returns True if signature is valid
   */
  verify(digest: string, signature: string, scheme?: string): boolean;
}

Usage Examples:

// Encrypt data with public key
const message = 'Hello, World!';
const encrypted = keypair.publicKey.encrypt(message, 'RSAES-PKCS1-V1_5');

// RSA-OAEP encryption with custom options
const oaepEncrypted = keypair.publicKey.encrypt(message, 'RSA-OAEP', {
  md: forge.md.sha256.create(),
  mgf1: {
    md: forge.md.sha256.create()
  }
});

// Verify signature
const md = forge.md.sha256.create();
md.update(message);
const signature = keypair.privateKey.sign(md);
const isValid = keypair.publicKey.verify(md.digest().getBytes(), signature);

RSA Private Key Operations

Decrypt data and create signatures using RSA private keys.

interface PrivateKey {
  /** RSA modulus (n) */
  n: any;
  /** Public exponent (e) */
  e: any;
  /** Private exponent (d) */
  d: any;
  /** Prime factor p */
  p?: any;
  /** Prime factor q */
  q?: any;
  /** d mod (p-1) */
  dP?: any;
  /** d mod (q-1) */
  dQ?: any;
  /** q^(-1) mod p */
  qInv?: any;
  
  /**
   * Decrypt data using RSA private key
   * @param data - Encrypted data as binary string
   * @param scheme - Padding scheme ('RSAES-PKCS1-V1_5', 'RSA-OAEP')
   * @param schemeOptions - Options for padding scheme
   * @returns Decrypted data as binary string
   */
  decrypt(data: string, scheme?: string, schemeOptions?: any): string;
  
  /**
   * Sign a message digest using RSA private key
   * @param messageDigest - Message digest object to sign
   * @param scheme - Signature scheme ('RSASSA-PSS', 'RSASSA-PKCS1-V1_5')
   * @returns Signature as binary string
   */
  sign(messageDigest: MessageDigest, scheme?: string): string;
}

Usage Examples:

// Decrypt data with private key
const decrypted = keypair.privateKey.decrypt(encrypted, 'RSAES-PKCS1-V1_5');
console.log('Decrypted:', decrypted); // "Hello, World!"

// RSA-OAEP decryption
const oaepDecrypted = keypair.privateKey.decrypt(oaepEncrypted, 'RSA-OAEP', {
  md: forge.md.sha256.create(),
  mgf1: {
    md: forge.md.sha256.create()
  }
});

// Sign message digest
const md = forge.md.sha256.create();
md.update('Message to sign');
const signature = keypair.privateKey.sign(md, 'RSASSA-PKCS1-V1_5');

// PSS signing
const pssSignature = keypair.privateKey.sign(md, 'RSASSA-PSS', {
  md: forge.md.sha256.create(),
  mgf: forge.mgf.mgf1.create(forge.md.sha256.create()),
  saltLength: 32
});

RSA Key Creation

Create RSA keys from existing parameters or convert between formats.

/**
 * Create RSA public key from modulus and exponent
 * @param n - Modulus as BigInteger or hex string
 * @param e - Public exponent as BigInteger or hex string
 * @returns RSA public key object
 */
forge.pki.rsa.setPublicKey(n: any, e: any): PublicKey;

/**
 * Create RSA private key from parameters
 * @param n - Modulus
 * @param e - Public exponent
 * @param d - Private exponent
 * @param p - Prime factor p (optional)
 * @param q - Prime factor q (optional) 
 * @param dP - d mod (p-1) (optional)
 * @param dQ - d mod (q-1) (optional)
 * @param qInv - q^(-1) mod p (optional)
 * @returns RSA private key object
 */
forge.pki.rsa.setPrivateKey(
  n: any, e: any, d: any, 
  p?: any, q?: any, dP?: any, dQ?: any, qInv?: any
): PrivateKey;

Usage Examples:

// Create public key from hex strings
const publicKey = forge.pki.rsa.setPublicKey(
  '00c4e3f7ba46b13d...', // modulus in hex
  '010001'              // exponent (65537) in hex
);

// Create private key with all parameters
const privateKey = forge.pki.rsa.setPrivateKey(
  n, e, d, p, q, dP, dQ, qInv
);

Ed25519 Digital Signatures

Ed25519 elliptic curve digital signatures for high-performance authentication.

/**
 * Generate Ed25519 key pair
 * @param options - Generation options
 * @returns Ed25519 key pair
 */
forge.pki.ed25519.generateKeyPair(options?: any): Ed25519KeyPair;

interface Ed25519KeyPair {
  /** Ed25519 private key */
  privateKey: Ed25519PrivateKey;
  /** Ed25519 public key */
  publicKey: Ed25519PublicKey;
}

interface Ed25519PrivateKey {
  /** Sign message with Ed25519 private key */
  sign(message: string | Uint8Array): Uint8Array;
}

interface Ed25519PublicKey {
  /** Verify Ed25519 signature */
  verify(message: string | Uint8Array, signature: Uint8Array): boolean;
}

Usage Examples:

// Generate Ed25519 key pair
const ed25519Keypair = forge.pki.ed25519.generateKeyPair();

// Sign message
const message = 'Message to sign';
const signature = ed25519Keypair.privateKey.sign(message);

// Verify signature
const isValid = ed25519Keypair.publicKey.verify(message, signature);
console.log('Ed25519 signature valid:', isValid);

Padding Schemes

RSA padding schemes for secure encryption and signatures.

// RSA Encryption Schemes
'RSAES-PKCS1-V1_5'  // PKCS#1 v1.5 padding (legacy)
'RSA-OAEP'          // Optimal Asymmetric Encryption Padding (recommended)

// RSA Signature Schemes  
'RSASSA-PKCS1-V1_5' // PKCS#1 v1.5 signatures (widely compatible)
'RSASSA-PSS'        // Probabilistic Signature Scheme (recommended)

interface RSAOAEPOptions {
  /** Message digest for OAEP (default: SHA-1) */
  md?: MessageDigest;
  /** MGF1 options */
  mgf1?: {
    md?: MessageDigest;
  };
  /** Optional label */
  label?: string;
}

interface RSAPSSOptions {
  /** Message digest for PSS */
  md?: MessageDigest;
  /** Mask generation function */
  mgf?: any;
  /** Salt length in bytes */
  saltLength?: number;
}

Usage Examples:

// RSA-OAEP encryption with SHA-256
const oaepOptions = {
  md: forge.md.sha256.create(),
  mgf1: {
    md: forge.md.sha256.create()
  }
};
const encrypted = publicKey.encrypt(message, 'RSA-OAEP', oaepOptions);

// PSS signing with custom parameters
const pssOptions = {
  md: forge.md.sha256.create(),
  mgf: forge.mgf.mgf1.create(forge.md.sha256.create()),
  saltLength: 32
};
const signature = privateKey.sign(messageDigest, 'RSASSA-PSS', pssOptions);

Key Size and Security

Recommended key sizes and security considerations.

// RSA Key Sizes (bits)
RSA_2048_BITS = 2048;  // Minimum recommended (equivalent to 112-bit security)
RSA_3072_BITS = 3072;  // Medium security (equivalent to 128-bit security)  
RSA_4096_BITS = 4096;  // High security (equivalent to 150+ bit security)

// Public Exponents
RSA_EXPONENT_3 = 3;           // Small exponent (faster verification)
RSA_EXPONENT_65537 = 0x10001; // Common exponent (recommended)

Security Recommendations:

// Recommended secure key generation
const secureKeypair = forge.pki.rsa.generateKeyPair(2048, 0x10001);

// Use RSA-OAEP for encryption (not PKCS#1 v1.5)
const encrypted = publicKey.encrypt(data, 'RSA-OAEP');

// Use PSS for signatures when possible
const signature = privateKey.sign(digest, 'RSASSA-PSS');

// Always use secure hash functions (SHA-256 or better)
const md = forge.md.sha256.create();
md.update(message);
const signature = privateKey.sign(md);

Error Handling

Common error conditions in asymmetric cryptography operations.

try {
  // Key generation
  const keypair = forge.pki.rsa.generateKeyPair(2048);
  
  // Encryption
  const encrypted = keypair.publicKey.encrypt(message, 'RSA-OAEP');
  
  // Decryption  
  const decrypted = keypair.privateKey.decrypt(encrypted, 'RSA-OAEP');
  
} catch (error) {
  // Handle errors:
  // - Key generation failures (insufficient randomness, invalid parameters)
  // - Encryption failures (message too long, invalid padding)
  // - Decryption failures (invalid ciphertext, padding errors)
  // - Signature verification failures (invalid signature, wrong key)
  // - Unsupported schemes or algorithms
  console.error('RSA operation failed:', error.message);
}

docs

asn1.md

asymmetric-cryptography.md

index.md

logging.md

message-digests.md

network-http.md

pkcs.md

pki.md

random.md

symmetric-encryption.md

tls.md

utilities.md

web-forms.md

tile.json