or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

curves.mdecdsa.mdeddsa.mdindex.mdutils.md
tile.json

utils.mddocs/

Utilities

Low-level utilities for elliptic curve operations, number theory functions, and cryptographic helper methods used throughout the elliptic library.

Capabilities

Data Conversion Utilities

Functions for converting between different data formats and encodings.

const utils = require('elliptic').utils;

/**
 * Convert data to array format
 * @param data - Input data (string, array, or buffer)
 * @param enc - Input encoding ('hex', 'base64', etc.)
 * @returns Array of bytes
 */
utils.toArray(data, enc);

/**
 * Encode data with specified encoding
 * @param data - Input data array
 * @param enc - Output encoding ('hex', 'base64', etc.)
 * @returns Encoded string or array
 */
utils.encode(data, enc);

/**
 * Zero-pad number to 2 digits
 * @param num - Number to pad
 * @returns Zero-padded string
 */
utils.zero2(num);

/**
 * Convert data to hex string
 * @param data - Input data
 * @returns Hex string representation
 */
utils.toHex(data);

Usage Examples:

const utils = require('elliptic').utils;

// Convert hex string to byte array
const bytes = utils.toArray('deadbeef', 'hex');
console.log(bytes); // [222, 173, 190, 239]

// Convert array back to hex
const hex = utils.encode(bytes, 'hex');
console.log(hex); // 'deadbeef'

// Zero padding
console.log(utils.zero2(5)); // '05'
console.log(utils.zero2(15)); // '15'

Byte Processing Utilities

Functions for parsing and processing byte data.

/**
 * Parse bytes from string or array
 * @param bytes - Input bytes (string or array)
 * @returns Parsed byte array
 */
utils.parseBytes(bytes);

/**
 * Create BN from little-endian bytes
 * @param bytes - Little-endian byte array
 * @returns BN instance
 */
utils.intFromLE(bytes);

Usage Examples:

const utils = require('elliptic').utils;

// Parse different byte formats
const bytes1 = utils.parseBytes('deadbeef'); // From hex string
const bytes2 = utils.parseBytes([0xde, 0xad, 0xbe, 0xef]); // From array

// Convert little-endian bytes to big number
const leBytes = [0xef, 0xbe, 0xad, 0xde]; // Little-endian representation
const bn = utils.intFromLE(leBytes);
console.log(bn.toString(16)); // 'deadbeef' (big-endian)

Number Theory Utilities

Advanced mathematical functions for elliptic curve operations.

/**
 * Get Non-Adjacent Form (NAF) representation
 * @param num - Number to convert
 * @param w - Window size
 * @param bits - Bit length
 * @returns NAF representation array
 */
utils.getNAF(num, w, bits);

/**
 * Get Joint Sparse Form (JSF) representation
 * @param k1 - First scalar
 * @param k2 - Second scalar  
 * @returns JSF representation for simultaneous multiplication
 */
utils.getJSF(k1, k2);

Usage Examples:

const utils = require('elliptic').utils;
const BN = require('bn.js');

// Get NAF representation for scalar multiplication optimization
const scalar = new BN('123456789abcdef', 16);
const naf = utils.getNAF(scalar, 4, 64);
console.log('NAF representation:', naf);

// Get JSF for simultaneous scalar multiplication
const k1 = new BN('12345', 16);
const k2 = new BN('abcde', 16);
const jsf = utils.getJSF(k1, k2);
console.log('JSF representation:', jsf);

Object Utilities

Helper functions for object and property management.

/**
 * Create cached property on object prototype
 * @param obj - Object constructor
 * @param name - Property name
 * @param computer - Function to compute property value
 */
utils.cachedProperty(obj, name, computer);

Usage Examples:

const utils = require('elliptic').utils;

// Create cached property (internal usage pattern)
function MyClass() {
  this._value = null;
}

utils.cachedProperty(MyClass, 'expensiveValue', function() {
  // This computation only runs once, result is cached
  console.log('Computing expensive value...');
  return Math.random() * 1000;
});

const instance = new MyClass();
console.log(instance.expensiveValue()); // Computes and caches
console.log(instance.expensiveValue()); // Returns cached value

Assertion Utilities

Assertion functions for parameter validation and error checking.

/**
 * Assert condition with error message
 * @param condition - Condition to check
 * @param message - Error message if condition fails
 */
utils.assert(condition, message);

Usage Examples:

const utils = require('elliptic').utils;

// Parameter validation
function processKey(key) {
  utils.assert(key, 'Key is required');
  utils.assert(typeof key === 'string', 'Key must be a string');
  utils.assert(key.length > 0, 'Key cannot be empty');
  
  // Process key...
}

