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

asn1.mddocs/

ASN.1 Encoding and Decoding

ASN.1 DER encoding/decoding for working with cryptographic standards and certificate formats. Node-forge provides comprehensive ASN.1 support for parsing and generating binary data structures used in PKI and cryptographic protocols.

Capabilities

ASN.1 Object Creation

Create ASN.1 objects with specified tag class, type, and value.

/**
 * Create an ASN.1 object
 * @param tagClass - ASN.1 tag class (UNIVERSAL, APPLICATION, CONTEXT_SPECIFIC, PRIVATE)
 * @param type - ASN.1 type identifier
 * @param constructed - True if constructed from other ASN.1 objects
 * @param value - Value content (string for primitive types, array for constructed)
 * @param options - Additional options
 * @returns ASN.1 object
 */
forge.asn1.create(
  tagClass: number,
  type: number,
  constructed: boolean,
  value: any,
  options?: ASN1Options
): ASN1;

interface ASN1 {
  /** ASN.1 tag class */
  tagClass: number;
  /** ASN.1 type identifier */
  type: number;
  /** Whether this is a constructed type */
  constructed: boolean;
  /** Value content */
  value: any;
  /** Original encoding (for validation) */
  original?: ASN1;
}

interface ASN1Options {
  /** Validate against original encoding */
  validate?: boolean;
}

Usage Examples:

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

// Create primitive ASN.1 objects
const boolean = forge.asn1.create(
  forge.asn1.Class.UNIVERSAL,
  forge.asn1.Type.BOOLEAN,
  false,
  '\x01' // TRUE
);

const integer = forge.asn1.create(
  forge.asn1.Class.UNIVERSAL,
  forge.asn1.Type.INTEGER,
  false,
  '\x01\x00' // 256 in two's complement
);

const octetString = forge.asn1.create(
  forge.asn1.Class.UNIVERSAL,
  forge.asn1.Type.OCTETSTRING,
  false,
  'Hello World'
);

// Create constructed ASN.1 objects
const sequence = forge.asn1.create(
  forge.asn1.Class.UNIVERSAL,
  forge.asn1.Type.SEQUENCE,
  true,
  [boolean, integer, octetString]
);

ASN.1 Constants

Standard ASN.1 tag classes and types for constructing valid structures.

/**
 * ASN.1 tag classes
 */
forge.asn1.Class = {
  UNIVERSAL: 0x00;        // Standard universal types
  APPLICATION: 0x40;      // Application-specific types
  CONTEXT_SPECIFIC: 0x80; // Context-specific types
  PRIVATE: 0xC0;          // Private types
};

/**
 * ASN.1 universal types
 */
forge.asn1.Type = {
  NONE: 0;
  BOOLEAN: 1;             // Boolean value
  INTEGER: 2;             // Integer value
  BITSTRING: 3;           // Bit string
  OCTETSTRING: 4;         // Octet (byte) string
  NULL: 5;                // Null value
  OID: 6;                 // Object identifier
  ODESC: 7;               // Object descriptor
  EXTERNAL: 8;            // External type
  REAL: 9;                // Real number
  ENUMERATED: 10;         // Enumerated value
  EMBEDDED_PDV: 11;       // Embedded PDV
  UTF8: 12;               // UTF-8 string
  SEQUENCE: 16;           // Sequence (ordered collection)
  SET: 17;                // Set (unordered collection)
  PRINTABLESTRING: 19;    // Printable string
  T61STRING: 20;          // T61 string
  VIDEOTEXSTRING: 21;     // Videotex string
  IA5STRING: 22;          // IA5 string
  UTCTIME: 23;            // UTC time
  GENERALIZEDTIME: 24;    // Generalized time
  GRAPHICSTRING: 25;      // Graphic string
  VISIBLESTRING: 26;      // Visible string
  GENERALSTRING: 27;      // General string
  UNIVERSALSTRING: 28;    // Universal string
  BMPSTRING: 30;          // BMP string
};

DER Encoding and Decoding

Convert between ASN.1 objects and DER (Distinguished Encoding Rules) binary format.

/**
 * Parse ASN.1 object from DER encoding
 * @param bytes - DER-encoded bytes as string or ByteStringBuffer
 * @param strict - Strict parsing mode (default: true)
 * @returns Parsed ASN.1 object
 */
forge.asn1.fromDer(bytes: string | ByteStringBuffer, strict?: boolean): ASN1;

/**
 * Encode ASN.1 object to DER format
 * @param asn1Object - ASN.1 object to encode
 * @returns DER-encoded bytes as ByteStringBuffer
 */
forge.asn1.toDer(asn1Object: ASN1): ByteStringBuffer;

