• Stars
    star
    1,583
  • Rank 28,415 (Top 0.6 %)
  • Language
    JavaScript
  • Created about 10 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Fast Elliptic Curve Cryptography in plain javascript

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.

More Repositories

1

node-ip

IP address tools for node.js
JavaScript
1,457
star
2

bn.js

BigNum in pure javascript
JavaScript
1,171
star
3

sticky-session

Sticky session balancer based on a `cluster` module
JavaScript
965
star
4

webpack-common-shake

CommonJS Tree Shaker plugin for WebPack
JavaScript
914
star
5

bud

**NOT MAINTAINED** Bud - The TLS Terminator
C
454
star
6

heartbleed

Extracting server private key using Heartbleed OpenSSL vulnerability.
C++
391
star
7

hash.js

Hash functions in pure javascript
JavaScript
312
star
8

fft.js

The fastest JS Radix-4/Radix-2 FFT implementation
JavaScript
228
star
9

dht.js

True bittorrent DHT in javascript
JavaScript
215
star
10

vock

VoIP on node.js
C++
182
star
11

candor

Experimental VM for a `Candor` language
C++
176
star
12

asn1.js

ASN.1 Decoder/Encoder/DSL
JavaScript
174
star
13

gyp.js

Feature-reduced port of GYP to JavaScript
JavaScript
160
star
14

common-shake

CommonJS Tree Shaker API
JavaScript
149
star
15

node-nat-upnp

NAT port mapping via UPnP
JavaScript
147
star
16

caine

Friendly butler
JavaScript
139
star
17

proof-of-work

Proof of Work with SHA256 and Bloom filter
JavaScript
112
star
18

node-index

Append-only B+ Tree index for node.js
CoffeeScript
85
star
19

wasm-jit

WebAssembly JIT
JavaScript
84
star
20

ocsp

OCSP Stapling/Checking for node.js
JavaScript
83
star
21

gradtype

WIP
Python
67
star
22

keychair

Chair and the Key
JavaScript
65
star
23

uv_link_t

Chainable libuv streams
C
63
star
24

vock-server

Server for Vock VoIP
JavaScript
58
star
25

tlsnappy

TLS, but faster!
C++
57
star
26

uv_ssl_t

Chainable SSL implementation for libuv
C
57
star
27

mmap.js

Working mmap bindings for node.js
C++
56
star
28

bitcode

Generate binary LLVM-compatible bitcode from JS
TypeScript
56
star
29

vote.wdgt

Free Proof-of-Work API for fancy Vote Counting widgets
JavaScript
54
star
30

deadbolt

Autoreleasing locks for node.js
JavaScript
54
star
31

node-netroute

Route table bindings for node.js
C++
48
star
32

wasm-ast

WebAssembly AST Parser
JavaScript
47
star
33

git-secure-tag

Secure git tag signing
JavaScript
46
star
34

heatline

Source-annotating profiler for node.js
JavaScript
46
star
35

home

My homepage
JavaScript
46
star
36

disasm

JS Disassembler
JavaScript
45
star
37

json-depth-stream

Streaming JSON parser with depth-limited auxiliary data
JavaScript
43
star
38

self-signed

Generate Self-Signed certificates in browser
JavaScript
41
star
39

hpack.js

HPACK implementation in pure JavaScript
JavaScript
39
star
40

tls.js

TLS Protocol implementation for node.js
JavaScript
39
star
41

spoon

CPS Style for JavaScript, JS->CFG->JS Transpiler
JavaScript
37
star
42

entropoetry

Entropic Poetry
JavaScript
36
star
43

dns.js

Plain javascript dns
JavaScript
36
star
44

bthread

BThread - Thread messaging and blog posting on bitcoin blockchain
JavaScript
33
star
45

bplus

Append-only B+ tree implemented in C
C
31
star
46

promise-waitlist

Promise-based Wait List for your apps
JavaScript
31
star
47

json-pipeline

JSON pipeline for a hypothetical compiler
JavaScript
30
star
48

satoshi

