JavaScript implementations of network transports, cryptography, ciphers, PKI, message digests, and various utilities.
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Implementation of PKCS standards including PKCS#1 (RSA), PKCS#7 (CMS), and PKCS#12 (key stores). Node-forge provides comprehensive support for standard cryptographic data formats used in PKI systems.
PKCS#1 defines RSA encryption and signature schemes with proper padding.
/**
* PKCS#1 padding schemes and operations
*/
forge.pkcs1 = {
/**
* Encode message using PKCS#1 v1.5 padding
* @param m - Message to encode
* @param key - RSA key for size calculation
* @param bt - Block type (0x00, 0x01, 0x02)
* @returns Padded message
*/
encode_rsa_oaep: (key: any, message: string, options?: any) => string;
/**
* Decode PKCS#1 v1.5 padded message
* @param m - Padded message
* @param key - RSA key
* @param pub - True for public key operation
* @returns Original message
*/
decode_rsa_oaep: (key: any, em: string, options?: any) => string;
};Usage Examples:
const forge = require('node-forge');
// RSA-OAEP encryption (handled automatically by RSA encrypt/decrypt)
const keypair = forge.pki.rsa.generateKeyPair(2048);
const message = 'Secret message';
// OAEP padding is applied automatically
const encrypted = keypair.publicKey.encrypt(message, 'RSA-OAEP');
const decrypted = keypair.privateKey.decrypt(encrypted, 'RSA-OAEP');PKCS#7 provides formats for signed, encrypted, and authenticated data.
/**
* Create PKCS#7 signed data structure
* @returns PKCS#7 signed data object
*/
forge.pkcs7.createSignedData(): PKCS7SignedData;
/**
* Create PKCS#7 encrypted data structure
* @returns PKCS#7 encrypted data object
*/
forge.pkcs7.createEncryptedData(): PKCS7EncryptedData;
/**
* Create PKCS#7 enveloped data structure
* @returns PKCS#7 enveloped data object
*/
forge.pkcs7.createEnvelopedData(): PKCS7EnvelopedData;
/**
* Parse PKCS#7 message from PEM format
* @param pem - PEM-encoded PKCS#7 message
* @returns PKCS#7 message object
*/
forge.pkcs7.messageFromPem(pem: string): PKCS7Message;
/**
* Convert PKCS#7 message to PEM format
* @param msg - PKCS#7 message object
* @param maxline - Maximum line length
* @returns PEM-encoded PKCS#7 message
*/
forge.pkcs7.messageToPem(msg: PKCS7Message, maxline?: number): string;
/**
* Parse PKCS#7 message from ASN.1
* @param asn1 - ASN.1 object
* @returns PKCS#7 message object
*/
forge.pkcs7.messageFromAsn1(asn1: ASN1): PKCS7Message;
interface PKCS7SignedData {
/** Content type OID */
type: string;
/** Content to be signed */
content: any;
/** Certificates included in the message */
certificates: Certificate[];
/** Certificate revocation lists */
crls: any[];
/** Signer information */
signers: PKCS7Signer[];
/**
* Add certificate to the signed data
* @param cert - Certificate to add
*/
addCertificate(cert: Certificate | string): void;
/**
* Add signer to the signed data
* @param signer - Signer information
*/
addSigner(signer: PKCS7Signer): void;
/**
* Sign the data
* @param key - Private key for signing
* @param authenticatedAttributes - Additional attributes to sign
*/
sign(key?: PrivateKey, authenticatedAttributes?: any[]): void;
/**
* Verify all signatures
* @param caStore - Certificate store for verification
* @returns True if all signatures are valid
*/
verify(caStore?: CertificateStore): boolean;
}
interface PKCS7Signer {
/** Signer's certificate */
certificate: Certificate;
/** Signature algorithm */
digestAlgorithm: string;
/** Authentication attributes */
authenticatedAttributes: any[];
/** Unauthenticated attributes */
unauthenticatedAttributes: any[];
/** Digital signature */
signature: string;
}Usage Examples:
// Create signed data
const p7 = forge.pkcs7.createSignedData();
// Set content to sign
p7.content = forge.util.createBuffer('Hello, World!', 'utf8');
// Add certificate
p7.addCertificate(signerCert);
// Add signer
p7.addSigner({
key: signerPrivateKey,
certificate: signerCert,
digestAlgorithm: forge.pki.oids.sha256,
authenticatedAttributes: [{
type: forge.pki.oids.contentTypes,
value: forge.pki.oids.data
}, {
type: forge.pki.oids.messageDigest
}, {
type: forge.pki.oids.signingTime,
value: new Date()
}]
});
// Sign the data
p7.sign();
// Convert to PEM
const pem = forge.pkcs7.messageToPem(p7);
// Verify signature
const caStore = forge.pki.createCertificateStore([caCert]);
const verified = p7.verify(caStore);
console.log('Signature verified:', verified);PKCS#12 provides a format for storing private keys and certificates.
/**
* Convert key and certificate to PKCS#12 format
* @param key - Private key
* @param cert - Certificate
* @param password - Protection password
* @param options - Additional options
* @returns PKCS#12 ASN.1 structure
*/
forge.pkcs12.toPkcs12Asn1(
key: PrivateKey,
cert: Certificate,
password: string,
options?: PKCS12Options
): ASN1;
/**
* Convert PKCS#12 ASN.1 to PEM format
* @param asn1 - PKCS#12 ASN.1 structure
* @param maxline - Maximum line length
* @returns PEM-encoded PKCS#12
*/
forge.pkcs12.toPem(asn1: ASN1, maxline?: number): string;
/**
* Parse PKCS#12 from ASN.1
* @param asn1 - PKCS#12 ASN.1 structure
* @param password - Protection password
* @returns PKCS#12 parsed data
*/
forge.pkcs12.pkcs12FromAsn1(asn1: ASN1, password?: string): PKCS12;
/**
* Parse PKCS#12 from DER bytes
* @param bytes - DER-encoded PKCS#12 data
* @param password - Protection password
* @returns PKCS#12 parsed data
*/
forge.pkcs12.pkcs12FromDer(bytes: string, password?: string): PKCS12;
interface PKCS12Options {
/** Encryption algorithm for private key */
algorithm?: string;
/** Key derivation iteration count */
count?: number;
/** Salt length */
saltSize?: number;
/** Use legacy algorithms */
useMac?: boolean;
/** MAC iteration count */
macCount?: number;
/** Friendly name for certificate */
friendlyName?: string;
/** Generate local key ID */
generateLocalKeyId?: boolean;
}
interface PKCS12 {
/** PKCS#12 version */
version: string;
/** Authentication safe bags */
safeContents: SafeBag[];
/** MAC data for integrity */
macData?: any;
/**
* Get certificate from PKCS#12
* @param bagId - Bag identifier
* @returns Certificate or null
*/
getBagsByFriendlyName(name: string, bagType: string): SafeBag[];
/**
* Get private key from PKCS#12
* @param bagId - Bag identifier
* @returns Private key or null
*/
getBagsByLocalKeyId(keyId: string, bagType: string): SafeBag[];
}
interface SafeBag {
/** Bag type */
type: string;
/** Bag attributes */
attributes: any;
/** Bag value (key, certificate, etc.) */
key?: PrivateKey;
cert?: Certificate;
asn1?: ASN1;
}Usage Examples:
// Create PKCS#12 from key and certificate
const p12Asn1 = forge.pkcs12.toPkcs12Asn1(
privateKey,
certificate,
'password123',
{
algorithm: '3des', // or 'aes128', 'aes192', 'aes256'
count: 100000, // PBKDF2 iterations
saltSize: 8, // Salt size in bytes
useMac: true, // Include MAC for integrity
friendlyName: 'My Certificate'
}
);
// Convert to PEM format
const p12Pem = forge.pkcs12.toPem(p12Asn1);
// Save as binary (for .p12/.pfx files)
const p12Der = forge.asn1.toDer(p12Asn1).getBytes();
// Parse PKCS#12 file
const p12 = forge.pkcs12.pkcs12FromAsn1(p12Asn1, 'password123');
// Extract certificates and keys
const certBags = p12.getBagsByFriendlyName('My Certificate', forge.pki.oids.certBag);
const keyBags = p12.getBagsByFriendlyName('My Certificate', forge.pki.oids.pkcs8ShroudedKeyBag);
if (certBags.length > 0) {
const cert = certBags[0].cert;
console.log('Certificate:', cert);
}
if (keyBags.length > 0) {
const key = keyBags[0].key;
console.log('Private key:', key);
}PBKDF2 derives cryptographic keys from passwords with salt and iteration count.
/**
* Derive key using PBKDF2
* @param password - Password string
* @param salt - Salt bytes
* @param iterations - Iteration count
* @param keyLength - Desired key length in bytes
* @param md - Message digest algorithm (default: SHA-1)
* @returns Derived key as binary string
*/
forge.pkcs5.pbkdf2(
password: string,
salt: string | ByteStringBuffer,
iterations: number,
keyLength: number,
md?: MessageDigest | string
): string;Usage Examples:
// Derive encryption key from password
const password = 'user-password';
const salt = forge.random.getBytesSync(16); // 128-bit salt
const iterations = 100000; // OWASP recommended minimum
const keyLength = 32; // 256-bit key
const derivedKey = forge.pkcs5.pbkdf2(password, salt, iterations, keyLength, 'sha256');
// Use derived key for encryption
const cipher = forge.cipher.createCipher('AES-CBC', derivedKey);
const iv = forge.random.getBytesSync(16);
cipher.start({iv: iv});
cipher.update(forge.util.createBuffer('secret data'));
cipher.finish();
const encrypted = cipher.output.getBytes();
// Store salt, iterations, IV, and encrypted data for later decryption
const keyDerivationInfo = {
salt: forge.util.encode64(salt),
iterations: iterations,
algorithm: 'sha256',
keyLength: keyLength
};Password-based encryption schemes for protecting private keys.
/**
* Available PBE algorithms
*/
forge.pbe.algorithms = {
'pbeWithMD2AndDES-CBC': any;
'pbeWithMD5AndDES-CBC': any;
'pbeWithMD2AndRC2-CBC': any;
'pbeWithMD5AndRC2-CBC': any;
'pbeWithSHA1AndDES-CBC': any;
'pbeWithSHA1AndRC2-CBC': any;
'pbeWithSHA1And3-KeyTripleDES-CBC': any;
'pbeWithSHA1And2-KeyTripleDES-CBC': any;
'pbeWithSHA1And128BitRC2-CBC': any;
'pbeWithSHA1And40BitRC2-CBC': any;
};
/**
* Encrypt data using password-based encryption
* @param data - Data to encrypt
* @param password - Password for encryption
* @param algorithm - PBE algorithm
* @param options - Encryption options
* @returns Encrypted data
*/
forge.pbe.encrypt(data: any, password: string, algorithm: string, options?: any): any;
/**
* Decrypt PBE-encrypted data
* @param encryptedData - Encrypted data
* @param password - Password for decryption
* @returns Decrypted data
*/
forge.pbe.decrypt(encryptedData: any, password: string): any;Usage Examples:
// Encrypt private key with password-based encryption
const privateKeyInfo = forge.pki.wrapRsaPrivateKey(privateKey);
const encryptedPrivateKeyInfo = forge.pbe.encrypt(
privateKeyInfo,
'encryption-password',
'pbeWithSHA1And3-KeyTripleDES-CBC'
);
// Decrypt private key
const decryptedPrivateKeyInfo = forge.pbe.decrypt(
encryptedPrivateKeyInfo,
'encryption-password'
);
const restoredPrivateKey = forge.pki.privateKeyFromAsn1(decryptedPrivateKeyInfo);Handle common PKCS operation errors.
try {
// PKCS#7 operations
const p7 = forge.pkcs7.createSignedData();
p7.sign(privateKey);
// PKCS#12 operations
const p12 = forge.pkcs12.toPkcs12Asn1(privateKey, certificate, password);
// PBKDF2 key derivation
const key = forge.pkcs5.pbkdf2(password, salt, iterations, keyLength);
} catch (error) {
// Handle errors:
// - Invalid passwords for PKCS#12
// - Missing certificates or keys
// - Unsupported algorithms
// - Malformed PKCS structures
// - Signature verification failures
// - Key derivation failures
console.error('PKCS operation failed:', error.message);
}