try {
  processKey(''); // Throws: Key cannot be empty
} catch (error) {
  console.error(error.message);
}

Advanced Utilities

NAF (Non-Adjacent Form)

NAF representation optimizes scalar multiplication by reducing the number of point operations:

Benefits:

  • Reduces average Hamming weight
  • Fewer point additions in scalar multiplication
  • Performance optimization for ECC operations

Use Cases:

  • Internal optimization in point multiplication
  • Precomputation strategies
  • Side-channel attack mitigation

JSF (Joint Sparse Form)

JSF representation optimizes simultaneous scalar multiplication (aP + bQ):

Benefits:

  • Reduces total number of point operations
  • More efficient than separate multiplications
  • Used in signature verification algorithms

Use Cases:

  • ECDSA signature verification
  • Multi-scalar multiplication
  • Performance-critical ECC operations

Cached Properties

Lazy evaluation pattern for expensive computations:

Benefits:

  • Compute values only when needed
  • Cache results for repeated access
  • Memory and performance optimization

Use Cases:

  • Key derivation caching
  • Point precomputation
  • Expensive mathematical operations

Encoding Formats

Supported Encodings

The utility functions support various encoding formats:

const supportedEncodings = [
  'hex',      // Hexadecimal string
  'base64',   // Base64 string
  'utf8',     // UTF-8 string
  'binary',   // Binary string
  // Additional encodings depending on environment
];

Encoding Examples

const utils = require('elliptic').utils;

const data = [0xde, 0xad, 0xbe, 0xef];

// Different encoding outputs
console.log(utils.encode(data, 'hex'));     // 'deadbeef'
console.log(utils.encode(data, 'base64'));  // '3q2+7w=='

// Reverse conversion
const hexBytes = utils.toArray('deadbeef', 'hex');
const b64Bytes = utils.toArray('3q2+7w==', 'base64');

Integration with External Libraries

BN.js Integration

Elliptic utilities work seamlessly with BN.js big number library:

const BN = require('bn.js');
const utils = require('elliptic').utils;

// Create BN from hex
const bn = new BN('deadbeef', 16);

// Convert to different formats
const array = bn.toArray();
const hex = bn.toString(16);

// Use with elliptic utils
const parsed = utils.parseBytes(hex);
const encoded = utils.encode(array, 'hex');

Buffer Compatibility

Node.js Buffer instances work directly with utility functions:

const utils = require('elliptic').utils;

// Node.js Buffer support
if (typeof Buffer !== 'undefined') {
  const buffer = Buffer.from('deadbeef', 'hex');
  const array = utils.toArray(buffer);
  const hex = utils.encode(array, 'hex');
}

Performance Considerations

Optimization Tips

  1. Reuse converted data: Cache array/hex conversions when possible
  2. Batch operations: Convert multiple values together when feasible
  3. Choose appropriate encodings: Hex is faster than base64 for most operations
  4. Leverage caching: Use cached properties for expensive computations

Memory Management

const utils = require('elliptic').utils;

// Efficient: reuse arrays
const data = utils.toArray('longHexString', 'hex');
const result1 = processData(data);
const result2 = processMoreData(data);

// Less efficient: repeated conversions
const result3 = processData(utils.toArray('longHexString', 'hex'));
const result4 = processMoreData(utils.toArray('longHexString', 'hex'));

Error Handling

Common Error Scenarios

const utils = require('elliptic').utils;

try {
  // Invalid hex string
  utils.toArray('invalid_hex', 'hex'); // May throw
} catch (error) {
  console.error('Invalid hex format:', error.message);
}

try {
  // Invalid encoding
  utils.encode([1, 2, 3], 'invalid_encoding'); // May throw
} catch (error) {
  console.error('Unsupported encoding:', error.message);
}

// Safe usage with validation
function safeConvert(data, encoding) {
  utils.assert(typeof data === 'string', 'Data must be string');
  utils.assert(typeof encoding === 'string', 'Encoding must be string');
  
  return utils.toArray(data, encoding);
}

Best Practices

  1. Validate inputs: Use assertions for parameter checking
  2. Handle encoding errors: Wrap conversions in try-catch blocks
  3. Check data lengths: Verify expected byte lengths for keys/signatures
  4. Use type checks: Ensure data types match expected formats

Internal vs External Usage

External Usage

These utilities are available for application developers:

  • Data format conversions
  • Byte array processing
  • Hex/base64 encoding operations
  • Input validation with assertions

Internal Usage

Some utilities are primarily for internal library operations:

  • NAF/JSF computations (advanced optimization)
  • Cached property creation (performance optimization)
  • Low-level number theory functions