Example usage for org.bouncycastle.asn1.x9 X9ECParameters getCurve

List of usage examples for org.bouncycastle.asn1.x9 X9ECParameters getCurve

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x9 X9ECParameters getCurve.

Prototype

public ECCurve getCurve() 

Source Link

Usage

From source file:ACNS.thresholdDSA.Util.java

License:Apache License

public static PublicParameters generateParamsforBitcoin(int k, int kPrime, SecureRandom rand,
        PaillierKey paillierPubKey) {//w ww .j  ava 2  s.c o  m

    X9ECParameters params = SECNamedCurves.getByName("secp256k1");
    ECDomainParameters CURVE = new ECDomainParameters(params.getCurve(), params.getG(), params.getN(),
            params.getH());

    int primeCertainty = k;
    BigInteger p;
    BigInteger q;
    BigInteger pPrime;
    BigInteger qPrime;
    BigInteger pPrimeqPrime;
    BigInteger nHat;

    do {
        p = new BigInteger(kPrime / 2, primeCertainty, rand);
    } while (!p.subtract(BigInteger.ONE).divide(BigInteger.valueOf(2)).isProbablePrime(primeCertainty));

    pPrime = p.subtract(BigInteger.ONE).divide(BigInteger.valueOf(2));

    do {
        q = new BigInteger(kPrime / 2, primeCertainty, rand);
    } while (!q.subtract(BigInteger.ONE).divide(BigInteger.valueOf(2)).isProbablePrime(primeCertainty));

    qPrime = q.subtract(BigInteger.ONE).divide(BigInteger.valueOf(2));

    // generate nhat. the product of two safe primes, each of length
    // kPrime/2
    nHat = p.multiply(q);

    BigInteger h2 = randomFromZnStar(nHat, rand);
    pPrimeqPrime = pPrime.multiply(qPrime);

    BigInteger x = randomFromZn(pPrimeqPrime, rand);
    BigInteger h1 = h2.modPow(x, nHat);

    return new PublicParameters(CURVE, nHat, kPrime, h1, h2, paillierPubKey);

}

From source file:co.rsk.peg.BridgeSupportTest.java

License:Open Source License

/**
 * Helper method to test addSignature() with a valid federatorPublicKey parameter and both valid/invalid signatures
 * @param privateKeysToSignWith keys used to sign the tx. Federator key when we want to produce a valid signature, a random key when we want to produce an invalid signature
 * @param numberOfInputsToSign There is just 1 input. 1 when testing the happy case, other values to test attacks/bugs.
 * @param signatureCanonical Signature should be canonical. true when testing the happy case, false to test attacks/bugs.
 * @param signTwice Sign again with the same key
 * @param expectedResult "InvalidParameters", "PartiallySigned" or "FullySigned"
 *///from w ww  . j a  va  2s .c  om
