Example usage for org.bouncycastle.crypto.ec ECElGamalEncryptor ECElGamalEncryptor

List of usage examples for org.bouncycastle.crypto.ec ECElGamalEncryptor ECElGamalEncryptor

Introduction

In this page you can find the example usage for org.bouncycastle.crypto.ec ECElGamalEncryptor ECElGamalEncryptor.

Prototype

ECElGamalEncryptor

Source Link

Usage

From source file:org.cryptoworkshop.ximix.demo.admin.Main.java

License:Apache License

public static void main(String[] args) throws Exception {
    Security.addProvider(new BouncyCastleProvider());

    XimixRegistrar adminRegistrar = XimixRegistrarFactory.createAdminServiceRegistrar(new File(args[0]),
            new EventNotifier() {
                @Override//from   w w w  .j  av a  2 s  . c  om
                public void notify(Level level, Throwable throwable) {
                    System.err.print(level + " " + throwable.getMessage());
                    throwable.printStackTrace(System.err);
                }

                @Override
                public void notify(Level level, Object detail) {
                    System.err.println(level + " " + detail.toString());
                }

                @Override
                public void notify(Level level, Object detail, Throwable throwable) {
                    System.err.println(level + " " + detail.toString());
                    throwable.printStackTrace(System.err);
                }
            });

    PEMParser pParse = new PEMParser(new FileReader(args[1]));

    X509Certificate trustAnchor = new JcaX509CertificateConverter().setProvider("BC")
            .getCertificate((X509CertificateHolder) pParse.readObject());

    pParse.close();

    KeyGenerationService keyGenerationService = adminRegistrar.connect(KeyGenerationService.class);

    byte[] encPubKey = keyGenerationService.fetchPublicKey("ECENCKEY");

    if (encPubKey == null) {
        KeyGenerationOptions keyGenOptions = new KeyGenerationOptions.Builder(Algorithm.EC_ELGAMAL, "secp256r1")
                .withThreshold(4).withNodes("A", "B", "C", "D", "E").build();

        encPubKey = keyGenerationService.generatePublicKey("ECENCKEY", keyGenOptions);
    }

    byte[] sigPubKey = keyGenerationService.fetchPublicKey("ECSIGKEY");

    if (sigPubKey == null) {
        KeyGenerationOptions keyGenOptions = new KeyGenerationOptions.Builder(Algorithm.ECDSA, "secp256r1")
                .withThreshold(2).withNodes("A", "B", "C", "D", "E").build();

        sigPubKey = keyGenerationService.generatePublicKey("ECSIGKEY", keyGenOptions);
    }

    byte[] blsPubKey = keyGenerationService.fetchPublicKey("BLSSIGKEY");

    if (blsPubKey == null) {
        KeyGenerationOptions keyGenOptions = new KeyGenerationOptions.Builder(Algorithm.BLS,
                "d62003-159-158.param").withThreshold(3).withNodes("A", "B", "C", "D", "E").build();

        blsPubKey = keyGenerationService.generatePublicKey("BLSSIGKEY", keyGenOptions);
    }

    CommandService commandService = adminRegistrar.connect(CommandService.class);

    if (!commandService.isBoardExisting("FRED")) {
        commandService.createBoard("FRED", new BoardCreationOptions.Builder("B").withBackUpHost("A").build());
    }

    UploadService client = adminRegistrar.connect(UploadService.class);

    final ECPublicKeyParameters pubKey = (ECPublicKeyParameters) PublicKeyFactory.createKey(encPubKey);

    final ECElGamalEncryptor encryptor = new ECElGamalEncryptor();

    encryptor.init(pubKey);

    // set up 100 "random" messages we use a seeded random here to make reload testing easier.
    SecureRandom pointRandom = new SecureRandom() {
        int counter = 1;

        public void nextBytes(byte[] data) {
            data[0] = (byte) counter++;
        }
    };

    final int numMessages = 100;

    final Set<ECPoint> part1 = new HashSet<>();
    final Set<ECPoint> part2 = new HashSet<>();

    final ECPoint[] plainText1 = new ECPoint[numMessages];
    final ECPoint[] plainText2 = new ECPoint[numMessages];
    for (int i = 0; i != plainText1.length; i++) {
        plainText1[i] = generatePoint(pubKey.getParameters(), pointRandom);
        plainText2[i] = generatePoint(pubKey.getParameters(), pointRandom);

        part1.add(plainText1[i]);
        part2.add(plainText2[i]);

        PairSequence encrypted = new PairSequence(
                new ECPair[] { encryptor.encrypt(plainText1[i]), encryptor.encrypt(plainText2[i]) }); // two column ballot

        client.uploadMessage("FRED", encrypted.getEncoded());
    }

    final Set<ECPoint> verifiedPart1 = new HashSet<>(part1);
    final Set<ECPoint> verifiedPart2 = new HashSet<>(part2);

    // board is hosted on "B" move to "A" then to "C" then back to "B"

    final CountDownLatch shuffleLatch = new CountDownLatch(1);
    final Map<String, byte[]> seedCommitmentMap = new HashMap<>();

    ShuffleOperationListener shuffleListener = new ShuffleOperationListener() {
        @Override
        public void commit(Map<String, byte[]> seedCommitments) {
            seedCommitmentMap.putAll(seedCommitments);
        }

        @Override
        public void status(ShuffleStatus statusObject) {
            System.err.println("status: " + statusObject.getMessage());
        }

        @Override
        public void completed() {
            shuffleLatch.countDown();
            System.err.println("done");
        }

        @Override
        public void failed(ShuffleStatus errorObject) {
            shuffleLatch.countDown();
            System.err.println("failed: " + errorObject.getMessage());
        }
    };

    Operation<ShuffleOperationListener> shuffleOp = commandService.doShuffleAndMove("FRED",
            new ShuffleOptions.Builder(MultiColumnRowTransform.NAME).withKeyID("ECENCKEY").build(),
            shuffleListener, "A", "A", "C", "C", "E");

    shuffleLatch.await();

    // Commented out as this service not available on VEC
    //        final CountDownLatch downloadLatch = new CountDownLatch(1);
    //
    //        final ByteArrayOutputStream challengeLogStream = new ByteArrayOutputStream();
    //
    //        Operation<DownloadOperationListener> op = commandService.downloadBoardContents("FRED",
    //                                                                                       new DownloadOptions.Builder()
    //                                                                                              .withKeyID("ECENCKEY")
    //                                                                                              .withThreshold(4)
    //                                                                                              .withNodes("A", "B", "C", "D")
    //                                                                                              .build(), new DownloadOperationListener()
    //        {
    //            int counter = 0;
    //
    //            @Override
    //            public void messageDownloaded(int index, byte[] message, List<byte[]> proofs)
    //            {
    //                PointSequence decrypted = PointSequence.getInstance(pubKey.getParameters().getCurve(), message);
    //
    //                if (part1.remove(decrypted.getECPoints()[0]) && part2.remove(decrypted.getECPoints()[1]))
    //                {
    //                    System.err.println(index + " message downloaded successfully");
    //                }
    //                else
    //                {
    //                    System.err.println(index + " decryption failed");
    //                }
    //
    //                for (int i = 0; i != proofs.size(); i++)
    //                {
    //                    try
    //                    {
    //                        challengeLogStream.write(proofs.get(i));
    //                    }
    //                    catch (IOException e)
    //                    {
    //                        e.printStackTrace();
    //                    }
    //                }
    //                counter++;
    //            }
    //
    //            @Override
    //            public void completed()
    //            {
    //                downloadLatch.countDown();
    //                System.err.println("completed " + (numMessages == counter));
    //            }
    //
    //            @Override
    //            public void status(String statusObject)
    //            {
    //                System.err.println("status: " + statusObject);
    //            }
    //
    //            @Override
    //            public void failed(String errorObject)
    //            {
    //                downloadLatch.countDown();
    //                System.err.println("failed");
    //            }
    //        });
    //
    //        downloadLatch.await();
    //
    //        //
    //        // verify the decryption challenge log.
    //        //
    //        ECDecryptionChallengeVerifier challengeVerifier = new ECDecryptionChallengeVerifier(pubKey, new ByteArrayInputStream(challengeLogStream.toByteArray()));
    //
    //        challengeVerifier.verify();

    Map<String, byte[][]> seedAndWitnessesMap = commandService.downloadShuffleSeedsAndWitnesses("FRED",
            shuffleOp.getOperationNumber(), "A", "C", "E");

    SignedDataVerifier signatureVerifier = new SignedDataVerifier(trustAnchor);

    final CountDownLatch transcriptCompleted = new CountDownLatch(1);

    final Map<Integer, byte[]> generalTranscripts = new TreeMap<>();

    ShuffleTranscriptsDownloadOperationListener transcriptListener = new ShuffleTranscriptsDownloadOperationListener() {
        @Override
        public void shuffleTranscriptArrived(long operationNumber, int stepNumber, InputStream transcript) {
            try {
                ByteArrayOutputStream bOut = new ByteArrayOutputStream();
                BufferedInputStream bIn = new BufferedInputStream(transcript);

                int ch;
                while ((ch = bIn.read()) >= 0) {
                    bOut.write(ch);
                }
                bOut.close();

                generalTranscripts.put(stepNumber, bOut.toByteArray());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void completed() {
            transcriptCompleted.countDown();
        }

        @Override
        public void status(String statusObject) {
            //To change body of implemented methods use File | Settings | File Templates.
        }

        @Override
        public void failed(String errorObject) {
            System.err.println("failed: " + errorObject);
            transcriptCompleted.countDown();
        }
    };

    commandService.downloadShuffleTranscripts("FRED", shuffleOp.getOperationNumber(),
            new ShuffleTranscriptOptions.Builder(TranscriptType.GENERAL).build(), transcriptListener, "A", "C",
            "E");

    transcriptCompleted.await();

    LinkIndexVerifier.Builder builder = new LinkIndexVerifier.Builder(numMessages);

    builder.setNetworkSeeds(seedCommitmentMap, seedAndWitnessesMap);

    for (Integer step : generalTranscripts.keySet()) {
        byte[] bytes = generalTranscripts.get(step);

        if (signatureVerifier.signatureVerified(new CMSSignedDataParser(
                new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(), bytes))) {
            builder.addTranscript(new ByteArrayInputStream(bytes));
        } else {
            System.err.println("General commitment check signature failed");
        }
    }

    LinkIndexVerifier linkVerifier = builder.build();

    byte[] challengeSeed = linkVerifier.getChallengeSeed();

    System.err.println("network seed: " + new String(Hex.encode(challengeSeed)));

    for (Integer step : generalTranscripts.keySet()) {
        byte[] bytes = generalTranscripts.get(step);

        if (!signatureVerifier.signatureVerified(new CMSSignedDataParser(
                new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(), bytes))) {
            System.err.println("General commitment check signature failed");
        }
    }

    //
    // added the distributed seed
    //
    final Map<Integer, byte[]> witnessTranscripts = new TreeMap<>();

    final CountDownLatch witnessTranscriptCompleted = new CountDownLatch(1);
    transcriptListener = new ShuffleTranscriptsDownloadOperationListener() {
        @Override
        public void shuffleTranscriptArrived(long operationNumber, int stepNumber, InputStream transcript) {
            try {
                ByteArrayOutputStream bOut = new ByteArrayOutputStream();
                BufferedInputStream bIn = new BufferedInputStream(transcript);

                int ch;
                while ((ch = bIn.read()) >= 0) {
                    bOut.write(ch);
                }
                bOut.close();

                witnessTranscripts.put(stepNumber, bOut.toByteArray());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void completed() {
            witnessTranscriptCompleted.countDown();
        }

        @Override
        public void status(String statusObject) {
            //To change body of implemented methods use File | Settings | File Templates.
        }

        @Override
        public void failed(String errorObject) {
            witnessTranscriptCompleted.countDown();
        }
    };

    commandService
            .downloadShuffleTranscripts("FRED", shuffleOp.getOperationNumber(),
                    new ShuffleTranscriptOptions.Builder(TranscriptType.WITNESSES)
                            .withChallengeSeed(challengeSeed).withPairingEnabled(true).build(),
                    transcriptListener, "A", "C", "E");

    witnessTranscriptCompleted.await();

    for (Integer step : witnessTranscripts.keySet()) {
        byte[] bytes = witnessTranscripts.get(step);

        if (!signatureVerifier.signatureVerified(new CMSSignedDataParser(
                new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(), bytes))) {
            System.err.println("Witness commitment check signature failed");
        }
    }

    //
    // verify the witness transcripts are correctly generated
    //
    for (Integer step : witnessTranscripts.keySet()) {
        byte[] bytes = witnessTranscripts.get(step);

        linkVerifier.verify(step, true, new ByteArrayInputStream(bytes));
    }

    //
    // verify the revealed commitments.
    //
    for (Integer key : witnessTranscripts.keySet()) {
        byte[] transcript = witnessTranscripts.get(key);
        byte[] initialTranscript = generalTranscripts.get(key);
        byte[] nextTranscript = generalTranscripts.get(key + 1);

        ECShuffledTranscriptVerifier verifier = new ECShuffledTranscriptVerifier(pubKey,
                new ByteArrayInputStream(transcript), new ByteArrayInputStream(initialTranscript),
                new ByteArrayInputStream(nextTranscript));

        verifier.verify();
    }

    System.err.println("transcripts verified");

    Map<String, InputStream> streamSeedCommitments = new HashMap<>();
    for (String key : seedCommitmentMap.keySet()) {
        streamSeedCommitments.put(key, new ByteArrayInputStream(seedCommitmentMap.get(key)));
    }

    Map<String, InputStream> streamSeedsAndWitnesses = new HashMap<>();
    for (String key : seedAndWitnessesMap.keySet()) {
        byte[][] sAndW = seedAndWitnessesMap.get(key);
        streamSeedsAndWitnesses.put(key,
                new ByteArrayInputStream(new SeedAndWitnessMessage(sAndW[0], sAndW[1]).getEncoded()));
    }

    Map<Integer, InputStream> streamWitnessTranscripts = new HashMap<>();
    for (Integer key : witnessTranscripts.keySet()) {
        streamWitnessTranscripts.put(key, new ByteArrayInputStream(witnessTranscripts.get(key)));
    }

    Map<Integer, InputStream> streamGeneralTranscripts = new HashMap<>();
    for (Integer key : generalTranscripts.keySet()) {
        streamGeneralTranscripts.put(key, new ByteArrayInputStream(generalTranscripts.get(key)));
    }

    final CountDownLatch shuffleOutputDownloadCompleted = new CountDownLatch(1);

    commandService.downloadShuffleResult("FRED",
            new DownloadShuffleResultOptions.Builder().withKeyID("ECENCKEY").withThreshold(4)
                    .withPairingEnabled(true).withNodes("A", "B", "C", "D", "E").build(),
            streamSeedCommitments, streamSeedsAndWitnesses, streamGeneralTranscripts, streamWitnessTranscripts,
            new DownloadOperationListener() {
                int counter = 0;

                @Override
                public void messageDownloaded(int index, byte[] message, List<byte[]> proofs) {
                    PointSequence decrypted = PointSequence.getInstance(pubKey.getParameters().getCurve(),
                            message);

                    if (verifiedPart1.remove(decrypted.getECPoints()[0])
                            && verifiedPart2.remove(decrypted.getECPoints()[1])) {
                        System.err.println(index + " message downloaded successfully");
                    } else {
                        System.err.println(index + " decryption failed");
                    }
                    counter++;
                }

                @Override
                public void completed() {
                    shuffleOutputDownloadCompleted.countDown();
                    System.err.println("completed " + (numMessages == counter));
                }

                @Override
                public void status(String statusObject) {
                    System.err.println("status: " + statusObject);
                }

                @Override
                public void failed(String errorObject) {
                    shuffleOutputDownloadCompleted.countDown();
                    System.err.println("failed " + errorObject);
                }
            });

    shuffleOutputDownloadCompleted.await();

    keyGenerationService.shutdown();
    client.shutdown();
    commandService.shutdown();

    adminRegistrar.shutdown();
}

From source file:org.cryptoworkshop.ximix.demo.ballot.Main.java

License:Apache License

public static void main(String[] args) throws Exception {
    if (args.length != 3) {
        System.err.println("Usage: Generate mixnet.xml number_of_regions avg_number_of_ballots");
        System.exit(1);/*from w w  w.ja  v  a  2s . c o m*/
    }

    XimixRegistrar adminRegistrar = XimixRegistrarFactory.createAdminServiceRegistrar(new File(args[0]),
            new EventNotifier() {
                @Override
                public void notify(Level level, Throwable throwable) {
                    System.err.print(level + " " + throwable.getMessage());
                    throwable.printStackTrace(System.err);
                }

                @Override
                public void notify(Level level, Object detail) {
                    System.err.println(level + " " + detail.toString());
                }

                @Override
                public void notify(Level level, Object detail, Throwable throwable) {
                    System.err.println(level + " " + detail.toString());
                    throwable.printStackTrace(System.err);
                }
            });

    File outDir = new File("electionData");

    if (!outDir.mkdir()) {
        System.err.println("Unable to create directory \"electionData\"");
        System.exit(1);
    }

    File ballotDir = new File(outDir, "ballots");

    ballotDir.mkdir();

    File candidateDir = new File(outDir, "candidateTables");

    candidateDir.mkdir();

    KeyService keyGenerationService = adminRegistrar.connect(KeyService.class);

    byte[] encPubKey = keyGenerationService.fetchPublicKey("ECENCKEY");

    ECPublicKeyParameters pubKey = (ECPublicKeyParameters) PublicKeyFactory.createKey(encPubKey);

    ECElGamalEncryptor encryptor = new ECElGamalEncryptor();

    encryptor.init(pubKey);

    DecimalFormat fmt = new DecimalFormat("000");

    int count = Integer.parseInt(args[1]);
    int ballotSize = Integer.parseInt(args[2]);

    for (int i = 0; i != count; i++) {
        String baseName = "REGION-" + fmt.format(i) + "_ATL_DEMO";

        generateBallots(ballotDir, candidateDir, baseName, new Random(i), ballotSize, encryptor,
                pubKey.getParameters(), new SecureRandom());
    }

    PackedBallotTableBuilder tableBuilder = new PackedBallotTableBuilder(new byte[20], pubKey.getParameters(),
            20, 3);
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();

    ECPoint paddingPoint = tableBuilder.build(bOut);

    Map<ECPoint, byte[]> packingMap = tableBuilder.getPackingMap();
    Map<Preferences, ECPoint> preferenceMap = new HashMap<>();

    for (ECPoint point : packingMap.keySet()) {
        Preferences pref = new Preferences(packingMap.get(point));

        preferenceMap.put(pref, point);
    }

    FileOutputStream fOut = new FileOutputStream(new File(outDir, "BTL_Table"));

    fOut.write(bOut.toByteArray());

    fOut.close();

    BufferedWriter bWrt = new BufferedWriter(new FileWriter(new File(outDir, "paddingpoint.json")));

    outputPoint(bWrt, paddingPoint, true);

    bWrt.close();

    for (int i = 0; i != count; i++) {
        String baseName = "REGION-" + fmt.format(i) + "_BTL_DEMO";

        generatePackedBallots(ballotDir, candidateDir, baseName, new Random(i), ballotSize, encryptor,
                pubKey.getParameters(), new SecureRandom(), preferenceMap, paddingPoint);
    }

    keyGenerationService.shutdown();
    adminRegistrar.shutdown();

    bWrt = new BufferedWriter(new FileWriter(new File(outDir, "map.properties")));

    bWrt.write("curve: secp256r1");
    bWrt.newLine();
    bWrt.write("use.direct: ATL");
    bWrt.newLine();
    bWrt.write("padding.file: paddingpoint.json");
    bWrt.newLine();
    bWrt.write("table.btl.file: BTL_Table");
    bWrt.newLine();
    bWrt.write("table.btl.linelength: 36");
    bWrt.newLine();
    bWrt.write("table.btl.packing: 3");
    bWrt.newLine();
    bWrt.write("candidate.tables: candidateTables");
    bWrt.newLine();

    bWrt.close();
}

From source file:org.cryptoworkshop.ximix.demo.client.Main.java

License:Apache License

public static void main(String[] args) throws Exception {
    XimixRegistrar registrar = XimixRegistrarFactory.createServicesRegistrar(new File(args[0]),
            new EventNotifier() {
                @Override//  w  ww .j a  v  a2  s.  c  o  m
                public void notify(Level level, Throwable throwable) {
                    System.err.print(level + " " + throwable.getMessage());
                    throwable.printStackTrace(System.err);
                }

                @Override
                public void notify(Level level, Object detail) {
                    System.err.println(level + " " + detail.toString());
                }

                @Override
                public void notify(Level level, Object detail, Throwable throwable) {
                    System.err.println(level + " " + detail.toString());
                    throwable.printStackTrace(System.err);
                }
            });

    KeyService keyFetcher = registrar.connect(KeyService.class);
    //UploadService client = registrar.connect(UploadService.class);
    SigningService signingService = registrar.connect(SigningService.class);

    byte[] encPubKey = keyFetcher.fetchPublicKey("ECENCKEY");

    ECPublicKeyParameters pubKey = (ECPublicKeyParameters) PublicKeyFactory.createKey(encPubKey);

    ECElGamalEncryptor encryptor = new ECElGamalEncryptor();

    encryptor.init(pubKey);

    ECPoint candidate1 = generatePoint(pubKey.getParameters(), new SecureRandom());

    ECPoint candidate2 = generatePoint(pubKey.getParameters(), new SecureRandom());

    //
    // encrypt two candidate numbers
    //
    ECPair encCandidate1 = encryptor.encrypt(candidate1);
    ECPair encCandidate2 = encryptor.encrypt(candidate2);

    PairSequence ballot = new PairSequence(encCandidate1, encCandidate2);

    // client.uploadMessage("FRED", ballot.getEncoded());

    SHA256Digest sha256 = new SHA256Digest();

    byte[] message = ballot.getEncoded();
    byte[] hash = new byte[sha256.getDigestSize()];

    sha256.update(message, 0, message.length);

    sha256.doFinal(hash, 0);

    //
    // ECDSA
    //
    SignatureGenerationOptions sigGenOptions = new SignatureGenerationOptions.Builder(Algorithm.ECDSA)
            .withThreshold(2).withNodes("A", "B", "C", "D").build();

    byte[] dsaSig = signingService.generateSignature("ECSIGKEY", sigGenOptions, hash);

    //
    // check the signature locally.
    //
    ECDSASigner signer = new ECDSASigner();

    ECPublicKeyParameters sigPubKey = (ECPublicKeyParameters) PublicKeyFactory
            .createKey(signingService.fetchPublicKey("ECSIGKEY"));

    signer.init(false, sigPubKey);

    BigInteger[] rs = decodeSig(dsaSig);

    if (signer.verifySignature(hash, rs[0], rs[1])) {
        System.out.println("sig verified!");
    } else {
        System.out.println("sig failed...");
    }

    SignatureGenerationOptions blsSigGenOptions = new SignatureGenerationOptions.Builder(Algorithm.BLS)
            .withThreshold(3).withNodes("B", "C", "D").build();

    byte[] blsSig = signingService.generateSignature("BLSSIGKEY", blsSigGenOptions, hash);

    //
    // check the signature locally.
    //
    BLS01Signer blsSigner = new BLS01Signer(sha256);

    BLS01PublicKeyParameters blsPubKey = BLSPublicKeyFactory
            .createKey(signingService.fetchPublicKey("BLSSIGKEY"));

    blsSigner.init(false, blsPubKey);

    blsSigner.update(message, 0, message.length);

    if (blsSigner.verifySignature(blsSig)) {
        System.out.println("sig verified!");
    } else {
        System.out.println("sig failed...");
    }

    keyFetcher.shutdown();
    signingService.shutdown();
    registrar.shutdown();
}

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();//  w w w . ja va2s .co  m
    }

    // 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());
    }/*  w w w. j av  a2 s .  c o  m*/

    // 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.cryptoworkshop.ximix.test.tests.BoardCreationTest.java

License:Apache License

private void doMixedMissingTest(final UploadService client, CommandService commandService,
        final ECPublicKeyParameters pubKey, String[] decNodes) throws Exception {
    SecureRandom random = new SecureRandom();

    ECElGamalEncryptor encryptor = new ECElGamalEncryptor();

    encryptor.init(pubKey);//from  ww w  . j a v a2  s  .c  o  m

    //
    // Set up plain text and upload encrypted pair.
    //

    int numberOfPoints = 100; // Adjust number of points to test here.

    final ECPoint[] plainText1 = new ECPoint[numberOfPoints];
    final ECPoint[] plainText2 = new ECPoint[numberOfPoints];

    Executor executor = Executors.newFixedThreadPool(4);

    //
    // Encrypt and submit.
    //
    final CountDownLatch bb1Latch = new CountDownLatch(plainText1.length);
    final CountDownLatch bb2Latch = new CountDownLatch(plainText1.length);
    final CountDownLatch cc1Latch = new CountDownLatch(plainText1.length);

    for (int i = 0; i < plainText1.length; i++) {
        plainText1[i] = generatePoint(pubKey.getParameters(), random);
        plainText2[i] = generatePoint(pubKey.getParameters(), random);

        final byte[] encrypted = new PairSequence(
                new ECPair[] { encryptor.encrypt(plainText1[i]), encryptor.encrypt(plainText2[i]) })
                        .getEncoded();

        executor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    client.uploadMessage("BBOARD1", encrypted);
                } catch (ServiceConnectionException e) {
                    e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                }
                bb1Latch.countDown();
            }
        });
        executor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    client.uploadMessage("BBOARD2", encrypted);
                } catch (ServiceConnectionException e) {
                    e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                }
                bb2Latch.countDown();
            }
        });
        executor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    client.uploadMessage("CBOARD1", encrypted);
                } catch (ServiceConnectionException e) {
                    e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                }
                cc1Latch.countDown();
            }
        });
    }

    bb1Latch.await();
    bb2Latch.await();
    cc1Latch.await();

    final ECPoint[] resultText1 = new ECPoint[plainText1.length];
    final ECPoint[] resultText2 = new ECPoint[plainText2.length];
    final AtomicBoolean downloadBoardCompleted = new AtomicBoolean(false);
    final AtomicBoolean downloadBoardFailed = new AtomicBoolean(false);
    final CountDownLatch encryptLatch = new CountDownLatch(1);
    final AtomicReference<Thread> decryptThread = new AtomicReference<>();

    Operation<DownloadOperationListener> op = commandService.downloadBoardContents("BBOARD1",
            new DownloadOptions.Builder().withKeyID("ECKEY").withThreshold(3).withNodes(decNodes).build(),
            new DownloadOperationListener() {
                int counter = 0;

                @Override
                public void messageDownloaded(int index, byte[] message, List<byte[]> proofs) {
                    PointSequence decrypted = PointSequence.getInstance(pubKey.getParameters().getCurve(),
                            message);
                    resultText1[counter] = decrypted.getECPoints()[0];
                    resultText2[counter++] = decrypted.getECPoints()[1];
                    TestUtil.checkThread(decryptThread);
                }

                @Override
                public void completed() {
                    downloadBoardCompleted.set(true);
                    TestUtil.checkThread(decryptThread);
                    encryptLatch.countDown();
                }

                @Override
                public void status(String statusObject) {
                    TestUtil.checkThread(decryptThread);
                }

                @Override
                public void failed(String errorObject) {
                    TestUtil.checkThread(decryptThread);
                    downloadBoardFailed.set(true);
                    encryptLatch.countDown();
                }
            });

    TestCase.assertTrue(encryptLatch.await(30, TimeUnit.SECONDS));

    TestCase.assertNotSame("Failed and complete must be different.", downloadBoardFailed.get(),
            downloadBoardCompleted.get());
    TestCase.assertTrue("Complete method called in DownloadOperationListener", downloadBoardCompleted.get());
    TestCase.assertFalse("Not failed.", downloadBoardFailed.get());

    //  TestCase.assertEquals("Shuffle and decrypt threads different.", decryptThread.get(), shuffleThread.get());

    //
    // Validate result points against plainText points.
    //

    Set<ECPoint> pt = new HashSet<>();
    for (int t = 0; t < plainText1.length; t++) {
        pt.add(plainText1[t]);
        pt.add(plainText2[t]);
    }

    for (int t = 0; t < plainText1.length; t++) {
        pt.remove(resultText1[t]);
        pt.remove(resultText2[t]);
    }

    TestCase.assertEquals(0, pt.size());
}

