Convert Figma logo to code with AI

indutny logoelliptic

Fast Elliptic Curve Cryptography in plain javascript

1,683
373
1,683
139

Top Related Projects

Optimized C library for EC operations on curve secp256k1

Quick Overview

Elliptic is a fast and robust JavaScript library for Elliptic Curve Cryptography (ECC). It provides a set of functions for working with elliptic curves, including key generation, signing, and verification. The library is designed to be efficient and suitable for use in both Node.js and browser environments.

Pros

  • High performance and optimized for speed
  • Supports multiple elliptic curves, including secp256k1 (used in Bitcoin)
  • Compatible with both Node.js and browser environments
  • Well-maintained and actively developed

Cons

  • Limited documentation and examples
  • Steep learning curve for those new to elliptic curve cryptography
  • May require additional security considerations when used in cryptographic applications

Code Examples

  1. Generating a key pair:
const EC = require('elliptic').ec;
const ec = new EC('secp256k1');

const key = ec.genKeyPair();
console.log('Private key:', key.getPrivate('hex'));
console.log('Public key:', key.getPublic('hex'));
  1. Signing a message:
const msg = 'Hello, Elliptic!';
const msgHash = ec.hash().update(msg).digest();
const signature = key.sign(msgHash);

console.log('Signature:', signature.toDER('hex'));
  1. Verifying a signature:
const publicKey = key.getPublic();
const isValid = ec.verify(msgHash, signature, publicKey);

console.log('Signature is valid:', isValid);

Getting Started

To use Elliptic in your project, follow these steps:

  1. Install the library using npm:

    npm install elliptic
    
  2. Import and initialize the library in your JavaScript code:

    const EC = require('elliptic').ec;
    const ec = new EC('secp256k1'); // or another supported curve
    
  3. You can now use the ec object to perform various elliptic curve operations, such as key generation, signing, and verification, as shown in the code examples above.

Competitor Comparisons

Optimized C library for EC operations on curve secp256k1

Pros of secp256k1

  • Highly optimized for performance, especially for Bitcoin-specific operations
  • Written in C, offering better speed and lower-level control
  • Extensively audited and battle-tested in the Bitcoin ecosystem

Cons of secp256k1

  • Limited to secp256k1 curve, less versatile for other elliptic curve operations
  • Steeper learning curve due to C implementation and Bitcoin-specific focus
  • Less straightforward integration in JavaScript/Node.js projects

Code Comparison

secp256k1 (C):

secp256k1_context* ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN);
unsigned char msg[32] = {...};
unsigned char seckey[32] = {...};
secp256k1_ecdsa_signature signature;
secp256k1_ecdsa_sign(ctx, &signature, msg, seckey, NULL, NULL);

elliptic (JavaScript):

const EC = require('elliptic').ec;
const ec = new EC('secp256k1');
const key = ec.keyFromPrivate('private_key');
const msg = 'message';
const signature = key.sign(msg);

The secp256k1 library provides low-level C functions for cryptographic operations, while elliptic offers a more high-level JavaScript API. secp256k1 is focused on performance and security for Bitcoin-specific use cases, whereas elliptic provides a more flexible and easier-to-use interface for various elliptic curve operations across different JavaScript environments.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Elliptic Build Status Coverage Status Code Climate

Saucelabs Test Status

Fast elliptic-curve cryptography in a plain javascript implementation.

NOTE: Please take a look at http://safecurves.cr.yp.to/ before choosing a curve for your cryptography operations.

Incentive

ECC is much slower than regular RSA cryptography, the JS implementations are even more slower.

Benchmarks

$ 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
========================

API

ECDSA

var EC = require('elliptic').ec;

// Create and initialize EC context
// (better do it once and reuse it)
var ec = new EC('secp256k1');

// Generate keys
var key = ec.genKeyPair();

// Sign the message's hash (input must be an array, or a hex-string)
var msgHash = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
var signature = key.sign(msgHash);

// Export DER encoded signature in Array
var derSign = signature.toDER();

