How to use the elliptic.curves function in elliptic

To help you get started, we’ve selected a few elliptic examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github hyperledger / fabric-sdk-node / fabric-common / lib / impl / CryptoSuite_ECDSA_AES.js View on Github external
}

// [Angelo De Caro] ECDSA signatures do not have unique representation and this can facilitate
// replay attacks and more. In order to have a unique representation,
// this change-set forses BCCSP to generate and accept only signatures
// with low-S.
// Bitcoin has also addressed this issue with the following BIP:
// https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki
// Before merging this change-set, we need to ensure that client-sdks
// generates signatures properly in order to avoid massive rejection
// of transactions.

// map for easy lookup of the "N/2" and "N" value per elliptic curve
const ordersForCurve = {
	'secp256r1': {
		'halfOrder': elliptic.curves.p256.n.shrn(1),
		'order': elliptic.curves.p256.n
	},
	'secp384r1': {
		'halfOrder': elliptic.curves.p384.n.shrn(1),
		'order': elliptic.curves.p384.n
	}
};

function _preventMalleability(sig, curveParams) {
	const halfOrder = ordersForCurve[curveParams.name].halfOrder;
	if (!halfOrder) {
		throw new Error('Can not find the half order needed to calculate "s" value for immalleable signatures. Unsupported curve name: ' + curveParams.name);
	}

	// in order to guarantee 's' falls in the lower range of the order, as explained in the above link,
	// first see if 's' is larger than half of the order, if so, it needs to be specially treated
github hyperledger-archives / fabric / sdk / node / hlc.js View on Github external
// hmac is sha3_384 = 48 bytes or sha3_256 = 32 bytes
        var ephemeralPublicKeyBytes = cipherText.slice(0, 97);
        var encryptedTokBytes = cipherText.slice(97, cipherText.length - 32);
        debug("encryptedTokBytes:\n", encryptedTokBytes);
        var macBytes = cipherText.slice(cipherText.length - 48);
        debug("length = ", ephemeralPublicKeyBytes.length + encryptedTokBytes.length + macBytes.length);
        //debug(rsaPrivKey.decrypt(eCertCreateResp.tok.tok));
        debug('encrypted Tok: ', eCertCreateResp.tok.tok);
        debug('encrypted Tok length: ', eCertCreateResp.tok.tok.length);
        //debug('public key obj:\n',ecKeypair2.pubKeyObj);
        debug('public key length: ', new Buffer(ecKeypair2.pubKeyObj.pubKeyHex, 'hex').length);
        //debug('private key obj:\n',ecKeypair2.prvKeyObj);
        debug('private key length: ', new Buffer(ecKeypair2.prvKeyObj.prvKeyHex, 'hex').length);

        var EC = elliptic.ec;
        var curve = elliptic.curves.p384;
        var ecdsa = new EC(curve);
        
        // convert bytes to usable key object
        var ephPubKey = ecdsa.keyFromPublic(ephemeralPublicKeyBytes.toString('hex'), 'hex');
        var encPrivKey = ecdsa.keyFromPrivate(ecKeypair2.prvKeyObj.prvKeyHex, 'hex');

        var secret = encPrivKey.derive(ephPubKey.getPublic());
        var aesKey = kdf.hkdf(secret.toArray(), 256, null, null, 'sha3-256');

        // debug('aesKey: ',aesKey);
        
        var decryptedTokBytes = kdf.aesCFBDecryt(aesKey, encryptedTokBytes);
        
        // debug(decryptedTokBytes);
        debug(decryptedTokBytes.toString());
github hyperledger / fabric-sdk-node / fabric-ca-client / lib / impl / CryptoSuite_ECDSA_AES.js View on Github external
}

// [Angelo De Caro] ECDSA signatures do not have unique representation and this can facilitate
// replay attacks and more. In order to have a unique representation,
// this change-set forses BCCSP to generate and accept only signatures
// with low-S.
// Bitcoin has also addressed this issue with the following BIP:
// https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki
// Before merging this change-set, we need to ensure that client-sdks
// generates signatures properly in order to avoid massive rejection
// of transactions.

// map for easy lookup of the "N/2" value per elliptic curve
const halfOrdersForCurve = {
	'secp256r1': elliptic.curves['p256'].n.shrn(1),
	'secp384r1': elliptic.curves['p384'].n.shrn(1)
};

