Low-level utilities for elliptic curve operations, number theory functions, and cryptographic helper methods used throughout the elliptic library.
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'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)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);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 valueAssertion 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);
}NAF representation optimizes scalar multiplication by reducing the number of point operations:
Benefits:
Use Cases:
JSF representation optimizes simultaneous scalar multiplication (aP + bQ):
Benefits:
Use Cases:
Lazy evaluation pattern for expensive computations:
Benefits:
Use Cases:
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
];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');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');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');
}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'));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);
}These utilities are available for application developers:
Some utilities are primarily for internal library operations: