elliptic

repository·master·Indexed 23 days ago

https://github.com/indutny/elliptic

A fast, plain JavaScript implementation of elliptic-curve cryptography (ECC). Version 6.6.1 provides tools for ECDSA, EdDSA, and ECDH across various supported curves, including secp256k1, p192, p224, p256, p384, p521, curve25519, and ed25519. It supports Short Weierstrass, Montgomery, Edwards, and Twisted Edwards curve types, offering utilities for key pair generation, message signing, signature verification, and shared secret derivation.

Tokens
5.3K
Snippets
6
Records
43
Agent score
82%

What's inside elliptic

  1. Implement ECDH key exchange

    master

    Use the ec module to perform Elliptic Curve Diffie-Hellman (ECDH) key exchange. You can generate key pairs and use the .derive() method to compute a shared secret.

    Note: The .derive() method returns a BN (Big Number) instance. For multi-party key exchange, you can manually perform point multiplication using .getPublic().mul(privateKey).

    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(shared1.toString(16));
    console.log(shared2.toString(16));
  2. Implement ECDSA signing and verification

    master

    Use the ec module to perform Elliptic Curve Digital Signature Algorithm (ECDSA) operations. You can initialize an EC context with a specific curve (e.g., secp256k1), generate key pairs, sign message hashes, and verify signatures.

    Note: The message hash input must be an array or a hex-string. Signatures can be exported as DER-encoded arrays or hex-strings. When verifying without a private key, you must import the public key using keyFromPublic.

    var EC = require('elliptic').ec;
    
    // Create and initialize EC context
    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 pub = pubPoint.encode('hex');
    
    // Import public key
    var key = ec.keyFromPublic(pub, 'hex');
    
    // Verify signature
    console.log(key.verify(msgHash, derSign));
  3. Implement EdDSA signing and verification

    master

    Use the eddsa module for Edwards-curve Digital Signature Algorithm operations. This is suitable for curves like ed25519. You can create a key pair from a secret (hex string, array, or Buffer), sign a message hash, and verify the signature.

    Note: For curve25519, use ed25519 for signing operations as curve25519 is not supported for ECDSA.

    var EdDSA = require('elliptic').eddsa;
    
    // Create and initialize EdDSA context
    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));
  4. Sign a message with ECDSA

    master

    The sign() method creates a digital signature for a given message using the provided private key.

    Parameters:

    • msg: The message to sign. Can be a string, number, BN instance, or an array-like object (e.g., Uint8Array).
    • key: The private key used for signing.
    • enc (optional): The encoding of the key (e.g., 'hex', 'utf8'). If enc is an object, it is treated as the options argument.
    • options (optional): Configuration object.
      • canonical: If true, ensures the signature follows the canonical form (where s is in the lower half of the curve order n).
      • msgBitLength: Allows overriding the bit length of the message.
      • k: A function to provide a custom nonce k for each iteration.

    Returns a Signature object containing r, s, and recoveryParam.

    const msg = 'hello world';
    const key = ec.keyFromPrivate('abc123...');
    const signature = ec.sign(msg, key, { canonical: true });
  5. Recover a public key from a signature

    master

    The recoverPubKey() method allows you to derive the public key from a message and a signature, provided you have the recovery parameter j.

    Parameters:

    • msg: The original message.
    • signature: The signature object.
    • j: The recovery parameter (an integer, typically 0-3).
    • enc (optional): The encoding of the signature.

    Returns the recovered public key point.

    const recoveredPubKey = ec.recoverPubKey(msg, signature, j);
  6. Verify an ECDSA signature

    master

    The verify() method checks if a signature is valid for a given message and public key.

    Parameters:

    • msg: The original message that was signed.
    • signature: The signature to verify. This can be a Signature object or a hex string.
    • key: The public key used for verification.
    • enc (optional): The encoding of the key.
    • options (optional): Configuration object.
      • msgBitLength: Allows overriding the bit length of the message.

    Returns true if the signature is valid, false otherwise.

    const isValid = ec.verify(msg, signature, publicKey);
  7. Find the public key recovery parameter

    master

    If you have a message, a signature, and the expected public key Q, you can use getKeyRecoveryParam() to find the correct recovery parameter j used during signing.

    Parameters:

    • e: The message (as a BN).
    • signature: The signature object.
    • Q: The expected public key point.
    • enc (optional): The encoding of the signature.

    Returns the integer j (0-3) that recovers the public key Q.

    const j = ec.getKeyRecoveryParam(msgBN, signature, publicKey);
  8. Public key and signature formats

    master

    When working with ECDSA, the library supports several formats for public keys and signatures to ensure interoperability.

    Public Key Formats:

    1. '04' + hex string of x + hex string of y
    2. Object with two hex string properties: { x: '...', y: '...' }
    3. Object with two buffer properties: { x: Buffer, y: Buffer }

    Signature Formats:

    1. DER-encoded signature as hex-string
    2. DER-encoded signature as buffer
    3. Object with two hex-string properties: { r: '...', s: '...' }
    4. Object with two buffer properties: { r: Buffer, s: Buffer }
  9. Supported elliptic curves and presets

    master

    Elliptic supports several curve types: Short Weierstrass, Montgomery, Edwards, and Twisted Edwards. The following presets are embedded and ready to use:

    • secp256k1
    • p192
    • p224
    • p256
    • p384
    • p521
    • curve25519 (Note: Use ed25519 for signing/ECDSA)
    • ed25519
  10. Access elliptic curves via the curve registry

    master

    The curve module serves as the central registry for accessing different elliptic curve implementations. You can access specific curve types through the following sub-modules:

    • curve.base: Base curve implementations.
    • curve.short: Short Weierstrass curve implementations.
    • curve.mont: Montgomery curve implementations.
    • curve.edwards: Edwards curve implementations.
  11. Validate a KeyPair with KeyPair.validate

    master

    Use validate() to check if the public key in the KeyPair is valid. It checks if the public key is not the point at infinity, if it is a valid point on the curve, and if it satisfies the curve equation (specifically checking pub * N == O).

    Returns an object: { result: boolean, reason: string | null }.