function _preventMalleability(sig, curveParams) {
	var halfOrder = halfOrdersForCurve[curveParams.name];
	if (!halfOrder) {
		throw new Error('Can not find the half order needed to calculate "s" value for immalleable signatures. Unsupported curve name: ' + curve);
	}

	// in order to guarantee 's' falls in the lower range of the order, as explained in the above link,
	// first see if 's' is larger than half of the order, if so, it needs to be specially treated
	if (sig.s.cmp(halfOrder) == 1) { // module 'bn.js', file lib/bn.js, method cmp()
		// convert from BigInteger used by jsrsasign Key objects and bn.js used by elliptic Signature objects
		var bigNum = new BN(curveParams.n.toString(16), 16);
		sig.s = bigNum.sub(sig.s);
	}
github hyperledger / fabric-chaincode-node / libraries / fabric-shim-crypto / lib / enc-sign.js View on Github external
}

// [Angelo De Caro] ECDSA signatures do not have unique representation and this can facilitate
// replay attacks and more. In order to have a unique representation,
// this change-set forses BCCSP to generate and accept only signatures
// with low-S.
// Bitcoin has also addressed this issue with the following BIP:
// https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki
// Before merging this change-set, we need to ensure that client-sdks
// generates signatures properly in order to avoid massive rejection
// of transactions.

// map for easy lookup of the "N/2" value per elliptic curve
const halfOrdersForCurve = {
    'secp256r1': elliptic.curves.p256.n.shrn(1),
    'secp384r1': elliptic.curves.p384.n.shrn(1)
};