private void addSignatureFromValidFederator(List<BtcECKey> privateKeysToSignWith, int numberOfInputsToSign,
        boolean signatureCanonical, boolean signTwice, String expectedResult) throws Exception {
    // Federation is the genesis federation ATM
    Federation federation = bridgeConstants.getGenesisFederation();
    Repository repository = createRepositoryImpl(config);

    final Keccak256 keccak256 = PegTestUtils.createHash3();

    Repository track = repository.startTracking();
    BridgeStorageProvider provider = new BridgeStorageProvider(track, PrecompiledContracts.BRIDGE_ADDR,
            config.getBlockchainConfig().getCommonConstants().getBridgeConstants(),
            bridgeStorageConfigurationAtHeightZero);

    BtcTransaction prevTx = new BtcTransaction(btcParams);
    TransactionOutput prevOut = new TransactionOutput(btcParams, prevTx, Coin.FIFTY_COINS,
            federation.getAddress());
    prevTx.addOutput(prevOut);

    BtcTransaction t = new BtcTransaction(btcParams);
    TransactionOutput output = new TransactionOutput(btcParams, t, Coin.COIN,
            new BtcECKey().toAddress(btcParams));
    t.addOutput(output);
    t.addInput(prevOut).setScriptSig(PegTestUtils.createBaseInputScriptThatSpendsFromTheFederation(federation));
    provider.getRskTxsWaitingForSignatures().put(keccak256, t);
    provider.save();
    track.commit();

    track = repository.startTracking();
    List<LogInfo> logs = new ArrayList<>();
    BridgeEventLogger eventLogger = new BridgeEventLoggerImpl(bridgeConstants, logs);
    BridgeSupport bridgeSupport = new BridgeSupport(config, track, eventLogger, contractAddress,
            mock(Block.class));

    Script inputScript = t.getInputs().get(0).getScriptSig();
    List<ScriptChunk> chunks = inputScript.getChunks();
    byte[] program = chunks.get(chunks.size() - 1).data;
    Script redeemScript = new Script(program);
    Sha256Hash sighash = t.hashForSignature(0, redeemScript, BtcTransaction.SigHash.ALL, false);

    BtcECKey.ECDSASignature sig = privateKeysToSignWith.get(0).sign(sighash);
    if (!signatureCanonical) {
        sig = new BtcECKey.ECDSASignature(sig.r, BtcECKey.CURVE.getN().subtract(sig.s));
    }
    byte[] derEncodedSig = sig.encodeToDER();

    List derEncodedSigs = new ArrayList();
    for (int i = 0; i < numberOfInputsToSign; i++) {
        derEncodedSigs.add(derEncodedSig);
    }
    bridgeSupport.addSignature(findPublicKeySignedBy(federation.getPublicKeys(), privateKeysToSignWith.get(0)),
            derEncodedSigs, keccak256.getBytes());
    if (signTwice) {
        // Create another valid signature with the same private key
        ECDSASigner signer = new ECDSASigner();
        X9ECParameters CURVE_PARAMS = CustomNamedCurves.getByName("secp256k1");
        ECDomainParameters CURVE = new ECDomainParameters(CURVE_PARAMS.getCurve(), CURVE_PARAMS.getG(),
                CURVE_PARAMS.getN(), CURVE_PARAMS.getH());
        ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(privateKeysToSignWith.get(0).getPrivKey(),
                CURVE);
        signer.init(true, privKey);
        BigInteger[] components = signer.generateSignature(sighash.getBytes());
        BtcECKey.ECDSASignature sig2 = new BtcECKey.ECDSASignature(components[0], components[1])
                .toCanonicalised();
        bridgeSupport.addSignature(
                findPublicKeySignedBy(federation.getPublicKeys(), privateKeysToSignWith.get(0)),
                Lists.newArrayList(sig2.encodeToDER()), keccak256.getBytes());
    }
    if (privateKeysToSignWith.size() > 1) {
        BtcECKey.ECDSASignature sig2 = privateKeysToSignWith.get(1).sign(sighash);
        byte[] derEncodedSig2 = sig2.encodeToDER();
        List derEncodedSigs2 = new ArrayList();
        for (int i = 0; i < numberOfInputsToSign; i++) {
            derEncodedSigs2.add(derEncodedSig2);
        }
        bridgeSupport.addSignature(
                findPublicKeySignedBy(federation.getPublicKeys(), privateKeysToSignWith.get(1)),
                derEncodedSigs2, keccak256.getBytes());
    }
    bridgeSupport.save();
    track.commit();

    provider = new BridgeStorageProvider(repository, PrecompiledContracts.BRIDGE_ADDR,
            config.getBlockchainConfig().getCommonConstants().getBridgeConstants(),
            bridgeStorageConfigurationAtHeightZero);

    if ("FullySigned".equals(expectedResult)) {
        Assert.assertTrue(provider.getRskTxsWaitingForSignatures().isEmpty());
        Assert.assertThat(logs, is(not(empty())));
        Assert.assertThat(logs, hasSize(3));
        LogInfo releaseTxEvent = logs.get(2);
        Assert.assertThat(releaseTxEvent.getTopics(), hasSize(1));
        Assert.assertThat(releaseTxEvent.getTopics(), hasItem(Bridge.RELEASE_BTC_TOPIC));
        BtcTransaction releaseTx = new BtcTransaction(bridgeConstants.getBtcParams(),
                ((RLPList) RLP.decode2(releaseTxEvent.getData()).get(0)).get(1).getRLPData());
        Script retrievedScriptSig = releaseTx.getInput(0).getScriptSig();
        Assert.assertEquals(4, retrievedScriptSig.getChunks().size());
        Assert.assertEquals(true, retrievedScriptSig.getChunks().get(1).data.length > 0);
        Assert.assertEquals(true, retrievedScriptSig.getChunks().get(2).data.length > 0);
    } else {
        Script retrievedScriptSig = provider.getRskTxsWaitingForSignatures().get(keccak256).getInput(0)
                .getScriptSig();
        Assert.assertEquals(4, retrievedScriptSig.getChunks().size());
        boolean expectSignatureToBePersisted = false; // for "InvalidParameters"
        if ("PartiallySigned".equals(expectedResult)) {
            expectSignatureToBePersisted = true;
        }
        Assert.assertEquals(expectSignatureToBePersisted,
                retrievedScriptSig.getChunks().get(1).data.length > 0);
        Assert.assertEquals(false, retrievedScriptSig.getChunks().get(2).data.length > 0);
    }
}

From source file:com.cryptolib.CryptoObject.java

License:Open Source License

