Example usage for org.bouncycastle.math.ec ECPoint add

List of usage examples for org.bouncycastle.math.ec ECPoint add

Introduction

In this page you can find the example usage for org.bouncycastle.math.ec ECPoint add.

Prototype

public abstract ECPoint add(ECPoint b);

Source Link

Usage

From source file:ACNS.thresholdDSA.sign.PlayerSigner.java

License:Apache License

@SuppressWarnings("deprecation")
public Round5Message round5(Round4Message... round4Messages) {

    // check rI and wI commitments. We are assuming that the players
    // messages are presented in the same order for consecutive
    // rounds. Otherwise, the verification will fail.
    for (int i = 0; i < round4Messages.length; i++) {
        if (!MultiTrapdoorCommitment.checkcommitment(round3messages[i].riWiCommitment,
                round4Messages[i].openRiWi, nmmpk)) {
            aborted = true;//from w w w.j  a  va2s  .  com
        }
    }

    // verify Everyone else's Zkp_i2
    for (Round4Message message : round4Messages) {
        if (!message.zkp2.verify(params, BitcoinParams.CURVE,
                BitcoinParams.CURVE.getCurve().decodePoint(message.openRiWi.getSecrets()[0].toByteArray()), u,
                message.openRiWi.getSecrets()[1])) {
            aborted = true;
        }
    }

    w = wI;
    for (int i = 0; i < round4Messages.length; i++) {
        w = paillierPublicKey.add(w, round4Messages[i].openRiWi.getSecrets()[1]);
    }

    ECPoint R = rI;
    for (int i = 0; i < round4Messages.length; i++) {
        R = R.add(BitcoinParams.CURVE.getCurve()
                .decodePoint(round4Messages[i].openRiWi.getSecrets()[0].toByteArray()));
    }

    r = R.getX().toBigInteger().mod(BitcoinParams.q);
    wShare = pI.decrypt(w);

    if (aborted) {
        return null;
    } else {
        return new Round5Message(wShare);
    }

}

From source file:com.example.quangadmin.smsencrypfinal.Khoigiaima.Makhoa.java

/**
 * @return the encryptext//from ww  w .jav a 2s. com
 */
public void Makhoa2(byte[] plaintext, ECPoint PublicKEYReceiver, BigInteger PrivateKEYSender) {
    BigInteger m;
    BigInteger r;
    BigInteger v;
    BigInteger nounce;
    ECPoint kG;
    BigInteger kIver;
    length1 = plaintext.length;
    byte[] c = new byte[1 + length1];
    int position = 0;
    c[position] = (byte) length1;
    position += 1;
    System.arraycopy(plaintext, 0, c, position, length1);

    // lay key AES K1 theo hash ban ro~ roi lay K1 ma hoa ban ro tao ra m
    BigInteger K1 = new BigInteger(256, new Random());
    ECPoint Pm = ecc.getG().multiply(K1);
    aes.Encryp(c, new SHA256().SHA256(Pm));
    m = new BigInteger(aes.getEncryptext());

    //Tao chu ky so tren m
    do {
        do {
            nounce = ecc.getNounce();
            kG = ecc.getG().multiply(nounce);
            r = kG.getX().toBigInteger().mod(ecc.getQ());
        } while (r.equals(BigInteger.ZERO));
        kIver = nounce.modInverse(ecc.getQ());
        v = kIver.multiply((m.add(PrivateKEYSender.multiply(r))));
    } while (v.equals(BigInteger.ZERO));

    // Ma hoa key AES K1 theo ECC P-384 xuat vao Pc
    ECPoint kPa = PublicKEYReceiver.multiply(nounce);

    // Chuan bi cho vao goi tao byte
    this.encryptext = aes.getEncryptext();
    this.Pc1 = kG;
    this.Pc2 = Pm.add(kPa);
    this.rr = r;
    this.vv = v;
}