Usage Examples:

// Create ASN.1 structure and encode to DER
const sequence = forge.asn1.create(
  forge.asn1.Class.UNIVERSAL,
  forge.asn1.Type.SEQUENCE,
  true,
  [
    forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.INTEGER, false, '\x01'),
    forge.asn1.create(forge.asn1.Class.UNIVERSAL, forge.asn1.Type.OCTETSTRING, false, 'test')
  ]
);

// Encode to DER
const derBytes = forge.asn1.toDer(sequence);
console.log('DER bytes:', derBytes.toHex());

// Parse from DER
const parsed = forge.asn1.fromDer(derBytes);
console.log('Parsed ASN.1:', parsed);

// Access parsed values
console.log('First element (integer):', parsed.value[0].value);
console.log('Second element (string):', parsed.value[1].value);

ASN.1 Object Operations

Utility functions for working with ASN.1 objects.

/**
 * Copy an ASN.1 object
 * @param asn1Object - ASN.1 object to copy
 * @param options - Copy options
 * @returns Deep copy of ASN.1 object
 */
forge.asn1.copy(asn1Object: ASN1, options?: any): ASN1;

/**
 * Compare two ASN.1 objects for equality
 * @param obj1 - First ASN.1 object
 * @param obj2 - Second ASN.1 object
 * @returns True if objects are equal
 */
forge.asn1.equals(obj1: ASN1, obj2: ASN1): boolean;

/**
 * Get length of ASN.1 object when encoded
 * @param asn1Object - ASN.1 object
 * @returns Length in bytes
 */
forge.asn1.getBerValueLength(asn1Object: ASN1): number;

Usage Examples:

// Copy ASN.1 object
const original = forge.asn1.create(
  forge.asn1.Class.UNIVERSAL,
  forge.asn1.Type.INTEGER,
  false,
  '\x01\x00'
);
const copy = forge.asn1.copy(original);

// Compare objects
const isEqual = forge.asn1.equals(original, copy);
console.log('Objects equal:', isEqual); // true

// Get encoded length
const length = forge.asn1.getBerValueLength(original);
console.log('Encoded length:', length);

Object Identifier (OID) Support

Handle Object Identifiers for algorithm and attribute identification.

/**
 * Convert OID string to DER encoding
 * @param oid - OID string (e.g., "1.2.840.113549.1.1.1")
 * @returns DER-encoded OID as ByteStringBuffer
 */
forge.asn1.oidToDer(oid: string): ByteStringBuffer;

/**
 * Convert DER-encoded OID to string
 * @param bytes - DER-encoded OID bytes
 * @returns OID string
 */
forge.asn1.derToOid(bytes: string | ByteStringBuffer): string;

/**
 * Validate OID string format
 * @param oid - OID string to validate
 * @returns True if valid OID format
 */
forge.asn1.validateOid(oid: string): boolean;

Usage Examples:

// Work with Object Identifiers
const rsaOid = '1.2.840.113549.1.1.1'; // RSA encryption OID
const derOid = forge.asn1.oidToDer(rsaOid);
console.log('DER-encoded OID:', derOid.toHex());

// Convert back to string
const oidString = forge.asn1.derToOid(derOid);
console.log('OID string:', oidString); // "1.2.840.113549.1.1.1"

// Create OID ASN.1 object
const oidAsn1 = forge.asn1.create(
  forge.asn1.Class.UNIVERSAL,
  forge.asn1.Type.OID,
  false,
  derOid.getBytes()
);

Date and Time Handling

Convert between JavaScript Date objects and ASN.1 time representations.

/**
 * Convert UTC time to JavaScript Date
 * @param utc - ASN.1 UTC time string (YYMMDDHHMMSSZ format)
 * @returns JavaScript Date object
 */
forge.asn1.utcTimeToDate(utc: string): Date;

/**
 * Convert generalized time to JavaScript Date
 * @param gentime - ASN.1 generalized time string (YYYYMMDDHHMMSSZ format)
 * @returns JavaScript Date object
 */
forge.asn1.generalizedTimeToDate(gentime: string): Date;

/**
 * Convert JavaScript Date to UTC time string
 * @param date - JavaScript Date object
 * @returns ASN.1 UTC time string
 */
forge.asn1.dateToUtcTime(date: Date): string;

/**
 * Convert JavaScript Date to generalized time string
 * @param date - JavaScript Date object
 * @returns ASN.1 generalized time string
 */
forge.asn1.dateToGeneralizedTime(date: Date): string;

Usage Examples:

// Work with ASN.1 time types
const now = new Date();