/** 
* Constructor./* w w  w.ja  v a2 s.  c  o m*/
* Create a new CryptoObject with encryption asymmetric elliptic curve encryption keypair 
* and digital sign asymmetric elliptic curve keypair.
* curve specificies elliptic curve for encryption scheme and sign algorithm e.g. "curve25519"
* enc_algorithm must be an implemented elliptic curve encryption algorithm e.g. "ECDH"
* shortAuthenticationStringSize must be a positive number, that represents the short authentication byte length.
* iv_size must be positiv, byte size of iv for encryption scheme
* tag_size must be positiv, byte size of tag for encryption scheme
*/
public CryptoObject(String curve, String enc_algorithm, int shortAuthenticationStringSize, int iv_size,
        int tag_size) throws CryptoSocketException {
    if (0 >= shortAuthenticationStringSize || 0 >= iv_size || 0 >= tag_size) {
        throw new CryptoSocketException(
                "shortAuthenticationStringSize,iv_size and tag_size must be a positive number!");
    }

    try {
        X9ECParameters ecP = CustomNamedCurves.getByName(curve);
        org.bouncycastle.jce.spec.ECParameterSpec ecGenSpec = new org.bouncycastle.jce.spec.ECParameterSpec(
                ecP.getCurve(), ecP.getG(), ecP.getN(), ecP.getH(), ecP.getSeed());
        this.provider = new BouncyCastleProvider();
        KeyPairGenerator g = KeyPairGenerator.getInstance(enc_algorithm, this.provider);
        this.random = new SecureRandom();
        g.initialize(ecGenSpec, this.random);
        this.encKeypair = g.generateKeyPair();

        if (this.encKeypair == null) {
            throw new CryptoSocketException("Unable to create new key pair!");
        }

        this.OOB = new byte[shortAuthenticationStringSize];
        this.random.nextBytes(this.OOB);
    } catch (NoSuchAlgorithmException nsa) {
        throw new CryptoSocketException("Algorithm is not supported!");
    } catch (InvalidAlgorithmParameterException iap) {
        throw new CryptoSocketException("Wrong parameter for algorithm!");
    }

    this.enc_algorithm = enc_algorithm;
    this.curve = curve;
    this.iv_size = iv_size;
    this.tag_size = tag_size;
}

From source file:com.cryptolib.CryptoObject.java

License:Open Source License

/**
* Open commitment and extract message to create shared secret.
*//*  w w w. ja  v a  2s . c  o m*/
public void openCommitmentAndCreateSharedSecret(byte[] decommitment)
        throws CryptoSocketException, InvalidKeyException, NoSuchAlgorithmException {
    this.cc.open(decommitment);

    try {
        BCECPublicKey mypk = (BCECPublicKey) (this.encKeypair.getPublic());
        int publicKeySize = mypk.getQ().getEncoded(true).length - 1;
        byte[] message = this.cc.getOtherMessage();

        if (message.length != publicKeySize + this.OOB.length) {
            throw new CryptoSocketException("Message size is wrong!");
        }

        byte[] otherPK = new byte[publicKeySize + 1];

        //compressed encoding magic byte
        otherPK[0] = (byte) 0x02;
        byte[] otherOOB = new byte[this.OOB.length];
        System.arraycopy(message, 0, otherPK, 1, publicKeySize);
        System.arraycopy(message, publicKeySize, otherOOB, 0, otherOOB.length);
        X9ECParameters ecP = CustomNamedCurves.getByName(curve);
        org.bouncycastle.jce.spec.ECParameterSpec ecGenSpec = new org.bouncycastle.jce.spec.ECParameterSpec(
                ecP.getCurve(), ecP.getG(), ecP.getN(), ecP.getH());
        //ECNamedCurveParameterSpec ecP = ECNamedCurveTable.getParameterSpec(this.curve);
        ECPublicKeySpec pubKey = new ECPublicKeySpec(ecP.getCurve().decodePoint(otherPK), ecGenSpec);
        KeyFactory kf = KeyFactory.getInstance(this.enc_algorithm, new BouncyCastleProvider());
        ECPublicKey pk = (ECPublicKey) kf.generatePublic(pubKey);
        createSharedEncKey(pk);
        mergeOOB(otherOOB);
    } catch (NoSuchAlgorithmException nsa) {
        throw new CryptoSocketException("Algorithm is not supported!");
    } catch (InvalidKeySpecException iks) {
        throw new CryptoSocketException("Wrong parameter for algorithm!");
    }
}

From source file:com.cryptolib.CryptoObject.java

License:Open Source License