// Verify signature
console.log(key.verify(msgHash, derSign));

// CHECK WITH NO PRIVATE KEY

var pubPoint = key.getPublic();
var x = pubPoint.getX();
var y = pubPoint.getY();

// Public Key MUST be either:
// 1) '04' + hex string of x + hex string of y; or
// 2) object with two hex string properties (x and y); or
// 3) object with two buffer properties (x and y)
var pub = pubPoint.encode('hex');                                 // case 1
var pub = { x: x.toString('hex'), y: y.toString('hex') };         // case 2
var pub = { x: x.toBuffer(), y: y.toBuffer() };                   // case 3
var pub = { x: x.toArrayLike(Buffer), y: y.toArrayLike(Buffer) }; // case 3

// Import public key
var key = ec.keyFromPublic(pub, 'hex');

// Signature MUST be either:
// 1) DER-encoded signature as hex-string; or
// 2) DER-encoded signature as buffer; or
// 3) object with two hex-string properties (r and s); or
// 4) object with two buffer properties (r and s)

var signature = '3046022100...'; // case 1
var signature = new Buffer('...'); // case 2
var signature = { r: 'b1fc...', s: '9c42...' }; // case 3

// Verify signature
console.log(key.verify(msgHash, signature));

EdDSA

var EdDSA = require('elliptic').eddsa;

// Create and initialize EdDSA context
// (better do it once and reuse it)
var ec = new EdDSA('ed25519');

// Create key pair from secret
var key = ec.keyFromSecret('693e3c...'); // hex string, array or Buffer

// Sign the message's hash (input must be an array, or a hex-string)
var msgHash = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
var signature = key.sign(msgHash).toHex();

// Verify signature
console.log(key.verify(msgHash, signature));

// CHECK WITH NO PRIVATE KEY

// Import public key
var pub = '0a1af638...';
var key = ec.keyFromPublic(pub, 'hex');

// Verify signature
var signature = '70bed1...';
console.log(key.verify(msgHash, signature));

ECDH

var EC = require('elliptic').ec;
var ec = new EC('curve25519');

// Generate keys
var key1 = ec.genKeyPair();
var key2 = ec.genKeyPair();

var shared1 = key1.derive(key2.getPublic());
var shared2 = key2.derive(key1.getPublic());

console.log('Both shared secrets are BN instances');
console.log(shared1.toString(16));
console.log(shared2.toString(16));

three and more members:

var EC = require('elliptic').ec;
var ec = new EC('curve25519');

var A = ec.genKeyPair();
var B = ec.genKeyPair();
var C = ec.genKeyPair();

var AB = A.getPublic().mul(B.getPrivate())
var BC = B.getPublic().mul(C.getPrivate())
var CA = C.getPublic().mul(A.getPrivate())

var ABC = AB.mul(C.getPrivate())
var BCA = BC.mul(A.getPrivate())
var CAB = CA.mul(B.getPrivate())

console.log(ABC.getX().toString(16))
console.log(BCA.getX().toString(16))
console.log(CAB.getX().toString(16))

NOTE: .derive() returns a BN instance.

Supported curves

Elliptic.js support following curve types:

  • Short Weierstrass
  • Montgomery
  • Edwards
  • Twisted Edwards

Following curve 'presets' are embedded into the library:

  • secp256k1
  • p192
  • p224
  • p256
  • p384
  • p521
  • curve25519
  • ed25519

NOTE: That curve25519 could not be used for ECDSA, use ed25519 instead.

Implementation details

ECDSA is using deterministic k value generation as per RFC6979. Most of the curve operations are performed on non-affine coordinates (either projective or extended), various windowing techniques are used for different cases.

All operations are performed in reduction context using bn.js, hashing is provided by hash.js

Related projects

  • eccrypto: isomorphic implementation of ECDSA, ECDH and ECIES for both browserify and node (uses elliptic for browser and secp256k1-node for node)

LICENSE

This software is licensed under the MIT License.

Copyright Fedor Indutny, 2014.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

NPM DownloadsLast 30 Days