Satoshi Conspiracy
JavaScript
30
star
49

bar

Node.js framework for building large modular web applications.
JavaScript
29
star
50

breakdown

Trace outgoing http requests for an http server and track the time spent doing CPU intensive workload during each request.
JavaScript
29
star
51

isodrive

Isometric game engine
JavaScript
28
star
52

miller-rabin

JavaScript
28
star
53

des.js

DES algorithm
JavaScript
27
star
54

pripub

RSA encryption for node.js
C++
25
star
55

minimalistic-crypto-utils

Minimalistic utils for JS-only crypto
JavaScript
24
star
56

macho

Mach-O parser for node.js
JavaScript
23
star
57

wasm-cli

CLI for wasm-jit
JavaScript
23
star
58

node-balancer

Node load balancer
JavaScript
22
star
59

nTPL

node.js Templating system
JavaScript
22
star
60

node.gzip

!!!!!! Not-supported !!!!!!!
JavaScript
22
star
61

uv_http_t

Chainable HTTP Server implementation
C
21
star
62

hmac-drbg

JS-only Hmac DRBG implementation
JavaScript
20
star
63

hash-cracker

V8 Hash Seed timing attack
C
20
star
64

json-gpg

JSON GPG sign and verify
JavaScript
20
star
65

dukhttp

C
19
star
66

bulk-gcd

Bulk GCD in Rust
Rust
19
star
67

brorand

JavaScript
19
star
68

ninja.js

Naive `ninja` implementation
JavaScript
18
star
69

escape.js

Using escape analysis to enforce heap value lifetime in JS
18
star
70

bitcode-builder

API for building typed CFG for bitcode module
TypeScript
17
star
71

github-scan

Collecting public SSH keys using GitHub APIs
TypeScript
16
star
72

elfy

Dumb simple ELF parser
JavaScript
16
star
73

llvm-ir

LLVM IR Builder
JavaScript
16
star
74

redns

Fast and configurable DNS lookup cache
JavaScript
15
star
75

awesome64

WIP Awesome 64-bit integer implementation in JS
JavaScript
15
star
76

pyg

Not GYP
C
14
star
77

linearscan.rs

Linear scan register allocator written in Rust
Rust
14
star
78

crypto-deck

Cryptographically secure Mental Card Deck implementation
JavaScript
14
star
79

hypercorn

WIP
JavaScript
14
star
80

node-bplus

Node.js bindings for a bplus library
C++
13
star
81

mini-test.c

Minimalistic portable test runner for C projects
C
13
star
82

node-cf

Run CFRunLoop within libuv's eventloop
C++
13
star
83

assert-text

Assertion for multi-line texts when you need it
JavaScript
13
star
84

tokio-lock

Access an object from a single Tokio task
Rust
13
star
85

sneequals

Sneaky equality check between objects using proxies
TypeScript
13
star
86

huffin

Vanity ed25519 public keys, through Huffman Codes
JavaScript
12
star
87

core2dump

Core to dump
C
12
star
88

latetyper

Typing latency (OS X only)
C
11
star
89

file-shooter

File Shooter (uv_link_t, uv_ssl_t, uv_http_t)
C
11
star
90

spectrum-analyzer

FFT-based windowed spectrum analyzer
JavaScript
11
star
91

mean.engineer

An incomplete ActivityPub implementation in TypeScript
TypeScript
11
star
92

endian-reader

Small node.js helper for reading from Buffer with specified (ahead of time) endian
JavaScript
11
star
93

audio

Some realtime audio playback/recording for node.js
C++
11
star
94

stream-pair

Coupled Streams
JavaScript
11
star
95

json-pipeline-reducer

Reducer for json-pipeline
JavaScript
11
star
96

mitm.js

JavaScript
10
star
97

json-pipeline-scheduler

Scheduler for JSON-Pipeline project
JavaScript
10
star
98

wbuf

JavaScript
10
star
99

offset-buffer

JavaScript
10
star
100

reopen-tty

A small library to open /dev/tty in a cross-platform way
JavaScript
9
star