/**
* Performs ECDH//from  w w w  . j a v a  2s.  com
*/
public void createSharedEncKey(ECPublicKey key) throws CryptoSocketException {
    try {
        X9ECParameters ecP = CustomNamedCurves.getByName(curve);
        ECDomainParameters ecdp = new ECDomainParameters(ecP.getCurve(), ecP.getG(), ecP.getN(), ecP.getH());
        ECPublicKeyParameters ecpkp = new ECPublicKeyParameters(key.getQ(), ecdp);
        BCECPrivateKey sk = (BCECPrivateKey) this.encKeypair.getPrivate();
        ECPrivateKeyParameters ecskp = new ECPrivateKeyParameters(sk.getD(), ecdp);
        ECDHCBasicAgreement ba = new ECDHCBasicAgreement();
        ba.init(ecskp);
        byte[] byteSharedSecret = ba.calculateAgreement(ecpkp).toByteArray();
        byte[] byteSharedSecretSecond = new byte[byteSharedSecret.length / 2];
        byte[] byteSharedSecretFirst = new byte[byteSharedSecret.length / 2];
        System.arraycopy(byteSharedSecret, 0, byteSharedSecretSecond, 0, byteSharedSecretSecond.length);
        System.arraycopy(byteSharedSecret, byteSharedSecretSecond.length, byteSharedSecretFirst, 0,
                byteSharedSecretFirst.length);
        this.sharedSecretFirst = new SecretKeySpec(byteSharedSecretFirst, "AES");
        this.sharedSecretSecond = new SecretKeySpec(byteSharedSecretSecond, "AES");
        this.has_symmetric_key = true;
        this.enc = Cipher.getInstance("AES/GCM/NoPadding");
        this.dec = Cipher.getInstance("AES/GCM/NoPadding");
    } catch (IllegalStateException is) {
        throw new CryptoSocketException("unable to create shared encryption key, wrong state!");
    } catch (NoSuchAlgorithmException nsa) {
        throw new CryptoSocketException("Encryption algorithm not found!");
    } catch (NoSuchPaddingException nsp) {
        throw new CryptoSocketException("Invalid padding algorithm!");
    }
}

From source file:com.distrimind.util.crypto.ASymmetricEncryptionType.java

License:Open Source License

static org.bouncycastle.jce.spec.ECParameterSpec getCurve25519() {

    if (curve25519 == null) {
        X9ECParameters ecP = CustomNamedCurves.getByName("curve25519");
        // ECParameterSpec curve25519 = ECNamedCurveTable.getParameterSpec(algorithm);
        curve25519 = new org.bouncycastle.jce.spec.ECParameterSpec(ecP.getCurve(), ecP.getG(), ecP.getN(),
                ecP.getH(), ecP.getSeed());
    }//from  w w  w .ja  va 2 s.  c  o m
    return curve25519;
}

From source file:com.github.horrorho.inflatabledonkey.crypto.ec.ECAssistant.java

License:Open Source License

public static int fieldLength(X9ECParameters x9ECParameters) {
    return fieldLength(x9ECParameters.getCurve());
}

From source file:com.github.horrorho.inflatabledonkey.crypto.ec.ECAssistant.java

License:Open Source License

public static ECDomainParameters ecDomainParametersFrom(X9ECParameters x9ECParameters) {
    return new ECDomainParameters(x9ECParameters.getCurve(), x9ECParameters.getG(), x9ECParameters.getN(),
            x9ECParameters.getH(), x9ECParameters.getSeed());
}

From source file:com.github.horrorho.inflatabledonkey.crypto.ec.ECCurvePoint.java

License:Open Source License

public static Optional<ECCurvePoint> create(BigInteger x, BigInteger y, String curveName) {
    X9ECParameters x9ECParameters = ECAssistant.x9ECParameters(curveName);
    ECPoint Q = x9ECParameters.getCurve().createPoint(x, y);

    if (!Q.isValid()) {
        logger.warn("-- create() - bad Q: {} curve: {}", Q, curveName);
        return Optional.empty();
    }//from  www  .j a v a2 s  . c  om

    ECCurvePoint point = new ECCurvePoint(Q, curveName, x9ECParameters);
    return Optional.of(point);
}

From source file:com.github.horrorho.inflatabledonkey.crypto.ec.key.imports.ECPrivateKeyImportCompact.java

License:Open Source License

@Override
public Optional<ECPrivateKey> importKey(String curveName, byte[] data) {
    X9ECParameters x9ECParameters = ECAssistant.x9ECParameters(curveName);
    int fieldLength = ECAssistant.fieldLength(x9ECParameters);
    if (fieldLength(data.length) != fieldLength) {
        logger.warn("-- importKey() - bad data length: {} curve: {} data:0x{}", data.length, curveName,
                Hex.toHexString(data));// ww w . java2  s  .c  o  m
    }

    BigInteger x = BigIntegers.fromUnsignedByteArray(data, 0, fieldLength);
    BigInteger y = ECPointsCompact.y(x9ECParameters.getCurve(), x);
    BigInteger d = BigIntegers.fromUnsignedByteArray(data, fieldLength, fieldLength);

    return ECKeyFactories.privateKeyFactory().createECPrivateKey(x, y, d, curveName);
}