From source file:com.vvote.verifier.component.votePacking.VotePackingVerifier.java

License:Open Source License

/**
 * Packs plaintext ids together using the provided packing size
 * /*from   w  w w. ja v  a2 s  . c o  m*/
 * @param preferences
 * @param packingSize
 * @return a list of packed plaintext ids
 */
private List<ECPoint> packPlaintexts(SortedMap<Integer, ECPoint> preferences, int packingSize) {
    int packingPreference = 0;
    ECPoint currentId = null;
    ECPoint currentPacking = null;
    List<ECPoint> currentPackedList = null;

    currentPackedList = new ArrayList<ECPoint>();

    // loop over preferences
    for (Integer pref : preferences.keySet()) {

        // increment the packing preference which ranges from 1 to packing
        // size
        packingPreference++;

        // gets the specific cipher
        currentId = preferences.get(pref);

        // multiply by the packing preference number (NOT the actual
        // preference number)
        currentId = currentId.multiply(BigInteger.valueOf(packingPreference));

        // either store this current cipher
        if (currentPacking == null) {
            currentPacking = currentId;
        } else {
            // or add to the previous packing
            currentPacking = currentPacking.add(currentId);
        }

        // packing preference needs to be reset if it equals the maximum
        // packing size
        if (packingPreference == packingSize) {
            packingPreference = 0;

            currentPackedList.add(currentPacking);
            currentPacking = null;
        }
    }

    if (currentPacking != null) {
        currentPackedList.add(currentPacking);
    }

    return currentPackedList;
}

From source file:edu.biu.scapi.primitives.dlog.bc.BcAdapterDlogEC.java

License:Open Source License

public GroupElement multiplyGroupElements(GroupElement groupElement1, GroupElement groupElement2)
        throws IllegalArgumentException {

    //if the GroupElements don't match the DlogGroup, throws exception
    if (!(checkInstance(groupElement1))) {
        throw new IllegalArgumentException("groupElement doesn't match the DlogGroup");
    }/*from  w w  w  .  ja  v  a2  s  . com*/
    if (!(checkInstance(groupElement2))) {
        throw new IllegalArgumentException("groupElement doesn't match the DlogGroup");
    }

    //if one of the points is the infinity point, the second one is the multiplication result
    if (((ECPointBc) groupElement1).isInfinity()) {
        return groupElement2;
    }
    if (((ECPointBc) groupElement2).isInfinity()) {
        return groupElement1;
    }

    //gets the ECPoints
    ECPoint point1 = ((ECPointBc) groupElement1).getPoint();
    ECPoint point2 = ((ECPointBc) groupElement2).getPoint();

    /* 
     * BC treats EC as additive group while we treat that as multiplicative group. 
     * Therefore, multiply point is add.
     */
    ECPoint result = point1.add(point2);

    //creates GroupElement from the result
    return createPoint(result);

}

From source file:l2fheBased.thresholdDSA.sign.PlayerSigner.java

License:Apache License