From source file:org.cryptoworkshop.ximix.test.tests.KeyProcessingTest.java

License:Apache License

private void doMixedMissingTest(UploadService client, CommandService commandService,
        final ECPublicKeyParameters pubKey, String[] decNodes) throws Exception {
    SecureRandom random = new SecureRandom();

    ECElGamalEncryptor encryptor = new ECElGamalEncryptor();

    encryptor.init(pubKey);//from   w  ww  .j  a v  a  2s  .com

    //
    // Set up plain text and upload encrypted pair.
    //

    int numberOfPoints = 15; // Adjust number of points to test here.

    final ECPoint[] plainText1 = new ECPoint[numberOfPoints];
    final ECPoint[] plainText2 = new ECPoint[numberOfPoints];

    //
    // Encrypt and submit.
    //
    for (int i = 0; i < plainText1.length; i++) {
        plainText1[i] = generatePoint(pubKey.getParameters(), random);
        plainText2[i] = generatePoint(pubKey.getParameters(), random);

        PairSequence encrypted = new PairSequence(
                new ECPair[] { encryptor.encrypt(plainText1[i]), encryptor.encrypt(plainText2[i]) });

        client.uploadMessage("FRED", encrypted.getEncoded());
    }

    final ECPoint[] resultText1 = new ECPoint[plainText1.length];
    final ECPoint[] resultText2 = new ECPoint[plainText2.length];
    final AtomicBoolean downloadBoardCompleted = new AtomicBoolean(false);
    final AtomicBoolean downloadBoardFailed = new AtomicBoolean(false);
    final CountDownLatch encryptLatch = new CountDownLatch(1);
    final AtomicReference<Thread> decryptThread = new AtomicReference<>();

    Operation<DownloadOperationListener> op = commandService.downloadBoardContents("FRED",
            new DownloadOptions.Builder().withKeyID("ECKEY").withThreshold(3).withNodes(decNodes).build(),
            new DownloadOperationListener() {
                int counter = 0;

                @Override
                public void messageDownloaded(int index, byte[] message, List<byte[]> proofs) {
                    PointSequence decrypted = PointSequence.getInstance(pubKey.getParameters().getCurve(),
                            message);
                    resultText1[counter] = decrypted.getECPoints()[0];
                    resultText2[counter++] = decrypted.getECPoints()[1];
                    TestUtil.checkThread(decryptThread);
                }

                @Override
                public void completed() {
                    downloadBoardCompleted.set(true);
                    TestUtil.checkThread(decryptThread);
                    encryptLatch.countDown();
                }

                @Override
                public void status(String statusObject) {
                    TestUtil.checkThread(decryptThread);
                }

                @Override
                public void failed(String errorObject) {
                    TestUtil.checkThread(decryptThread);
                    downloadBoardFailed.set(true);
                    encryptLatch.countDown();
                }
            });

    TestCase.assertTrue(encryptLatch.await(20, TimeUnit.SECONDS));

    TestCase.assertNotSame("Failed and complete must be different.", downloadBoardFailed.get(),
            downloadBoardCompleted.get());
    TestCase.assertTrue("Complete method called in DownloadOperationListener", downloadBoardCompleted.get());
    TestCase.assertFalse("Not failed.", downloadBoardFailed.get());

    //  TestCase.assertEquals("Shuffle and decrypt threads different.", decryptThread.get(), shuffleThread.get());

    //
    // Validate result points against plainText points.
    //

    for (int t = 0; t < plainText1.length; t++) {
        TestCase.assertTrue(plainText1[t].equals(resultText1[t]));
        TestCase.assertTrue(plainText2[t].equals(resultText2[t]));
    }
}