// Create UTC time (valid until 2049)
const utcTime = forge.asn1.dateToUtcTime(now);
const utcAsn1 = forge.asn1.create(
  forge.asn1.Class.UNIVERSAL,
  forge.asn1.Type.UTCTIME,
  false,
  utcTime
);

// Create generalized time (valid beyond 2049)
const genTime = forge.asn1.dateToGeneralizedTime(now);
const genAsn1 = forge.asn1.create(
  forge.asn1.Class.UNIVERSAL,
  forge.asn1.Type.GENERALIZEDTIME,
  false,
  genTime
);

// Parse time values back to Date
const parsedUtc = forge.asn1.utcTimeToDate(utcTime);
const parsedGen = forge.asn1.generalizedTimeToDate(genTime);
console.log('Parsed UTC time:', parsedUtc);
console.log('Parsed generalized time:', parsedGen);

Advanced ASN.1 Structures

Build complex ASN.1 structures commonly used in cryptographic applications.

Usage Examples:

// Create X.509 certificate validity structure
function createValidity(notBefore, notAfter) {
  return forge.asn1.create(
    forge.asn1.Class.UNIVERSAL,
    forge.asn1.Type.SEQUENCE,
    true,
    [
      forge.asn1.create(
        forge.asn1.Class.UNIVERSAL,
        forge.asn1.Type.UTCTIME,
        false,
        forge.asn1.dateToUtcTime(notBefore)
      ),
      forge.asn1.create(
        forge.asn1.Class.UNIVERSAL,
        forge.asn1.Type.UTCTIME,
        false,
        forge.asn1.dateToUtcTime(notAfter)
      )
    ]
  );
}

// Create algorithm identifier structure
function createAlgorithmIdentifier(oid, parameters = null) {
  const sequence = [
    forge.asn1.create(
      forge.asn1.Class.UNIVERSAL,
      forge.asn1.Type.OID,
      false,
      forge.asn1.oidToDer(oid).getBytes()
    )
  ];
  
  if (parameters !== null) {
    sequence.push(parameters);
  } else {
    sequence.push(
      forge.asn1.create(
        forge.asn1.Class.UNIVERSAL,
        forge.asn1.Type.NULL,
        false,
        ''
      )
    );
  }
  
  return forge.asn1.create(
    forge.asn1.Class.UNIVERSAL,
    forge.asn1.Type.SEQUENCE,
    true,
    sequence
  );
}

// Use the structures
const validity = createValidity(new Date(), new Date(Date.now() + 365*24*60*60*1000));
const rsaAlgId = createAlgorithmIdentifier('1.2.840.113549.1.1.1'); // RSA

Error Handling

Handle common ASN.1 parsing and encoding errors.

try {
  // Parse potentially malformed DER data
  const asn1Obj = forge.asn1.fromDer(derBytes, true); // strict mode
  
  // Encode ASN.1 object
  const encoded = forge.asn1.toDer(asn1Obj);
  
  // Validate OID
  const oid = '1.2.840.113549.1.1.1';
  if (!forge.asn1.validateOid(oid)) {
    throw new Error('Invalid OID format');
  }
  
} catch (error) {
  // Handle errors:
  // - Malformed DER encoding
  // - Invalid ASN.1 structure
  // - Unsupported ASN.1 types
  // - Invalid OID format
  // - Date/time conversion errors
  // - Length encoding errors
  console.error('ASN.1 operation failed:', error.message);
}

Performance Considerations

Optimize ASN.1 operations for better performance.

Usage Examples:

// Efficient parsing of large ASN.1 structures
function parseSequenceElements(seq) {
  const elements = [];
  if (seq.constructed && seq.value) {
    for (let i = 0; i < seq.value.length; i++) {
      elements.push(seq.value[i]);
    }
  }
  return elements;
}

// Reuse OID encodings for better performance
const commonOids = {
  RSA: forge.asn1.oidToDer('1.2.840.113549.1.1.1'),
  SHA256: forge.asn1.oidToDer('2.16.840.1.101.3.4.2.1'),
  MD5: forge.asn1.oidToDer('1.2.840.113549.2.5')
};

// Use cached OID encodings
function createRsaAlgorithmId() {
  return forge.asn1.create(
    forge.asn1.Class.UNIVERSAL,
    forge.asn1.Type.SEQUENCE,
    true,
    [
      forge.asn1.create(
        forge.asn1.Class.UNIVERSAL,
        forge.asn1.Type.OID,
        false,
        commonOids.RSA.getBytes()
      ),
      forge.asn1.create(
        forge.asn1.Class.UNIVERSAL,
        forge.asn1.Type.NULL,
        false,
        ''
      )
    ]
  );
}

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