public Round3Message round3(Round2Message... round2Messages) {
    // check commitments. We are assuming that the players
    // messages are
    // presented in the same order for consecutive rounds. Otherwise, the
    // verification
    // will fail.
    ECPoint R = myRI;
    u = myUI;/*from  w w w  . j  a v a 2  s  .co  m*/
    v = myVI;
    w = myWI;

    for (int i = 0; i < round2Messages.length; i++) {

        // from player i
        BigInteger[] playerIsSecrets = round2Messages[i].openRiUiViWi.getSecrets();
        ECPoint rI = BitcoinParams.CURVE.getCurve().decodePoint(playerIsSecrets[0].toByteArray());
        L1Ciphertext uI = new L1Ciphertext(playerIsSecrets[1], playerIsSecrets[2]);
        L1Ciphertext vI = new L1Ciphertext(playerIsSecrets[3], playerIsSecrets[4]);
        L1Ciphertext wI = new L1Ciphertext(playerIsSecrets[5], playerIsSecrets[6]);

        // check commitments

        if (!MultiTrapdoorCommitment.checkcommitment(round1messages[i].riUiViWiCommitment,
                round2Messages[i].openRiUiViWi, nmmpk)) {
            aborted = true;
        }

        // verify ZKPs
        if (!round2Messages[i].zkp.verify(params, BitcoinParams.CURVE, rI, vI, uI, wI)) {
            aborted = true;
        }

        R = R.add(rI);
        u = paillierPublicKey.add(u, uI);
        v = paillierPublicKey.add(v, vI);
        w = paillierPublicKey.add(w, wI);

    }

    L1Ciphertext wq = paillierPublicKey.cMult(w, BitcoinParams.q);
    r = R.getX().toBigInteger().mod(BitcoinParams.q);
    L2Ciphertext uv = paillierPublicKey.mult(u, v);
    L2Ciphertext z = paillierPublicKey.add(wq, uv);
    etaShare = pI.decrypt(z);
    if (aborted) {
        return null;
    } else {
        return new Round3Message(etaShare);
    }

}

From source file:org.cryptoworkshop.ximix.client.verify.ECDecryptionChallengeVerifier.java

License:Apache License

/**
 * Verify that the decryption challenge transcript is valid, throwing an exception if an issue is found..
 *
 * @throws TranscriptVerificationException on verification failure.
 *///w w w.  j a  v a2 s  .co m
public void verify() throws TranscriptVerificationException {
    ASN1InputStream aIn = new ASN1InputStream(logStream);
    ASN1InputStream resultIn = new ASN1InputStream(resultStream);
    ASN1InputStream lastIn = new ASN1InputStream(lastStageStream);

    try {
        int messageIndex = -1;
        ECPair[] encPairs = null;

        ASN1Object obj;
        while ((obj = aIn.readObject()) != null) {
            ChallengeLogMessage logMessage = ChallengeLogMessage.getInstance(obj);

            ECPoint[] sourceMessage = logMessage.getSourceMessage();
            ECDecryptionProof[] proofs = logMessage.getProofs();

            ECPublicKeyParameters currentPubKey = (ECPublicKeyParameters) PublicKeyFactory
                    .createKey(logMessage.getKeyInfo());
            if (!isSameParameters(pubKey.getParameters(), currentPubKey.getParameters())) {
                throw new TranscriptVerificationException(
                        "Log message indicates inconsistent public key parameters.");
            }

            if (messageIndex != logMessage.getIndex()) {
                if (activePeers.length != 0) {
                    LagrangeWeightCalculator weightCalculator = new LagrangeWeightCalculator(maxSequenceNo + 1,
                            pubKey.getParameters().getN());

                    ECPoint accumulatedQ = null;

                    BigInteger[] weights = weightCalculator.computeWeights(activePeers);

                    // verify the partial public keys represent the one we have.
                    for (int i = 0; i != weights.length; i++) {
                        if (weights[i] != null) {
                            if (accumulatedQ == null) {
                                accumulatedQ = activePeers[i].getQ().multiply(weights[i]);
                            } else {
                                accumulatedQ = accumulatedQ.add(activePeers[i].getQ().multiply(weights[i]));
                            }
                        }
                    }

                    if (!pubKey.getQ().equals(accumulatedQ)) {
                        throw new TranscriptVerificationException(
                                "Log message indicates inconsistent public key.");
                    }

                    // verify the partial decrypts result in the final message

                    int len = activeMsgParts[0].length;
                    for (int i = 1; i != activeMsgParts.length; i++) {
                        if (activeMsgParts[i].length != len) {
                            throw new TranscriptVerificationException("Partial decrypt length mismatch");
                        }
                    }

                    int baseIndex = 0;
                    for (int i = 0; i != activeMsgParts.length; i++) {
                        if (activeMsgParts[i] != null) {
                            baseIndex = i;
                            break;
                        }
                    }

                    BigInteger baseWeight = weights[baseIndex];

                    ECPoint[] decryptions = reassemblePoints(activeMsgParts, encPairs, weights, baseIndex,
                            baseWeight);

                    ECPoint[] recordedDecrypts = PointSequence
                            .getInstance(pubKey.getParameters().getCurve(), resultIn.readObject())
                            .getECPoints();

                    if (!Arrays.areEqual(decryptions, recordedDecrypts)) {
                        throw new TranscriptVerificationException(
                                "Recorded decrypts do not match partial ones.");
                    }

                    // reset the peers array.
                    for (int i = 0; i != activePeers.length; i++) {
                        activePeers[i] = null;
                    }
                    for (int i = 0; i != activeMsgParts.length; i++) {
                        activeMsgParts[i] = null;
                    }
                } else if (messageIndex != -1) {
                    throw new TranscriptVerificationException("Nothing to verify!");
                }

                messageIndex = logMessage.getIndex();
                PostedMessage pM = PostedMessage.getInstance(lastIn.readObject());
                encPairs = PairSequence.getInstance(pubKey.getParameters().getCurve(), pM.getMessage())
                        .getECPairs();
            }

            addPeer(logMessage.getSequenceNo(), currentPubKey, sourceMessage);

            if (!logMessage.hasPassed()) {
                throw new TranscriptVerificationException("Log message indicates challenge did not pass.");
            }

            for (int i = 0; i != proofs.length; i++) {
                if (!proofs[i].isVerified(activePeers[logMessage.getSequenceNo()], encPairs[i].getX(),
                        sourceMessage[i])) {
                    throw new TranscriptVerificationException(
                            "Proof results do not match combined source message and cipher text.");
                }
            }
        }
    } catch (TranscriptVerificationException e) {
        throw e;
    } catch (Exception e) {
        throw new TranscriptVerificationException(
                "Exception validating decryption challenge transcript: " + e.getMessage(), e);
    }
}