function _preventMalleability(sig, curveParams) {
    const curve = curveParams.name;
    const halfOrder = halfOrdersForCurve[curve];
    if (!halfOrder) {
        throw new Error(`Can not find the half order needed to calculate "s" value for immalleable signatures. Unsupported curve name: ${curve}`);
    }

    // in order to guarantee 's' falls in the lower range of the order, as explained in the above link,
    // first see if 's' is larger than half of the order, if so, it needs to be specially treated
    if (sig.s.cmp(halfOrder) === 1) { // module 'bn.js', file lib/bn.js, method cmp()
        // convert from BigInteger used by jsrsasign Key objects and bn.js used by elliptic Signature objects
        const bigNum = new BN(curveParams.n.toString(16), 16);
        sig.s = bigNum.sub(sig.s);
    }
github hyperledger / fabric-sdk-node / test / unit / headless-tests.js View on Github external
var jsrsa = require('jsrsasign');
var KEYUTIL = jsrsa.KEYUTIL;
var ECDSA = jsrsa.ECDSA;
var asn1 = jsrsa.asn1;

var CryptoSuite_ECDSA_AES = require('fabric-client/lib/impl/CryptoSuite_ECDSA_AES.js');
var ecdsaKey = require('fabric-client/lib/impl/ecdsa/key.js');
var api = require('fabric-client/lib/api.js');
var elliptic = require('elliptic');
var BN = require('bn.js');
var Signature = require('elliptic/lib/elliptic/ec/signature.js');
var PKCS11 = require('fabric-client/lib/impl/bccsp_pkcs11.js');

const halfOrdersForCurve = {
	'secp256r1': elliptic.curves['p256'].n.shrn(1),
	'secp384r1': elliptic.curves['p384'].n.shrn(1)
};

test('\n\n** utils.getCryptoSuite tests **\n\n', (t) => {
	var cs = utils.getCryptoSuite({keysize: 384, algorithm: 'EC'}, keyValStorePath5);
	t.equal(cs instanceof CryptoSuite_ECDSA_AES, true, 'Should return an instance of CryptoSuite_ECDSA_AES');
	t.equal(cs._keySize, 384, 'Returned instance should have keysize of 384');
	t.equal(cs._storePath, keyValStorePath5, 'Returned instance should have store path of ' + keyValStorePath5);

	cs = utils.getCryptoSuite({keysize: 384, algorithm: 'EC'}, keyValStorePath5);
	t.equal(cs instanceof CryptoSuite_ECDSA_AES, true, 'Default test: should return an instance of CryptoSuite_ECDSA_AES');
	t.equal(cs._keySize, 384, 'Returned instance should have keysize of 384');
	t.equal(cs._storePath, keyValStorePath5, 'Returned instance should have store path of ' + keyValStorePath5);

	cs = utils.getCryptoSuite({algorithm: 'EC'}, keyValStorePath5);
	t.equal(cs instanceof CryptoSuite_ECDSA_AES, true, 'Should return an instance of CryptoSuite_ECDSA_AES');
github hyperledger / fabric-sdk-node / test / integration / signTransactionOffline.js View on Github external
function sign(privateKey, proposalBytes, algorithm, keySize) {
	const hashAlgorithm = algorithm.toUpperCase();
	const hashFunction = HashPrimitives[`${hashAlgorithm}_${keySize}`];
	const ecdsaCurve = elliptic.curves[`p${keySize}`];
	const ecdsa = new EC(ecdsaCurve);
	const key = KEYUTIL.getKey(privateKey);

	const signKey = ecdsa.keyFromPrivate(key.prvKeyHex, 'hex');
	const digest = hashFunction(proposalBytes);

	let sig = ecdsa.sign(Buffer.from(digest, 'hex'), signKey);
	sig = _preventMalleability(sig, key.ecparams);

	return Buffer.from(sig.toDER());
}
github the-bitcoin-token / bitcoin-source / lib / browser / Key.js View on Github external
set: function(c) {
    var oldc = this._compressed;
    this._compressed = !!c;
    if (oldc == this._compressed)
      return;
    var oldp = this._pub;
    if (this._pub) {
      if (this._compressed) {
        var xbuf = this._pub.slice(1, 33);
        var ybuf = this._pub.slice(33, 65);
        var x = new bignum(xbuf);
        var y = new bignum(ybuf);
        var p = new Point(x, y);
        this._pub = p.toCompressedPubKey();
      } else {
        var ec = elliptic.curves.secp256k1;
        var xbuf = this._pub.slice(1, 33);
        var odd = this._pub[0] == 3 ? true : false;
        var p = ec.curve.pointFromX(odd, xbuf);
        var ybuf = new Buffer(p.y.toArray());
        var xb = new bignum(xbuf);
        var yb = new bignum(ybuf);
        var pb = new Point(xb, yb);
        this._pub = pb.toUncompressedPubKey();
      }
    }
    if (!this._compressed) {
      //bug in eckey
      //oldp.slice(1).copy(this._pub, 1);
    }
  },
  get: function() {
github hyperledger / fabric-sdk-node / fabric-common / lib / impl / bccsp_pkcs11.js View on Github external
}
		if (!hashAlgo || typeof hashAlgo !== 'string') {
			throw new Error(util.format('Unsupported hash algorithm: %j', hashAlgo));
		}
		hashAlgo = hashAlgo.toUpperCase();
		const hashPair = `${hashAlgo}_${keySize}`;
		if (!CryptoAlgorithms[hashPair] || !HashPrimitives[hashPair]) {
			throw Error(util.format('Unsupported hash algorithm and key size pair: %s', hashPair));
		}

		super();

		this._keySize = keySize;

		this._curveName = `secp${this._keySize}r1`;
		this._ecdsaCurve = elliptic.curves[`p${this._keySize}`];

		this._hashAlgo = hashAlgo;

		this._hashFunction = HashPrimitives[hashPair];

		/*
		 * Load native PKCS11 library, open PKCS11 session and login.
		 */
		if (_pkcs11 === null) {
			_pkcs11 = new pkcs11js.PKCS11();
		}
		this._pkcs11 = _pkcs11;

		this._pkcs11OpenSession(this._pkcs11, pkcs11Lib, pkcs11Slot, pkcs11Pin, pkcs11UserType, pkcs11ReadWrite);

		/*
github hyperledger-archives / fabric / sdk / node / lib / crypto.js View on Github external
this.hashFunctionKeyDerivation = hashPrimitives.hash_sha3_384;
                this.hashOutputSize = 48;
                break;
            case "sha2-256":
                debug("Using sha2-256");
                this.hashFunction = hashPrimitives.sha2_256;
                this.hashFunctionKeyDerivation = hashPrimitives.hash_sha2_256;
                this.hashOutputSize = 32;
                break;
        }
        switch (this.securityLevel) {
            case 256:
                this.ecdsaCurve = elliptic.curves['p256'];
                break;
            case 384:
                this.ecdsaCurve = elliptic.curves['p384'];
                break;
        }
    };
    /** HKDF with the specified hash function.
github the-bitcoin-token / bitcoin-source / src / crypto / point.js View on Github external
import elliptic from 'elliptic'
import BN from './bn'
import BufferUtil from '../util/buffer'

const ec = elliptic.curves.secp256k1
const ecPoint = ec.curve.point.bind(ec.curve)
const ecPointFromX = ec.curve.pointFromX.bind(ec.curve)

/**
 *
 * Instantiate a valid secp256k1 Point from the X and Y coordinates.
 *
 * @param {BN|String} x - The X coordinate
 * @param {BN|String} y - The Y coordinate
 * @link https://github.com/indutny/elliptic
 * @augments elliptic.curve.point
 * @throws {Error} A validation error if exists
 * @returns {Point} An instance of Point
 * @constructor
 */
const Point = function Point(x, y, isRed) {