### Install and Setup Elliptic.js Source: https://github.com/indutny/elliptic/blob/master/_autodocs/usage-guide.md Import the elliptic library for use in Node.js or browser environments. Access main components like EC, EdDSA, and curves. ```javascript var elliptic = require('elliptic'); // Access main components var EC = elliptic.ec; var EdDSA = elliptic.eddsa; var curves = elliptic.curves; ``` -------------------------------- ### Install Elliptic.js Source: https://github.com/indutny/elliptic/blob/master/_autodocs/00-START-HERE.md Install the elliptic package using npm. This is the first step before using the library. ```bash npm install elliptic ``` -------------------------------- ### Montgomery Reduction Context Source: https://github.com/indutny/elliptic/blob/master/_autodocs/types.md Demonstrates the setup and usage of Montgomery reduction context from bn.js for fast modular arithmetic. Ensure bn.js is installed and imported. ```javascript var BN = require('bn.js'); var p = new BN('fff...', 16); var red = BN.mont(p); // Montgomery reduction var x = new BN(5).toRed(red); var y = x.redAdd(new BN(3).toRed(red)); ``` -------------------------------- ### Complete EdDSA Example Workflow Source: https://github.com/indutny/elliptic/blob/master/_autodocs/api-reference-eddsa.md A comprehensive example demonstrating the full EdDSA workflow: key pair generation, signing a message, serializing the public key and signature, and verifying the signature using the public key. ```javascript var EdDSA = require('elliptic').eddsa; var eddsa = new EdDSA('ed25519'); // Alice's key pair var aliceSecret = '693e3c9e7a5c4d3b2a1f0e9d8c7b6a59...'; // 64 hex chars var alice = eddsa.keyFromSecret(aliceSecret); // Sign a message var message = 'Hello, Bob!'; var msgArray = Buffer.from(message); var signature = alice.sign(msgArray); // Serialize for transmission var alicePubHex = alice.getPublic('hex'); var sigHex = signature.toHex(); // --- Network transmission --- // Bob verifies using Alice's public key var bob = eddsa.keyFromPublic(alicePubHex); var isValid = bob.verify(msgArray, sigHex); if (isValid) { console.log('Message verified!'); } else { console.log('Invalid signature'); } ``` -------------------------------- ### Point Usage Example Source: https://github.com/indutny/elliptic/blob/master/_autodocs/types.md Demonstrates how to generate a key pair, retrieve the public point, and perform basic operations like checking point equality and encoding the point in hex format. This example uses the secp256k1 curve. ```javascript var EC = require('elliptic').ec; var ec = new EC('secp256k1'); var key = ec.genKeyPair(); var point = key.getPublic(); // Point instance console.log(point.getX().toString(16)); console.log(point.getY().toString(16)); // Check if two points are equal var point2 = ec.g.mul(key.getPrivate()); console.log(point.eq(point2)); // true // Encode point var encoded = point.encode('hex'); // uncompressed var compressed = point.encode('hex', true); // compressed ``` -------------------------------- ### Preset Curve Usage Example Source: https://github.com/indutny/elliptic/blob/master/_autodocs/types.md Shows how to access and use predefined elliptic curves like secp256k1, p256, and ed25519 from the elliptic library. It demonstrates initializing an EC instance with a preset curve. ```javascript var elliptic = require('elliptic'); // Access preset curves var secp256k1 = elliptic.curves.secp256k1; var p256 = elliptic.curves.p256; var ed25519 = elliptic.curves.ed25519; // Use with EC var EC = elliptic.ec; var ec = new EC(secp256k1); // or pass string 'secp256k1' ``` -------------------------------- ### Generate and Get Public Key Source: https://github.com/indutny/elliptic/blob/master/_autodocs/quick-reference.md Shows how to generate a new key pair and retrieve the public key in different formats: uncompressed hex, compressed hex, and as an object with x and y coordinates. ```javascript var key = ec.genKeyPair(); var pub = key.getPublic('hex'); // uncompressed var pubCompressed = key.getPublic(true, 'hex'); // compressed var pubObj = { x: key.getPublic().getX().toString('hex'), y: key.getPublic().getY().toString('hex') }; ``` -------------------------------- ### Encode Key Pair to Different Formats Source: https://github.com/indutny/elliptic/blob/master/_autodocs/usage-guide.md Demonstrates how to get private and public keys in hex, array, or buffer formats. Useful for serialization and storage. ```javascript var EC = require('elliptic').ec; var ec = new EC('secp256k1'); var key = ec.genKeyPair(); // Hex string var privHex = key.getPrivate('hex'); var pubHex = key.getPublic('hex'); // Array of bytes var privArray = key.getPrivate('array'); var pubArray = key.getPublic('array'); // Buffer (Node.js) var privBuffer = key.getPrivate('buffer'); var pubBuffer = key.getPublic('buffer'); // Public key compact/compressed var pubCompressed = key.getPublic(true, 'hex'); ``` -------------------------------- ### Get Private Key Source: https://github.com/indutny/elliptic/blob/master/_autodocs/quick-reference.md Illustrates how to retrieve the private key from a key pair object in various formats: hex string, byte array, or as a Big Number (BN) object. ```javascript var priv = key.getPrivate('hex'); // hex string var privArray = key.getPrivate('array'); // byte array var privBN = key.getPrivate(); // BN object ``` -------------------------------- ### Encode Signature to DER Format Source: https://github.com/indutny/elliptic/blob/master/_autodocs/api-reference-signature.md Shows how to encode a signature into DER format as a hex string, byte array, or Buffer. Includes a round-trip example of signing, encoding to DER, and verifying. ```javascript var key = ec.genKeyPair(); var msgHash = [0, 1, 2, 3, 4, 5]; var signature = key.sign(msgHash); // Get DER as hex string (most common) var derHex = signature.toDER('hex'); console.log(derHex); // Output: '304502210099f...8701' // Get DER as byte array var derArray = signature.toDER(); console.log(derArray); // Output: [0x30, 0x45, 0x02, 0x21, ...] // Get DER as Buffer var derBuffer = signature.toDER('buffer'); console.log(Buffer.isBuffer(derBuffer)); // true // Round-trip: sign -> DER -> verify var key2 = ec.keyFromPublic(key.getPublic('hex'), 'hex'); var valid = ec.verify(msgHash, derHex, key2, 'hex'); console.log(valid); // true ``` -------------------------------- ### Mocha Test Setup and Runner Configuration Source: https://github.com/indutny/elliptic/blob/master/test/unittests.html Configures Mocha for running tests, sets a timeout, and initializes a test runner. It also sets up event listeners for test completion and failures to report results. ```javascript mocha.setup('bdd'); mocha.timeout(20000); mocha.setup('bdd'); mocha.timeout(20000); var runner = mocha.run(); var failedTests = []; runner.on('end', function(){ window.mochaResults = runner.stats; window.mochaResults.reports = failedTests; }); runner.on('fail', function(test, err) { var flattenTitles = function(test) { var titles = []; while (test.parent.title) { titles.push(test.parent.title); test = test.parent; } return titles.reverse(); }; failedTests.push({name: test.title, result: false, message: err.message, stack: err.stack, titles: flattenTitles(test)}); }); ``` -------------------------------- ### Get Private Key in Different Formats Source: https://github.com/indutny/elliptic/blob/master/_autodocs/INDEX.md Retrieve the private key in hexadecimal, byte array, or Buffer format. The default output is a Big Number instance. ```javascript key.getPrivate('hex') ``` ```javascript key.getPrivate('array') ``` ```javascript key.getPrivate('buffer') ``` ```javascript key.getPrivate() ``` -------------------------------- ### Usage Example: EdDSA Signature to Hex Source: https://github.com/indutny/elliptic/blob/master/_autodocs/api-reference-eddsa.md Demonstrates how to generate a signature and then encode it to a hex string for display or transmission. The output is a 128-character hex string for ed25519. ```javascript var key = eddsa.keyFromSecret('693e3c...'); var msgHash = [0, 1, 2, 3]; var signature = key.sign(msgHash); var sigHex = signature.toHex(); console.log(sigHex); // Output: '70BED1...ABC123' (128 hex chars for ed25519) ``` -------------------------------- ### Get Public Key from KeyPair Source: https://github.com/indutny/elliptic/blob/master/_autodocs/api-reference-key-pair.md Retrieve the public key in various formats, including Point objects, uncompressed/compressed hex strings, or Buffers. Specify encoding and compactness. ```javascript keypair.getPublic(compact, enc) ``` ```javascript var key = ec.genKeyPair(); // Get as Point object var pub = key.getPublic(); console.log(pub.getX().toString(16)); console.log(pub.getY().toString(16)); // Get uncompressed hex string var pubHex = key.getPublic('hex'); // Format: '04' + x_coords + y_coords // Get compressed hex string var pubCompressed = key.getPublic(true, 'hex'); // Format: '02/03' + x_coords // Get as Buffer var pubBuffer = key.getPublic('utf8', 'buffer'); ``` -------------------------------- ### Main Entry Point Exports Source: https://github.com/indutny/elliptic/blob/master/_autodocs/modules-and-exports.md Accesses library version, utility functions, curve classes, preset curves, and context classes for ECDSA and EdDSA. ```javascript var elliptic = require('elliptic'); console.log(elliptic.version); // '6.6.1' var EC = elliptic.ec; // EC constructor var EdDSA = elliptic.eddsa; // EdDSA constructor var curves = elliptic.curves; // available curves var utils = elliptic.utils; // utility functions ``` -------------------------------- ### Get Private Key from KeyPair Source: https://github.com/indutny/elliptic/blob/master/_autodocs/INDEX.md Retrieve the private key component from a KeyPair object. ```javascript keypair.getPrivate(enc) ``` -------------------------------- ### Get Public Key from KeyPair Source: https://github.com/indutny/elliptic/blob/master/_autodocs/INDEX.md Retrieve the public key component from a KeyPair object. ```javascript keypair.getPublic(compact, enc) ``` -------------------------------- ### Optimizing Key Pair Generation and Signing Source: https://github.com/indutny/elliptic/blob/master/_autodocs/quick-reference.md Demonstrates the performance benefit of reusing the EC instance for multiple key generation and signing operations. Creating a new EC instance in a loop is inefficient. ```javascript // Good var ec = new EC('secp256k1'); for (var i = 0; i < 1000; i++) { var key = ec.genKeyPair(); var sig = key.sign(msg); } // Bad for (var i = 0; i < 1000; i++) { var ec = new EC('secp256k1'); // expensive var key = ec.genKeyPair(); var sig = key.sign(msg); } ``` -------------------------------- ### Get ECDSA Key Recovery Parameter Source: https://github.com/indutny/elliptic/blob/master/_autodocs/INDEX.md Calculate the key recovery parameter for an ECDSA signature. ```javascript ec.getKeyRecoveryParam(e, sig, Q, enc) ``` -------------------------------- ### Perform Modular Arithmetic with RedBN Source: https://github.com/indutny/elliptic/blob/master/_autodocs/types.md Shows how to use RedBN for faster modular arithmetic. It involves creating a reduction context using BN.mont(), converting regular BNs to RedBN instances, performing modular addition using redAdd(), and converting the result back to a normal BN. ```javascript var BN = require('bn.js'); var red = BN.mont(p); var x = new BN(5).toRed(red); var y = new BN(3).toRed(red); var z = x.redAdd(y); // z = 8 mod p var result = z.fromRed(); // convert back to normal BN ``` -------------------------------- ### Get Public Key from KeyPair (EdDSA) Source: https://github.com/indutny/elliptic/blob/master/_autodocs/INDEX.md Retrieve the public key component from an EdDSA KeyPair object. ```javascript keypair.getPublic(enc) ``` -------------------------------- ### Initialize KeyPair Source: https://github.com/indutny/elliptic/blob/master/_autodocs/api-reference-key-pair.md Instantiate a KeyPair object. Can be initialized empty, with a private key, or with a public key for verification purposes. ```javascript var EC = require('elliptic').ec; var ec = new EC('secp256k1'); // Empty keypair var kp = ec.keyPair(); // With private key var kp2 = ec.keyPair({ priv: '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef', privEnc: 'hex' }); // With public key (verification only) var kp3 = ec.keyPair({ pub: { x: 'x_coordinate_hex', y: 'y_coordinate_hex' }, pubEnc: 'hex' }); ``` -------------------------------- ### Usage Example: EdDSA Signature to Bytes Source: https://github.com/indutny/elliptic/blob/master/_autodocs/api-reference-eddsa.md Shows how to obtain the byte array representation of an EdDSA signature. For ed25519, this array will have a length of 64. ```javascript var signature = key.sign(msgHash); var sigBytes = signature.toBytes(); console.log(sigBytes.length); // 64 for ed25519 ``` -------------------------------- ### keyFromPrivate Source: https://github.com/indutny/elliptic/blob/master/_autodocs/api-reference-ec.md Constructs a KeyPair instance from a given private key. Supports various formats for the private key input and encoding. ```APIDOC ## ec.keyFromPrivate(priv, enc) ### Description Constructs a KeyPair instance from a given private key. Supports various formats for the private key input and encoding. ### Parameters * **priv** (BN | Buffer | Array | string | number) - Required - Private key in various formats. * **enc** (string) - Optional - Encoding of private key ('hex', 'array', 'buffer'). Defaults to 'hex'. ### Returns KeyPair instance ### Usage Example ```javascript // From hex string var key = ec.keyFromPrivate('0123456789abcdef...', 'hex'); // From array var key2 = ec.keyFromPrivate([1, 2, 3, 4, ...], 'array'); // From BN (big number) var BN = require('bn.js'); var key3 = ec.keyFromPrivate(new BN('0123...', 16)); ``` ``` -------------------------------- ### Main Entry Point: require('elliptic') Source: https://github.com/indutny/elliptic/blob/master/_autodocs/modules-and-exports.md The main entry point for the elliptic library provides access to its version, utility functions, curve definitions, and the core EC and EdDSA classes. ```APIDOC ## require('elliptic') ### Description Provides access to the library's version, utility functions, curve definitions, and the core EC and EdDSA classes. ### Exported Properties - **version** (string): The library version. - **utils** (object): Utility functions. - **rand** (function): Random byte generator. - **curve** (object): Curve type classes. - **curves** (object): Preset curve instances. - **ec** (class): ECDSA context class. - **eddsa** (class): EdDSA context class. ### Usage Example ```javascript var elliptic = require('elliptic'); console.log(elliptic.version); // '6.6.1' var EC = elliptic.ec; // EC constructor var EdDSA = elliptic.eddsa; // EdDSA constructor var curves = elliptic.curves; // available curves var utils = elliptic.utils; // utility functions ``` ``` -------------------------------- ### Key Creation Methods Source: https://github.com/indutny/elliptic/blob/master/_autodocs/quick-reference.md Methods for generating new key pairs or importing existing private and public keys. ```javascript // Key creation ec.genKeyPair() ec.keyFromPrivate(priv, enc) ec.keyFromPublic(pub, enc) ``` -------------------------------- ### Get Public Key in Different Formats Source: https://github.com/indutny/elliptic/blob/master/_autodocs/INDEX.md Retrieve the public key in hexadecimal (uncompressed or compressed), byte array, or Buffer format. Coordinate objects can also be accessed. ```javascript key.getPublic('hex') ``` ```javascript key.getPublic(true, 'hex') ``` ```javascript key.getPublic('array') ``` ```javascript key.getPublic('buffer') ``` ```javascript {x: key.getPublic().getX(), ...} ``` -------------------------------- ### KeyPair Constructors (EC) Source: https://github.com/indutny/elliptic/blob/master/_autodocs/quick-reference.md Shows various methods for creating or loading KeyPair objects within the EC context. ```javascript // KeyPair (EC) ec.keyPair(options) ec.keyFromPrivate(priv, enc) ec.keyFromPublic(pub, enc) ec.genKeyPair(options) ``` -------------------------------- ### KeyPair Constructor Source: https://github.com/indutny/elliptic/blob/master/_autodocs/api-reference-key-pair.md Initializes a new KeyPair instance. It can be used to create an empty key pair, or one initialized with a private or public key. ```APIDOC ## Constructor: KeyPair Represents an ECDSA key pair (public and/or private). ### Signature ```javascript new KeyPair(ec, options) ``` ### Parameters #### `ec` - **Type:** EC - **Required:** Yes - **Description:** EC instance that context belongs to #### `options` - **Type:** object - **Required:** No - **Default:** {} - **Description:** Key initialization options ##### `options.priv` - **Type:** BN | Buffer | string - **Required:** No - **Description:** Private key ##### `options.privEnc` - **Type:** string - **Required:** No - **Default:** 'hex' - **Description:** Private key encoding ##### `options.pub` - **Type:** object | Buffer | string - **Required:** No - **Description:** Public key ##### `options.pubEnc` - **Type:** string - **Required:** No - **Default:** 'hex' - **Description:** Public key encoding ### Returns - KeyPair instance ### Usage Example ```javascript var EC = require('elliptic').ec; var ec = new EC('secp256k1'); // Empty keypair var kp = ec.keyPair(); // With private key var kp2 = ec.keyPair({ priv: '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef', privEnc: 'hex' }); // With public key (verification only) var kp3 = ec.keyPair({ pub: { x: 'x_coordinate_hex', y: 'y_coordinate_hex' }, pubEnc: 'hex' }); ``` ``` -------------------------------- ### Key Pair Options for Private and Public Keys Source: https://github.com/indutny/elliptic/blob/master/_autodocs/INDEX.md Describes the options for providing private and public keys when initializing a key pair, including their format and encoding. ```javascript { priv: BN|string|Buffer, // private key privEnc: string, // private key encoding pub: Point|object|string, // public key pubEnc: string // public key encoding } ``` -------------------------------- ### Get Private Key from KeyPair Source: https://github.com/indutny/elliptic/blob/master/_autodocs/api-reference-key-pair.md Retrieve the private key in the specified encoding (BN, hex string, array, or Buffer). Throws an error if the KeyPair only contains a public key. ```javascript keypair.getPrivate(enc) ``` ```javascript var key = ec.genKeyPair(); // Get as BN (big number) var priv = key.getPrivate(); console.log(priv.toString(16)); // Get as hex string var privHex = key.getPrivate('hex'); // Get as array of bytes var privArray = key.getPrivate('array'); // Encoding 'hex' gives zero-padded 2-digit hex (64 chars for secp256k1) var privHex2 = key.getPrivate('hex'); ``` -------------------------------- ### Create KeyPair from Coordinates Source: https://github.com/indutny/elliptic/blob/master/_autodocs/quick-reference.md Explains how to create a key pair object by providing the public key's x and y coordinates, specifying the encoding format. ```javascript var key = ec.keyPair({ pub: { x: 'abc123...', y: 'def456...' }, pubEnc: 'hex' }); ``` -------------------------------- ### Create Signature Instance Source: https://github.com/indutny/elliptic/blob/master/_autodocs/api-reference-signature.md Demonstrates creating a Signature instance from an object with r, s, and recoveryParam, from a DER-encoded hex string, and from an existing Signature instance. ```javascript var EC = require('elliptic').ec; var ec = new EC('secp256k1'); var key = ec.genKeyPair(); var msgHash = [0, 1, 2, 3, 4, 5]; var signature = key.sign(msgHash); // Create from object var sig1 = new Signature({ r: 'abc123...', s: 'def456...', recoveryParam: 0 }, 'hex'); // Create from DER-encoded hex string var derHex = 'ab01010101...'; var sig2 = new Signature(derHex, 'hex'); // Create from existing Signature (returns same instance) var sig3 = new Signature(signature); console.log(sig3 === signature); // true ``` -------------------------------- ### Get Signature in DER Format Source: https://github.com/indutny/elliptic/blob/master/_autodocs/INDEX.md Convert a signature to DER format as a hexadecimal string or byte array. Individual components 'r' and 's', as well as the recovery parameter, can also be accessed. ```javascript sig.toDER('hex') ``` ```javascript sig.toDER('array') ``` ```javascript sig.r.toString('hex') ``` ```javascript sig.s.toString('hex') ``` ```javascript sig.recoveryParam ``` -------------------------------- ### Create KeyPair from Private Key Source: https://github.com/indutny/elliptic/blob/master/_autodocs/api-reference-key-pair.md Create a KeyPair instance directly from a private key. If an existing KeyPair is provided, it is returned unchanged. ```javascript var ec = new EC('secp256k1'); var key = KeyPair.fromPrivate(ec, 'abc123...', 'hex'); // If already a KeyPair, returns it unchanged var key2 = KeyPair.fromPrivate(ec, key); console.log(key === key2); // true ``` -------------------------------- ### Signing Messages with Different Encodings Source: https://github.com/indutny/elliptic/blob/master/_autodocs/quick-reference.md Demonstrates how to sign a message using various input formats: Array, Hex string, Buffer, BN, and Number. Ensure the correct encoding is specified when using hex strings. ```javascript key.sign([0, 1, 2, 3, 4, 5]); ``` ```javascript key.sign('000102030405', 'hex'); ``` ```javascript key.sign(Buffer.from([0, 1, 2, 3, 4, 5])); ``` ```javascript key.sign(new (require('bn.js'))(0x000102030405)); ``` ```javascript key.sign(255); ``` -------------------------------- ### Signature Constructors (EC) Source: https://github.com/indutny/elliptic/blob/master/_autodocs/quick-reference.md Illustrates how to create a Signature object for the EC class. ```javascript // Signature (EC) new Signature(options, enc) ``` -------------------------------- ### Get EdDSA Secret Seed Source: https://github.com/indutny/elliptic/blob/master/_autodocs/api-reference-eddsa.md The getSecret method retrieves the secret seed of the KeyPair. It can be returned as a hex string, byte array, or Buffer. This method will throw an error if the KeyPair does not have a private key. ```javascript keypair.getSecret(enc) ``` -------------------------------- ### EdDSA Context Class Usage Source: https://github.com/indutny/elliptic/blob/master/_autodocs/modules-and-exports.md Shows how to instantiate the EdDSA context, generate keys from a secret, sign messages, and verify signatures using a public key. ```javascript var EdDSA = require('elliptic').eddsa; var eddsa = new EdDSA('ed25519'); var key = eddsa.keyFromSecret('693e3c...'); var signature = eddsa.sign([1,2,3], key); var valid = eddsa.verify([1,2,3], signature, key.getPublic('hex')); ``` -------------------------------- ### Get EdDSA Public Key in Various Encodings Source: https://github.com/indutny/elliptic/blob/master/_autodocs/api-reference-eddsa.md The getPublic method allows you to retrieve the public key in different formats: hex string, byte array, or Buffer. This is useful for sharing or storing the public key. ```javascript var key = eddsa.keyFromSecret('693e3c...'); // Get hex string var pubHex = key.getPublic('hex'); // Get buffer var pubBuffer = key.getPublic('buffer'); // Get byte array var pubArray = key.getPublic('array'); ``` -------------------------------- ### Benchmark Results for Elliptic Library Source: https://github.com/indutny/elliptic/blob/master/README.md These benchmarks compare the performance of the elliptic library against eccjs for signing, verification, key generation, and ECDH operations. The results are displayed in operations per second. ```bash node benchmarks/index.js Benchmarking: sign elliptic#sign x 262 ops/sec ±0.51% (177 runs sampled) eccjs#sign x 55.91 ops/sec ±0.90% (144 runs sampled) ------------------------ Fastest is elliptic#sign ======================== Benchmarking: verify elliptic#verify x 113 ops/sec ±0.50% (166 runs sampled) eccjs#verify x 48.56 ops/sec ±0.36% (125 runs sampled) ------------------------ Fastest is elliptic#verify ======================== Benchmarking: gen elliptic#gen x 294 ops/sec ±0.43% (176 runs sampled) eccjs#gen x 62.25 ops/sec ±0.63% (129 runs sampled) ------------------------ Fastest is elliptic#gen ======================== Benchmarking: ecdh elliptic#ecdh x 136 ops/sec ±0.85% (156 runs sampled) ------------------------ Fastest is elliptic#ecdh ======================== ``` -------------------------------- ### Import Utilities Source: https://github.com/indutny/elliptic/blob/master/_autodocs/modules-and-exports.md Use this pattern to import the utils object and access utility functions like toArray. ```javascript var utils = require('elliptic').utils; var array = utils.toArray('ff00aa', 'hex'); ``` -------------------------------- ### Precomputation for EC Instance Source: https://github.com/indutny/elliptic/blob/master/_autodocs/quick-reference.md Notes that precomputation, such as for the generator point 'ec.g', happens automatically upon EC instance initialization, improving performance. ```javascript // Happens automatically var ec = new EC('secp256k1'); // ec.g is precomputed on initialization ``` -------------------------------- ### Constructor Source: https://github.com/indutny/elliptic/blob/master/_autodocs/api-reference-ec.md Initializes a new EC context for ECDSA operations. You can provide either a curve name as a string or an options object containing a specific curve instance. ```APIDOC ## new EC(options) ### Description Initializes a new EC context for ECDSA operations. You can provide either a curve name as a string or an options object containing a specific curve instance. ### Parameters * **options** (string | object) - Required - Either a curve name string (e.g., `'secp256k1'`) or an options object with `curve` property. * **options.curve** (PresetCurve) - Required (if object) - A PresetCurve instance from `elliptic.curves`. ### Returns EC instance ### Throws * **AssertionError** - Unknown curve name provided ### Usage Example ```javascript var elliptic = require('elliptic'); var EC = elliptic.ec; // Create EC context with curve name (shorthand) var ec = new EC('secp256k1'); // Create EC context with curve object (explicit) var ec2 = new EC({ curve: elliptic.curves.secp256k1 }); ``` ``` -------------------------------- ### ECDSA Context Class Usage Source: https://github.com/indutny/elliptic/blob/master/_autodocs/modules-and-exports.md Demonstrates creating an ECDSA context, generating key pairs, signing messages, and verifying signatures. ```javascript var EC = require('elliptic').ec; // Create context var ec = new EC('secp256k1'); // Generate keys var key = ec.genKeyPair(); // Sign var signature = ec.sign([1,2,3], key); // Verify var valid = ec.verify([1,2,3], signature, key); ``` -------------------------------- ### Recover Public Key from Signature Source: https://github.com/indutny/elliptic/blob/master/_autodocs/usage-guide.md Demonstrates how to recover the original public key from a message hash, signature, and recovery parameter. Useful for verifying signatures when the public key is not explicitly known. ```javascript var EC = require('elliptic').ec; var ec = new EC('secp256k1'); var key = ec.genKeyPair(); var msgHash = [0, 1, 2, 3, 4, 5]; var signature = key.sign(msgHash); // Recovery parameter is stored in signature var recoveryParam = signature.recoveryParam; // 0-3 // Recover public key from signature var recovered = ec.recoverPubKey(msgHash, signature, recoveryParam); // Verify it matches original var original = key.getPublic(); console.log('Key recovered:', recovered.eq(original)); // Get recovery param if not available var recoveryParam2 = ec.getKeyRecoveryParam(msgHash, signature, key.getPublic()); console.log('Recovery param:', recoveryParam2); ``` -------------------------------- ### Import EC Constructor with Curve Object Source: https://github.com/indutny/elliptic/blob/master/_autodocs/modules-and-exports.md Use this pattern to import the elliptic library, then access the EC constructor and curves to initialize EC with a curve object. ```javascript var elliptic = require('elliptic'); var EC = elliptic.ec; var curves = elliptic.curves; var ec = new EC({ curve: curves.p256 }); ``` -------------------------------- ### Initialize secp256k1 Curve Source: https://github.com/indutny/elliptic/blob/master/_autodocs/supported-curves.md Instantiate the Elliptic.js library with the secp256k1 curve. This curve is widely used in Bitcoin and Ethereum. ```javascript var EC = require('elliptic').ec; var ec = new EC('secp256k1'); ``` -------------------------------- ### Instance Method: sign Source: https://github.com/indutny/elliptic/blob/master/_autodocs/api-reference-eddsa.md Signs a given message using the provided secret key or KeyPair. The signature can then be verified. ```APIDOC ## Instance Method: sign(message, secret) ### Description Sign a message using EdDSA. ### Parameters - **message** (string | Buffer | Array) - Required - Message bytes to sign. - **secret** (KeyPair | string | Buffer | Array) - Required - Secret seed or KeyPair. ### Returns - Signature instance. ### Usage Example ```javascript var eddsa = new EdDSA('ed25519'); var msgHash = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // Sign with secret (creates key internally) var signature = eddsa.sign(msgHash, '693e3c...'); // Or sign with key object var key = eddsa.keyFromSecret('693e3c...'); var signature2 = key.sign(msgHash); // Convert signature to hex string var sigHex = signature.toHex(); // Round-trip verify var pub = key.getPublic('hex'); var isValid = eddsa.verify(msgHash, sigHex, pub); console.log(isValid); // true ``` ``` -------------------------------- ### Instantiate Elliptic Curve Source: https://github.com/indutny/elliptic/wiki/Home Shortcut for instantiating an elliptic curve object with a specific curve name. ```javascript ec = elliptic.ec('secp256k1') ``` -------------------------------- ### keyFromPublic Source: https://github.com/indutny/elliptic/blob/master/_autodocs/api-reference-ec.md Creates a KeyPair instance from a public key. This is primarily for verification purposes as it does not include the private key. ```APIDOC ## ec.keyFromPublic(pub, enc) ### Description Creates a KeyPair instance from a public key. This is primarily for verification purposes as it does not include the private key. ### Parameters * **pub** (object | Buffer | string) - Required - Public key in various formats. * **enc** (string) - Optional - Encoding of public key. Defaults to 'hex'. ### Returns KeyPair instance (public only) ### Public Key Format Options: 1. **Encoded string/buffer:** `'04' + hex_x + hex_y` (uncompressed), `'02/03' + hex_x` (compressed) 2. **Object with x, y:** `{ x: '...', y: '...' }` (hex strings or buffers) 3. **Point coordinates:** `{ x: BN_instance, y: BN_instance }` ### Usage Example ```javascript // From hex string (uncompressed) var pubKeyHex = '04' + 'x_coordinate...' + 'y_coordinate...'; var key = ec.keyFromPublic(pubKeyHex, 'hex'); // From object (hex coordinates) var key2 = ec.keyFromPublic({ x: '6b17d1f2...', y: '4fe342e2...' }, 'hex'); // From compressed format var key3 = ec.keyFromPublic('02' + '6b17d1f2...', 'hex'); ``` ``` -------------------------------- ### Signature Constructor (EdDSA) Source: https://github.com/indutny/elliptic/blob/master/_autodocs/quick-reference.md Shows how to construct an EdDSA Signature object, requiring the EdDSA instance and the signature data. ```javascript // Signature (EdDSA) new (require('elliptic').eddsa.Signature)(eddsa, sig) ``` -------------------------------- ### Create KeyPair from Public Key Source: https://github.com/indutny/elliptic/blob/master/_autodocs/api-reference-key-pair.md Create a KeyPair instance from a public key, suitable for verification operations. Supports various encodings and input types. ```javascript var ec = new EC('secp256k1'); // From hex-encoded public key var key = KeyPair.fromPublic(ec, '04abc123...', 'hex'); // From coordinates object var key2 = KeyPair.fromPublic(ec, { x: 'x_hex_value', y: 'y_hex_value' }, 'hex'); // From existing KeyPair, returns unchanged var key3 = KeyPair.fromPublic(ec, key); ``` -------------------------------- ### KeyPair.fromPrivate Source: https://github.com/indutny/elliptic/blob/master/_autodocs/api-reference-key-pair.md Creates a KeyPair instance from a given private key. If the provided private key is already a KeyPair instance, it is returned unchanged. ```APIDOC ## Static Method: KeyPair.fromPrivate Create a KeyPair from a private key. ### Signature ```javascript KeyPair.fromPrivate(ec, priv, enc) ``` ### Parameters #### `ec` - **Type:** EC - **Required:** Yes - **Description:** EC context instance #### `priv` - **Type:** KeyPair | BN | string | Buffer | Array - **Required:** Yes - **Description:** Private key or existing KeyPair #### `enc` - **Type:** string - **Required:** No - **Default:** 'hex' - **Description:** Encoding ('hex', 'array', 'buffer') ### Returns - KeyPair instance ### Usage Example ```javascript var ec = new EC('secp256k1'); var key = KeyPair.fromPrivate(ec, 'abc123...', 'hex'); // If already a KeyPair, returns it unchanged var key2 = KeyPair.fromPrivate(ec, key); console.log(key === key2); // true ``` ``` -------------------------------- ### EC Class Constructors Source: https://github.com/indutny/elliptic/blob/master/_autodocs/quick-reference.md Demonstrates the instantiation of the EC class with different curve specifications. ```javascript // EC new EC(curveName) new EC({curve: PresetCurve}) ``` -------------------------------- ### Import EdDSA Constructor Source: https://github.com/indutny/elliptic/blob/master/_autodocs/modules-and-exports.md Use this pattern to import the EdDSA constructor and initialize it with an algorithm name string like 'ed25519'. ```javascript var EdDSA = require('elliptic').eddsa; var eddsa = new EdDSA('ed25519'); ``` -------------------------------- ### Initialize p224 Curve Source: https://github.com/indutny/elliptic/blob/master/_autodocs/supported-curves.md Instantiate the Elliptic.js library with the p224 curve. Suitable for medium security needs and legacy systems. ```javascript var ec = new EC('p224'); ``` -------------------------------- ### Key Creation Source: https://github.com/indutny/elliptic/blob/master/_autodocs/quick-reference.md Methods for generating and loading key pairs from private or public keys. ```APIDOC ## Key Creation ### `ec.genKeyPair()` Generates a new random key pair. ### `ec.keyFromPrivate(priv, enc)` Creates a key pair object from a private key. - `priv`: The private key. - `enc`: The encoding of the private key (e.g., 'hex', 'utf8'). ### `ec.keyFromPublic(pub, enc)` Creates a key pair object from a public key. - `pub`: The public key. - `enc`: The encoding of the public key (e.g., 'hex', 'utf8'). ``` -------------------------------- ### Instance Method: keyFromSecret Source: https://github.com/indutny/elliptic/blob/master/_autodocs/api-reference-eddsa.md Creates a KeyPair object from a secret seed (private key). Supports various input formats for the secret. ```APIDOC ## Instance Method: keyFromSecret(secret) ### Description Create a KeyPair from a secret seed (private key). ### Parameters - **secret** (KeyPair | string | Buffer | Array) - Required - Secret seed bytes or existing KeyPair. - **String:** Hex-encoded seed (e.g., '693e3c...'). - **Buffer:** Raw seed bytes. - **Array:** Byte array. ### Returns - KeyPair instance with private key. ### Usage Example ```javascript var eddsa = new EdDSA('ed25519'); // From hex string (32 bytes = 64 hex chars for ed25519) var key1 = eddsa.keyFromSecret('693e3c...'); // From buffer var key2 = eddsa.keyFromSecret(Buffer.from([...32 bytes...])); // From byte array var key3 = eddsa.keyFromSecret([0x69, 0x3e, 0x3c, ..., 0xff]); // From existing KeyPair (returns unchanged) var key4 = eddsa.keyFromSecret(key1); console.log(key4 === key1); // true ``` ``` -------------------------------- ### KeyPair.fromPublic Source: https://github.com/indutny/elliptic/blob/master/_autodocs/api-reference-key-pair.md Creates a KeyPair instance from a given public key. This KeyPair will only support verification operations as it does not contain a private key. If the provided public key is already a KeyPair instance, it is returned unchanged. ```APIDOC ## Static Method: KeyPair.fromPublic Create a KeyPair from a public key (verification-only, no private key). ### Signature ```javascript KeyPair.fromPublic(ec, pub, enc) ``` ### Parameters #### `ec` - **Type:** EC - **Required:** Yes - **Description:** EC context instance #### `pub` - **Type:** KeyPair | object | string | Buffer - **Required:** Yes - **Description:** Public key or existing KeyPair #### `pubEnc` - **Type:** string - **Required:** No - **Default:** 'hex' - **Description:** Encoding ### Returns - KeyPair instance (public only) ### Usage Example ```javascript var ec = new EC('secp256k1'); // From hex-encoded public key var key = KeyPair.fromPublic(ec, '04abc123...', 'hex'); // From coordinates object var key2 = KeyPair.fromPublic(ec, { x: 'x_hex_value', y: 'y_hex_value' }, 'hex'); // From existing KeyPair, returns unchanged var key3 = KeyPair.fromPublic(ec, key); ``` ``` -------------------------------- ### Initialize p192 Curve Source: https://github.com/indutny/elliptic/blob/master/_autodocs/supported-curves.md Instantiate the Elliptic.js library with the p192 curve. This curve is for legacy systems and not recommended for new applications. ```javascript var ec = new EC('p192'); ``` -------------------------------- ### ECDSA Signing with p521 Source: https://github.com/indutny/elliptic/blob/master/_autodocs/supported-curves.md Shows how to generate a key pair and sign a message hash using the p521 curve for maximum security. ```javascript var EC = require('elliptic').ec; var ec = new EC('p521'); var key = ec.genKeyPair(); var msgHash = [1, 2, 3, 4, 5]; var sig = key.sign(msgHash); ``` -------------------------------- ### Create Key Pair from Private Key Source: https://github.com/indutny/elliptic/blob/master/_autodocs/api-reference-ec.md Instantiate a KeyPair from a private key. Supports various formats for the private key and encodings. ```javascript // From hex string var key = ec.keyFromPrivate('0123456789abcdef...', 'hex'); // From array var key2 = ec.keyFromPrivate([1, 2, 3, 4, ...], 'array'); // From BN (big number) var BN = require('bn.js'); var key3 = ec.keyFromPrivate(new BN('0123...', 16)); ``` -------------------------------- ### Initialize p384 Curve Source: https://github.com/indutny/elliptic/blob/master/_autodocs/supported-curves.md Instantiate the Elliptic.js library with the p384 curve. Suitable for high-security applications requiring 384-bit modulus. ```javascript var ec = new EC('p384'); ``` -------------------------------- ### Signing and Verification Methods Source: https://github.com/indutny/elliptic/blob/master/_autodocs/quick-reference.md Methods for signing messages with a private key and verifying signatures with a public key. ```javascript // Signing/verification ec.sign(msg, key, enc, options) ec.verify(msg, sig, key, enc, options) ``` -------------------------------- ### Create Key Pair Source: https://github.com/indutny/elliptic/blob/master/_autodocs/api-reference-ec.md Generate a new key pair. Can be initialized empty to generate keys later, or with existing private or public keys. ```javascript // Empty keypair (keys will be generated later) var kp = ec.keyPair(); // With private key var kp2 = ec.keyPair({ priv: '0123456789abcdef...', // Private key privEnc: 'hex' // Encoding of private key }); // With public key var kp3 = ec.keyPair({ pub: '04abc123...', // Public key pubEnc: 'hex' // Encoding of public key }); ``` -------------------------------- ### Store and Load Keys Source: https://github.com/indutny/elliptic/blob/master/_autodocs/usage-guide.md Serialize private and public keys to JSON for storage and later retrieval. Ensure the EC instance is re-initialized when loading keys. ```javascript // Save var key = ec.genKeyPair(); var stored = { priv: key.getPrivate('hex'), pub: key.getPublic('hex') }; var json = JSON.stringify(stored); // Later, load var EC = require('elliptic').ec; var ec = new EC('secp256k1'); var stored2 = JSON.parse(json); var key2 = ec.keyPair({ priv: stored2.priv, privEnc: 'hex' }); ``` -------------------------------- ### Import Elliptic Library Modules Source: https://github.com/indutny/elliptic/blob/master/_autodocs/quick-reference.md Import the necessary modules from the elliptic library for cryptographic operations. ```javascript var elliptic = require('elliptic'); var EC = elliptic.ec; var EdDSA = elliptic.eddsa; var curves = elliptic.curves; var utils = elliptic.utils; ``` -------------------------------- ### Initialize p521 Curve Source: https://github.com/indutny/elliptic/blob/master/_autodocs/supported-curves.md Instantiate the Elliptic.js library with the p521 curve. Offers maximum security for long-term protection with a 521-bit modulus. ```javascript var ec = new EC('p521'); ``` -------------------------------- ### KeyPair Constructors (EdDSA) Source: https://github.com/indutny/elliptic/blob/master/_autodocs/quick-reference.md Demonstrates methods for creating EdDSA KeyPair objects from secret keys or public keys. ```javascript // KeyPair (EdDSA) eddsa.keyFromSecret(secret) eddsa.keyFromPublic(pub) ``` -------------------------------- ### Import Elliptic Keys Source: https://github.com/indutny/elliptic/blob/master/_autodocs/usage-guide.md Imports keys from different representations including hex strings, byte arrays, and objects containing public key coordinates. Ensure the correct encoding is specified. ```javascript var EC = require('elliptic').ec; var ec = new EC('secp256k1'); // From private key (hex) var privKey = ec.keyFromPrivate('abc123...', 'hex'); // From private key (array) var privKey2 = ec.keyFromPrivate([0xab, 0xc1, 0x23, ...], 'array'); // From public key (hex) var pubKey = ec.keyFromPublic('04abc123...', 'hex'); // From public key (object with coordinates) var pubKey2 = ec.keyFromPublic({ x: 'abc123...', y: 'def456...' }, 'hex'); // From public key (compressed) var pubKey3 = ec.keyFromPublic('02abc123...', 'hex'); ``` -------------------------------- ### Create Key Pair from Public Key Source: https://github.com/indutny/elliptic/blob/master/_autodocs/api-reference-ec.md Instantiate a KeyPair from a public key for verification purposes. Supports various public key formats including encoded strings, buffers, objects with coordinates, and compressed formats. ```javascript // From hex string (uncompressed) var pubKeyHex = '04' + 'x_coordinate...' + 'y_coordinate...'; var key = ec.keyFromPublic(pubKeyHex, 'hex'); // From object (hex coordinates) var key2 = ec.keyFromPublic({ x: '6b17d1f2...', y: '4fe342e2...' }, 'hex'); // From compressed format var key3 = ec.keyFromPublic('02' + '6b17d1f2...', 'hex'); ``` -------------------------------- ### Handle Key Import Errors Source: https://github.com/indutny/elliptic/blob/master/_autodocs/errors-and-exceptions.md This code snippet shows how to import a public key and validate it. It uses a try-catch block to handle potential errors during key import and includes validation checks for the imported key's integrity. ```javascript var EC = require('elliptic').ec; var ec = new EC('secp256k1'); try { var key = ec.keyFromPublic(publicKeyHex, 'hex'); var validation = key.validate(); if (!validation.result) { console.log('Invalid key:', validation.reason); } else { console.log('Valid key'); } } catch (e) { console.log('Error importing key:', e.message); } ``` -------------------------------- ### Sign and Verify a Message with ECDSA Source: https://github.com/indutny/elliptic/blob/master/_autodocs/00-START-HERE.md Demonstrates generating a key pair and signing a message using the secp256k1 curve. The signature can then be verified. ```javascript var EC = require('elliptic').ec; var ec = new EC('secp256k1'); // Generate a key pair var key = ec.genKeyPair(); // Sign a message var signature = key.sign([0, 1, 2, 3, 4, 5]); // Verify it console.log(key.verify([0, 1, 2, 3, 4, 5], signature)); // true ``` -------------------------------- ### Handle Signing Errors Source: https://github.com/indutny/elliptic/blob/master/_autodocs/usage-guide.md Illustrates how to catch errors that occur during the signing process due to invalid message formats, negative numbers, or using a public key. ```javascript var EC = require('elliptic').ec; var ec = new EC('secp256k1'); var key = ec.genKeyPair(); // Invalid message format try { ec.sign({}, key); // Not array-like } catch (e) { console.log('Error:', e.message); } // Negative message try { var BN = require('bn.js'); var neg = new BN(-1); ec.sign(neg, key); } catch (e) { console.log('Error:', e.message); } // Key without private component var pubKey = ec.keyFromPublic(key.getPublic('hex'), 'hex'); try { pubKey.sign([1, 2, 3]); } catch (e) { console.log('Error:', e.message); } ``` -------------------------------- ### Create and Use BN Big Numbers Source: https://github.com/indutny/elliptic/blob/master/_autodocs/types.md Demonstrates how to create a Big Number (BN) instance from a hexadecimal string and use it with the elliptic library to derive a private key and sign a message. The resulting 'r' value from the signature is then converted to a hexadecimal string. ```javascript var BN = require('bn.js'); var EC = require('elliptic').ec; var ec = new EC('secp256k1'); var priv = new BN('abcdef...', 16); var key = ec.keyFromPrivate(priv); var r = key.sign([1,2,3]).r; // r is a BN console.log(r.toString(16)); // output as hex ``` -------------------------------- ### ECDSA Signing with p384 Source: https://github.com/indutny/elliptic/blob/master/_autodocs/supported-curves.md Demonstrates generating a key pair and signing a message hash using the p384 curve for high security. ```javascript var EC = require('elliptic').ec; var ec = new EC('p384'); var key = ec.genKeyPair(); var msgHash = [1, 2, 3, 4, 5]; var sig = key.sign(msgHash); ``` -------------------------------- ### Initialize p256 Curve Source: https://github.com/indutny/elliptic/blob/master/_autodocs/supported-curves.md Instantiate the Elliptic.js library with the p256 curve. This NIST standard curve is common in TLS and certificate authorities. ```javascript var ec = new EC('p256'); ``` -------------------------------- ### Handling Public Key Import Errors Source: https://github.com/indutny/elliptic/blob/master/_autodocs/quick-reference.md Uses a try-catch block to manage errors that may occur when importing a public key from a hex string. ```javascript try { var key = ec.keyFromPublic(pubHex, 'hex'); } catch (e) { console.log('Import error:', e.message); } ```