From source file:org.cryptoworkshop.ximix.common.crypto.threshold.ECCommittedSecretShare.java

License:Apache License

/**
 * Return the commitment value for a particular share number.
 *
 * @param shareNumber the number of this share.
 * @return the EC point representing the committed value.
 *///w  ww  . j  av  a  2  s.  c om
public ECPoint getCommitment(int shareNumber) {
    ECPoint commitment = commitmentFactors[0];
    BigInteger alpha = BigInteger.valueOf(shareNumber + 1); // note: this is related to a value.
    BigInteger powAplha = BigInteger.ONE;

    for (int k = 1; k < commitmentFactors.length; k++) {
        powAplha = powAplha.multiply(alpha);

        commitment = commitment.add(commitmentFactors[k].multiply(powAplha));
    }

    return commitment;
}

From source file:org.cryptoworkshop.ximix.node.crypto.test.BasicShamirSharingTest.java

License:Apache License

private void doTest(ECDomainParameters domainParams, AsymmetricCipherKeyPair[] kps, int threshold,
        boolean shouldPass, int... missing) {
    int numberOfPeers = kps.length;

    // create the splitter for the peers/threshold over the order of the curve.
    ShamirSecretSplitter secretSplitter = new ShamirSecretSplitter(numberOfPeers, threshold,
            domainParams.getN(), new SecureRandom());

    // Having created a private key the server creates shares of that
    // private key. It would keep one share for itself and sends the others
    // shares to the other servers.
    BigInteger[][] privateKeyShares = new BigInteger[numberOfPeers][];
    BigInteger[] finalPrivateKeyShares = new BigInteger[numberOfPeers];
    for (int i = 0; i < numberOfPeers; i++) {
        privateKeyShares[i] = secretSplitter.split(((ECPrivateKeyParameters) kps[i].getPrivate()).getD())
                .getShares();/*from   w  ww . j av  a2s . c om*/
    }

    // Simulates distributing shares and combining them
    for (int i = 0; i < numberOfPeers; i++) {
        finalPrivateKeyShares[i] = privateKeyShares[0][i];
        for (int j = 1; j < numberOfPeers; j++) {
            finalPrivateKeyShares[i] = finalPrivateKeyShares[i].add(privateKeyShares[j][i]);
        }
    }

    ECPoint pubPoint = ((ECPublicKeyParameters) kps[0].getPublic()).getQ();

    for (int i = 1; i < numberOfPeers; i++) {
        pubPoint = pubPoint.add(((ECPublicKeyParameters) kps[i].getPublic()).getQ());
    }

    ECPublicKeyParameters jointPub = new ECPublicKeyParameters(pubPoint, domainParams);

    // Create a random plaintext
    ECPoint plaintext = generatePoint(domainParams, new SecureRandom());

    // Encrypt it using the joint public key
    ECEncryptor enc = new ECElGamalEncryptor();

    enc.init(new ParametersWithRandom(jointPub, new SecureRandom()));

    ECPair cipherText = enc.encrypt(plaintext);

    // do partial decrypts
    ECPoint[] partialDecs = new ECPoint[numberOfPeers];

    for (int i = 0; i < numberOfPeers; i++) {
        partialDecs[i] = cipherText.getX().multiply(finalPrivateKeyShares[i]);
    }

    // simulate missing peers
    for (int i = 0; i != missing.length; i++) {
        partialDecs[missing[i]] = null;
    }

    // decryption step
    LagrangeWeightCalculator lagrangeWeightCalculator = new LagrangeWeightCalculator(numberOfPeers,
            domainParams.getN());

    BigInteger[] weights = lagrangeWeightCalculator.computeWeights(partialDecs);

    // weighting
    ECPoint weightedDecryption = partialDecs[0].multiply(weights[0]);
    for (int i = 1; i < weights.length; i++) {
        if (partialDecs[i] != null) {
            weightedDecryption = weightedDecryption.add(partialDecs[i].multiply(weights[i]));
        }
    }

    // Do final decryption to recover plaintext ECPoint
    ECPoint decrypted = cipherText.getY().add(weightedDecryption.negate());

    Assert.assertEquals(shouldPass, plaintext.equals(decrypted));
}