From source file:org.cryptoworkshop.ximix.test.tests.KeyProcessingTest.java

License:Apache License

@Test
public void testKeyGenerationEncryptionTestWithShuffle() throws Exception {
    SquelchingThrowableHandler handler = new SquelchingThrowableHandler();
    handler.squelchType(SocketException.class);

    ///*  ww  w  .j a  v  a2s  .  co m*/
    // Set up nodes.
    //

    XimixNode nodeOne = getXimixNode("/conf/mixnet.xml", "/conf/node1.xml", handler);
    NodeTestUtil.launch(nodeOne);

    XimixNode nodeTwo = getXimixNode("/conf/mixnet.xml", "/conf/node2.xml", handler);
    NodeTestUtil.launch(nodeTwo);

    XimixNode nodeThree = getXimixNode("/conf/mixnet.xml", "/conf/node3.xml", handler);
    NodeTestUtil.launch(nodeThree);

    XimixNode nodeFour = getXimixNode("/conf/mixnet.xml", "/conf/node4.xml", handler);
    NodeTestUtil.launch(nodeFour);

    XimixNode nodeFive = getXimixNode("/conf/mixnet.xml", "/conf/node5.xml", handler);
    NodeTestUtil.launch(nodeFive);

    SecureRandom random = new SecureRandom();

    XimixRegistrar adminRegistrar = XimixRegistrarFactory
            .createAdminServiceRegistrar(ResourceAnchor.load("/conf/mixnet.xml"), new TestNotifier());

    CommandService commandService = adminRegistrar.connect(CommandService.class);

    commandService.createBoard("FRED", new BoardCreationOptions.Builder("B").build());

    KeyGenerationService keyGenerationService = adminRegistrar.connect(KeyGenerationService.class);

    KeyGenerationOptions keyGenOptions = new KeyGenerationOptions.Builder(Algorithm.EC_ELGAMAL, "secp256r1")
            .withThreshold(4).withNodes("A", "B", "C", "D", "E").build();

    byte[] encPubKey = keyGenerationService.generatePublicKey("ECKEY", keyGenOptions);

    UploadService client = adminRegistrar.connect(UploadService.class);

    final ECPublicKeyParameters pubKey = (ECPublicKeyParameters) PublicKeyFactory.createKey(encPubKey);

    final ECElGamalEncryptor encryptor = new ECElGamalEncryptor();

    encryptor.init(pubKey);

    //
    // Set up plain text and upload encrypted pair.
    //

    int numberOfPoints = 20; // Adjust number of points to test here.

    final ECPoint[] plainText1 = new ECPoint[numberOfPoints];
    final ECPoint[] plainText2 = new ECPoint[numberOfPoints];
    Set<ECPoint> plain1 = new HashSet<>();
    Set<ECPoint> plain2 = new HashSet<>();

    //
    // Encrypt and submit.
    //
    for (int i = 0; i < plainText1.length; i++) {
        plainText1[i] = generatePoint(pubKey.getParameters(), random);
        plainText2[i] = generatePoint(pubKey.getParameters(), random);

        plain1.add(plainText1[i]);
        plain2.add(plainText2[i]);

        PairSequence encrypted = new PairSequence(
                new ECPair[] { encryptor.encrypt(plainText1[i]), encryptor.encrypt(plainText2[i]) });

        client.uploadMessage("FRED", encrypted.getEncoded());
    }

    //
    // Perform shuffle.
    //
    final CountDownLatch shufflerLatch = new CountDownLatch(1);

    final AtomicBoolean shuffleCompleted = new AtomicBoolean(false);
    final AtomicBoolean shuffleFailed = new AtomicBoolean(false);
    final AtomicReference<Thread> shuffleThread = new AtomicReference<>();

    ShuffleOperationListener shuffleListener = new ShuffleOperationListener() {
        @Override
        public void commit(Map<String, byte[]> seedCommitments) {

        }

        @Override
        public void completed() {
            shuffleCompleted.set(true);
            TestUtil.checkThread(shuffleThread);
            shufflerLatch.countDown();
        }

        @Override
        public void status(ShuffleStatus statusObject) {
            //To change body of implemented methods use File | Settings | File Templates.
        }

        @Override
        public void failed(ShuffleStatus errorObject) {
            shuffleFailed.set(true);
            shufflerLatch.countDown();
            TestUtil.checkThread(shuffleThread);
        }
    };

    Operation<ShuffleOperationListener> shuffleOp = commandService.doShuffleAndMove("FRED",
            new ShuffleOptions.Builder(MultiColumnRowTransform.NAME).withKeyID("ECKEY").build(),
            shuffleListener, "A", "C", "D", "E");

    shufflerLatch.await();

    //
    // Fail if operation did not complete in the nominated time frame.
    //
    //TestCase.assertTrue("Shuffle timed out.", shufflerLatch.await(20, TimeUnit.SECONDS));

    //
    // Check that failed and completed methods are exclusive.
    //

    TestCase.assertNotSame("Failed flag and completed flag must be different.", shuffleCompleted.get(),
            shuffleFailed.get());

    //
    // Check for success of shuffle.
    //
    TestCase.assertTrue(shuffleCompleted.get());

    //
    // Check that shuffle did not fail.
    //
    TestCase.assertFalse(shuffleFailed.get());

    final CountDownLatch transcriptCompleted = new CountDownLatch(1);

    final Map<String, byte[]> generalTranscripts = new HashMap<>();

    ShuffleTranscriptsDownloadOperationListener transcriptListener = new ShuffleTranscriptsDownloadOperationListener() {
        @Override
        public void shuffleTranscriptArrived(long operationNumber, int stepNumber, InputStream transcript) {
            try {
                ByteArrayOutputStream bOut = new ByteArrayOutputStream();
                BufferedInputStream bIn = new BufferedInputStream(transcript);

                int ch;
                while ((ch = bIn.read()) >= 0) {
                    bOut.write(ch);
                }
                bOut.close();

                generalTranscripts.put(Long.toHexString(operationNumber) + "." + stepNumber,
                        bOut.toByteArray());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void completed() {
            transcriptCompleted.countDown();
        }

        @Override
        public void status(String statusObject) {
            //To change body of implemented methods use File | Settings | File Templates.
        }

        @Override
        public void failed(String errorObject) {
            transcriptCompleted.countDown();
        }
    };

    commandService.downloadShuffleTranscripts("FRED", shuffleOp.getOperationNumber(),
            new ShuffleTranscriptOptions.Builder(TranscriptType.GENERAL).build(), transcriptListener, "A", "C",
            "D", "E");

    transcriptCompleted.await();

    TestCase.assertEquals(5, generalTranscripts.size());

    final Map<String, byte[]> witnessTranscripts = new HashMap<>();

    final CountDownLatch witnessTranscriptCompleted = new CountDownLatch(1);
    transcriptListener = new ShuffleTranscriptsDownloadOperationListener() {
        @Override
        public void shuffleTranscriptArrived(long operationNumber, int stepNumber, InputStream transcript) {
            try {
                ByteArrayOutputStream bOut = new ByteArrayOutputStream();
                BufferedInputStream bIn = new BufferedInputStream(transcript);

                int ch;
                while ((ch = bIn.read()) >= 0) {
                    bOut.write(ch);
                }
                bOut.close();

                witnessTranscripts.put(Long.toHexString(operationNumber) + "." + stepNumber,
                        bOut.toByteArray());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void completed() {
            witnessTranscriptCompleted.countDown();
        }

        @Override
        public void status(String statusObject) {
            //To change body of implemented methods use File | Settings | File Templates.
        }

        @Override
        public void failed(String errorObject) {
            witnessTranscriptCompleted.countDown();
        }
    };

    commandService.downloadShuffleTranscripts("FRED", shuffleOp.getOperationNumber(),
            new ShuffleTranscriptOptions.Builder(TranscriptType.WITNESSES).withChallengeSeed(new byte[55])
                    .build(),
            transcriptListener, "A", "C", "D", "E");

    witnessTranscriptCompleted.await();

    TestCase.assertEquals(4, witnessTranscripts.size());

    final ECPoint[] resultText1 = new ECPoint[plainText1.length];
    final ECPoint[] resultText2 = new ECPoint[plainText2.length];
    final AtomicBoolean downloadBoardCompleted = new AtomicBoolean(false);
    final AtomicBoolean downloadBoardFailed = new AtomicBoolean(false);
    final CountDownLatch encryptLatch = new CountDownLatch(1);
    final AtomicReference<Thread> decryptThread = new AtomicReference<>();

    Operation<DownloadOperationListener> op = commandService.downloadBoardContents("FRED",
            new DownloadOptions.Builder().withKeyID("ECKEY").withThreshold(4).withNodes("A", "B", "C", "D", "E")
                    .build(),
            new DownloadOperationListener() {
                int counter = 0;

                @Override
                public void messageDownloaded(int index, byte[] message, List<byte[]> proofs) {
                    PointSequence decrypted = PointSequence.getInstance(pubKey.getParameters().getCurve(),
                            message);
                    resultText1[counter] = decrypted.getECPoints()[0];
                    resultText2[counter++] = decrypted.getECPoints()[1];
                    TestUtil.checkThread(decryptThread);
                    for (int i = 0; i != proofs.size(); i++) {
                        ChallengeLogMessage logMessage = ChallengeLogMessage.getInstance(proofs.get(i));

                        if (!logMessage.hasPassed()) {
                            downloadBoardFailed.set(true);
                        }
                    }
                }

                @Override
                public void completed() {
                    downloadBoardCompleted.set(true);
                    TestUtil.checkThread(decryptThread);
                    encryptLatch.countDown();
                }

                @Override
                public void status(String statusObject) {
                    TestUtil.checkThread(decryptThread);
                }

                @Override
                public void failed(String errorObject) {
                    TestUtil.checkThread(decryptThread);
                    downloadBoardFailed.set(true);
                    encryptLatch.countDown();
                }
            });

    TestCase.assertTrue(encryptLatch.await(20, TimeUnit.SECONDS));

    TestCase.assertNotSame("Failed and complete must be different.", downloadBoardFailed.get(),
            downloadBoardCompleted.get());
    TestCase.assertTrue("Complete method called in DownloadOperationListener", downloadBoardCompleted.get());
    TestCase.assertFalse("Not failed.", downloadBoardFailed.get());

    //
    // Validate result points against plainText points.
    //

    for (int t = 0; t < plainText1.length; t++) {
        plain1.remove(resultText1[t]);
        plain2.remove(resultText2[t]);
    }

    TestCase.assertTrue(plain1.isEmpty());
    TestCase.assertTrue(plain2.isEmpty());

    NodeTestUtil.shutdownNodes();
    client.shutdown();
    commandService.shutdown();
}

From source file:org.cryptoworkshop.ximix.test.tests.KeyProcessingTest.java

License:Apache License

@Test
public void testKeyGenerationEncryptionTestWithDecryptionAndZKP() throws Exception {
    SquelchingThrowableHandler handler = new SquelchingThrowableHandler();
    handler.squelchType(SocketException.class);

    ////from   ww  w .  j a v a  2s.c om
    // Set up nodes.
    //

    XimixNode nodeOne = getXimixNode("/conf/mixnet.xml", "/conf/node1.xml", handler);
    NodeTestUtil.launch(nodeOne);

    XimixNode nodeTwo = getXimixNode("/conf/mixnet.xml", "/conf/node2.xml", handler);
    NodeTestUtil.launch(nodeTwo);

    XimixNode nodeThree = getXimixNode("/conf/mixnet.xml", "/conf/node3.xml", handler);
    NodeTestUtil.launch(nodeThree);

    XimixNode nodeFour = getXimixNode("/conf/mixnet.xml", "/conf/node4.xml", handler);
    NodeTestUtil.launch(nodeFour);

    XimixNode nodeFive = getXimixNode("/conf/mixnet.xml", "/conf/node5.xml", handler);
    NodeTestUtil.launch(nodeFive);

    SecureRandom random = new SecureRandom();

    XimixRegistrar adminRegistrar = XimixRegistrarFactory
            .createAdminServiceRegistrar(ResourceAnchor.load("/conf/mixnet.xml"), new TestNotifier());

    KeyGenerationService keyGenerationService = adminRegistrar.connect(KeyGenerationService.class);

    KeyGenerationOptions keyGenOptions = new KeyGenerationOptions.Builder(Algorithm.EC_ELGAMAL, "secp256r1")
            .withThreshold(4).withNodes("A", "B", "C", "D", "E").build();

    byte[] encPubKey = keyGenerationService.generatePublicKey("ECKEY", keyGenOptions);

    CommandService commandService = adminRegistrar.connect(CommandService.class);

    commandService.createBoard("FRED", new BoardCreationOptions.Builder("B").build());

    UploadService client = adminRegistrar.connect(UploadService.class);

    final ECPublicKeyParameters pubKey = (ECPublicKeyParameters) PublicKeyFactory.createKey(encPubKey);

    final ECElGamalEncryptor encryptor = new ECElGamalEncryptor();

    encryptor.init(pubKey);

    //
    // Set up plain text and upload encrypted pair.
    //

    int numberOfPoints = 20; // Adjust number of points to test here.

    final ECPoint[] plainText1 = new ECPoint[numberOfPoints];
    final ECPoint[] plainText2 = new ECPoint[numberOfPoints];
    Set<ECPoint> plain1 = new HashSet<>();
    Set<ECPoint> plain2 = new HashSet<>();

    ByteArrayOutputStream postedMessageStream = new ByteArrayOutputStream();

    //
    // Encrypt and submit.
    //
    for (int i = 0; i < plainText1.length; i++) {
        plainText1[i] = generatePoint(pubKey.getParameters(), random);
        plainText2[i] = generatePoint(pubKey.getParameters(), random);

        plain1.add(plainText1[i]);
        plain2.add(plainText2[i]);

        PairSequence encrypted = new PairSequence(
                new ECPair[] { encryptor.encrypt(plainText1[i]), encryptor.encrypt(plainText2[i]) });

        client.uploadMessage("FRED", encrypted.getEncoded());

        postedMessageStream.write(new PostedMessage(i, encrypted.getEncoded()).getEncoded());
    }

    final ECPoint[] resultText1 = new ECPoint[plainText1.length];
    final ECPoint[] resultText2 = new ECPoint[plainText2.length];
    final AtomicBoolean downloadBoardCompleted = new AtomicBoolean(false);
    final AtomicBoolean downloadBoardFailed = new AtomicBoolean(false);
    final CountDownLatch encryptLatch = new CountDownLatch(1);
    final AtomicReference<Thread> decryptThread = new AtomicReference<>();

    final ByteArrayOutputStream logStream = new ByteArrayOutputStream();
    final ByteArrayOutputStream resultStream = new ByteArrayOutputStream();

    Operation<DownloadOperationListener> op = commandService.downloadBoardContents("FRED",
            new DownloadOptions.Builder().withKeyID("ECKEY").withThreshold(4).withNodes("A", "B", "C", "D", "E")
                    .build(),
            new DownloadOperationListener() {
                int counter = 0;

                @Override
                public void messageDownloaded(int index, byte[] message, List<byte[]> proofs) {
                    try {
                        resultStream.write(message);
                        for (byte[] proof : proofs) {
                            logStream.write(proof);
                        }
                    } catch (IOException e) {
                        TestCase.fail(e.toString());
                    }
                    PointSequence decrypted = PointSequence.getInstance(pubKey.getParameters().getCurve(),
                            message);
                    resultText1[counter] = decrypted.getECPoints()[0];
                    resultText2[counter++] = decrypted.getECPoints()[1];
                    TestUtil.checkThread(decryptThread);

                }

                @Override
                public void completed() {
                    downloadBoardCompleted.set(true);
                    TestUtil.checkThread(decryptThread);
                    encryptLatch.countDown();
                }

                @Override
                public void status(String statusObject) {
                    TestUtil.checkThread(decryptThread);
                }

                @Override
                public void failed(String errorObject) {
                    TestUtil.checkThread(decryptThread);
                    downloadBoardFailed.set(true);
                    encryptLatch.countDown();
                }
            });

    TestCase.assertTrue(encryptLatch.await(20, TimeUnit.SECONDS));

    TestCase.assertNotSame("Failed and complete must be different.", downloadBoardFailed.get(),
            downloadBoardCompleted.get());
    TestCase.assertTrue("Complete method not called in DownloadOperationListener",
            downloadBoardCompleted.get());
    TestCase.assertFalse("Not failed.", downloadBoardFailed.get());

    ECDecryptionChallengeVerifier verifier = new ECDecryptionChallengeVerifier(pubKey,
            new ByteArrayInputStream(postedMessageStream.toByteArray()),
            new ByteArrayInputStream(resultStream.toByteArray()),
            new ByteArrayInputStream(logStream.toByteArray()));

    verifier.verify();

    //
    // Validate result points against plainText points.
    //

    for (int t = 0; t < plainText1.length; t++) {
        plain1.remove(resultText1[t]);
        plain2.remove(resultText2[t]);
    }

    TestCase.assertTrue(plain1.isEmpty());
    TestCase.assertTrue(plain2.isEmpty());

    NodeTestUtil.shutdownNodes();
    client.shutdown();
    commandService.shutdown();
}

From source file:org.cryptoworkshop.ximix.test.tests.KeyProcessingTest.java

License:Apache License

@Test
public void testKeyGenerationEncryptionTest() throws Exception {
    SquelchingThrowableHandler handler = new SquelchingThrowableHandler();

    handler.squelchType(SocketException.class);
    //handler.squelchType(SocketException.class);

    ///* ww  w. j  ava 2  s .c  o  m*/
    // Set up nodes.
    //

    XimixNode nodeOne = getXimixNode("/conf/mixnet.xml", "/conf/node1.xml", handler);
    NodeTestUtil.launch(nodeOne);

    XimixNode nodeTwo = getXimixNode("/conf/mixnet.xml", "/conf/node2.xml", handler);
    NodeTestUtil.launch(nodeTwo);

    XimixNode nodeThree = getXimixNode("/conf/mixnet.xml", "/conf/node3.xml", handler);
    NodeTestUtil.launch(nodeThree);

    XimixNode nodeFour = getXimixNode("/conf/mixnet.xml", "/conf/node4.xml", handler);
    NodeTestUtil.launch(nodeFour);

    XimixNode nodeFive = getXimixNode("/conf/mixnet.xml", "/conf/node5.xml", handler);
    NodeTestUtil.launch(nodeFive);

    SecureRandom random = new SecureRandom();

    XimixRegistrar adminRegistrar = XimixRegistrarFactory
            .createAdminServiceRegistrar(ResourceAnchor.load("/conf/mixnet.xml"), new TestNotifier());

    KeyGenerationService keyGenerationService = adminRegistrar.connect(KeyGenerationService.class);

    KeyGenerationOptions keyGenOptions = new KeyGenerationOptions.Builder(Algorithm.EC_ELGAMAL, "secp256r1")
            .withThreshold(4).withNodes("A", "B", "C", "D", "E").build();

    byte[] encPubKey = keyGenerationService.generatePublicKey("ECKEY", keyGenOptions);

    CommandService commandService = adminRegistrar.connect(CommandService.class);

    commandService.createBoard("FRED", new BoardCreationOptions.Builder("B").build());

    UploadService client = adminRegistrar.connect(UploadService.class);

    final ECPublicKeyParameters pubKey = (ECPublicKeyParameters) PublicKeyFactory.createKey(encPubKey);

    final ECElGamalEncryptor encryptor = new ECElGamalEncryptor();

    encryptor.init(pubKey);

    //
    // Set up plain text and upload encrypted pair.
    //

    int numberOfPoints = 1; // Adjust number of points to test here.

    final ECPoint[] plainText1 = new ECPoint[numberOfPoints];
    final ECPoint[] plainText2 = new ECPoint[numberOfPoints];

    //
    // Encrypt and submit.
    //
    for (int i = 0; i < plainText1.length; i++) {
        plainText1[i] = generatePoint(pubKey.getParameters(), random);
        plainText2[i] = generatePoint(pubKey.getParameters(), random);

        PairSequence encrypted = new PairSequence(
                new ECPair[] { encryptor.encrypt(plainText1[i]), encryptor.encrypt(plainText2[i]) });

        client.uploadMessage("FRED", encrypted.getEncoded());
    }

    final ECPoint[] resultText1 = new ECPoint[plainText1.length];
    final ECPoint[] resultText2 = new ECPoint[plainText2.length];
    final ValueObject<Boolean> downloadBoardCompleted = new ValueObject<Boolean>(false);
    final ValueObject<Boolean> downloadBoardFailed = new ValueObject<Boolean>(false);
    final CountDownLatch encryptLatch = new CountDownLatch(1);
    final ValueObject<Thread> decryptThread = new ValueObject<>();

    Operation<DownloadOperationListener> op = commandService.downloadBoardContents("FRED",
            new DownloadOptions.Builder().withKeyID("ECKEY").withThreshold(4).withNodes("A", "B", "C", "D", "E")
                    .build(),
            new DownloadOperationListener() {
                int counter = 0;

                @Override
                public void messageDownloaded(int index, byte[] message, List<byte[]> proofs) {
                    PointSequence decrypted = PointSequence.getInstance(pubKey.getParameters().getCurve(),
                            message);
                    resultText1[counter] = decrypted.getECPoints()[0];
                    resultText2[counter++] = decrypted.getECPoints()[1];
                }

                @Override
                public void completed() {
                    downloadBoardCompleted.set(true);
                    decryptThread.set(Thread.currentThread());
                    encryptLatch.countDown();
                }

                @Override
                public void status(String statusObject) {
                    //To change body of implemented methods use File | Settings | File Templates.
                }

                @Override
                public void failed(String errorObject) {
                    downloadBoardFailed.set(true);
                    encryptLatch.countDown();
                }
            });

    TestCase.assertTrue(encryptLatch.await(20, TimeUnit.SECONDS));

    TestCase.assertNotSame("Failed and complete must be different.", downloadBoardFailed.get(),
            downloadBoardCompleted.get());
    TestCase.assertTrue("Complete method called in DownloadOperationListener", downloadBoardCompleted.get());
    TestCase.assertFalse("Not failed.", downloadBoardFailed.get());

    //        TestCase.assertEquals("Shuffle and decrypt threads different.",decryptThread.get(), shuffleThread.get());

    //
    // Validate result points against plainText points.
    //

    for (int t = 0; t < plainText1.length; t++) {

        NodeTestUtil.printHexln("PT 1", plainText1[0].getEncoded());
        NodeTestUtil.printHexln("RT 1", resultText1[0].getEncoded());

        NodeTestUtil.printHexln("PT 2", plainText2[0].getEncoded());
        NodeTestUtil.printHexln("RT 2", resultText2[0].getEncoded());

        TestCase.assertTrue(plainText1[t].equals(resultText1[t]));
        TestCase.assertTrue(plainText2[t].equals(resultText2[t]));
    }

    NodeTestUtil.shutdownNodes();
    client.shutdown();
    commandService.shutdown();

}