From source file:org.cryptoworkshop.ximix.node.crypto.test.NewDKGTest.java

License:Apache License

private void doTest(ECDomainParameters domainParams, AsymmetricCipherKeyPair[] kps, int threshold,
        boolean shouldPass, int... missing) {
    int numberOfPeers = kps.length;

    // create the splitter for the peers/threshold over the order of the curve.
    ECPoint hVal = domainParams.getG().multiply(getRandomInteger(domainParams.getN(), new SecureRandom()));
    ECNewDKGSecretSplitter secretSplitter = new ECNewDKGSecretSplitter(numberOfPeers, threshold, hVal,
            domainParams, new SecureRandom());

    // Having created a private key the server creates shares of that
    // private key. It would keep one share for itself and sends the others
    // shares to the other servers.
    ECCommittedSplitSecret[] privateKeyShares = new ECCommittedSplitSecret[numberOfPeers];
    BigInteger[] finalPrivateKeyShares = new BigInteger[numberOfPeers];
    for (int i = 0; i < numberOfPeers; i++) {
        privateKeyShares[i] = secretSplitter.split(((ECPrivateKeyParameters) kps[i].getPrivate()).getD());
    }//from w w w .j  a  v  a2  s . c om

    // Simulates distributing shares and combining them
    for (int i = 0; i < numberOfPeers; i++) {
        finalPrivateKeyShares[i] = privateKeyShares[0].getShares()[i];
        for (int j = 1; j < numberOfPeers; j++) {
            finalPrivateKeyShares[i] = finalPrivateKeyShares[i].add(privateKeyShares[j].getShares()[i]);
        }
    }

    //
    // check the commitment values.
    //
    for (int i = 0; i != numberOfPeers; i++) {
        ECCommittedSecretShare[] shares = privateKeyShares[i].getCommittedShares();
        for (int j = 0; j != numberOfPeers; j++) {
            Assert.assertTrue(shares[j].isRevealed(j, domainParams, hVal));
        }
    }

    ECPoint pubPoint = ((ECPublicKeyParameters) kps[0].getPublic()).getQ();

    for (int i = 1; i < numberOfPeers; i++) {
        pubPoint = pubPoint.add(((ECPublicKeyParameters) kps[i].getPublic()).getQ());
    }

    ECPublicKeyParameters jointPub = new ECPublicKeyParameters(pubPoint, domainParams);

    //
    // check the public key commitment values.
    //
    for (int i = 0; i != numberOfPeers; i++) {
        BigInteger[] aCoefficients = privateKeyShares[i].getCoefficients();
        ECPoint[] qCommitments = new ECPoint[aCoefficients.length];

        for (int k = 0; k != qCommitments.length; k++) {
            qCommitments[k] = domainParams.getG().multiply(aCoefficients[k]);
        }

        for (int j = 0; j != numberOfPeers; j++) {
            ECPoint val = qCommitments[0];
            for (int k = 1; k != qCommitments.length; k++) {
                val = val.add(qCommitments[k].multiply(BigInteger.valueOf(j + 1).pow(k)));
            }

            Assert.assertEquals(domainParams.getG().multiply(privateKeyShares[i].getShares()[j]), val);
        }
    }

    // Create a random plaintext
    ECPoint plaintext = generatePoint(domainParams, new SecureRandom());

    // Encrypt it using the joint public key
    ECEncryptor enc = new ECElGamalEncryptor();

    enc.init(new ParametersWithRandom(jointPub, new SecureRandom()));

    ECPair cipherText = enc.encrypt(plaintext);

    // do partial decrypts
    ECPoint[] partialDecs = new ECPoint[numberOfPeers];

    for (int i = 0; i < numberOfPeers; i++) {
        partialDecs[i] = cipherText.getX().multiply(finalPrivateKeyShares[i]);
    }

    // simulate missing peers
    for (int i = 0; i != missing.length; i++) {
        partialDecs[missing[i]] = null;
    }

    // decryption step
    LagrangeWeightCalculator lagrangeWeightCalculator = new LagrangeWeightCalculator(numberOfPeers,
            domainParams.getN());

    BigInteger[] weights = lagrangeWeightCalculator.computeWeights(partialDecs);

    // weighting
    ECPoint weightedDecryption = partialDecs[0].multiply(weights[0]);
    for (int i = 1; i < weights.length; i++) {
        if (partialDecs[i] != null) {
            weightedDecryption = weightedDecryption.add(partialDecs[i].multiply(weights[i]));
        }
    }

    // Do final decryption to recover plaintext ECPoint
    ECPoint decrypted = cipherText.getY().add(weightedDecryption.negate());

    Assert.assertEquals(shouldPass, plaintext.equals(decrypted));
}

From source file:org.hyperledger.common.BouncyCastleCrypto.java

License:Apache License

@Override
public byte[] getPublicKeyAtOffset(byte[] publicKey, byte[] offset) {
    BigInteger offsetInt = new BigInteger(publicKey);
    boolean invert = false;

    if (offsetInt.compareTo(BigInteger.ZERO) < 0) {
        invert = true;/*from www .ja v  a  2s  .com*/
        offsetInt = offsetInt.abs();
    }

    ECPoint oG = curve.getG().multiply(offsetInt);

    if (invert) {
        oG = oG.negate();
    }

    return oG.add(curve.getCurve().decodePoint(publicKey)).getEncoded(true);
}