List of usage examples for org.bouncycastle.crypto.ec ECElGamalEncryptor encrypt
public ECPair encrypt(ECPoint point)
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 ww w.ja va2s .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); } }); 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
private static void generateBallots(File ballotDir, File candidateDir, String baseName, Random rand, int ballotSize, ECElGamalEncryptor encryptor, ECDomainParameters ecParams, SecureRandom pointRandom) throws IOException { File ballotFile = new File(ballotDir, baseName + ".blt"); File candidateFile = new File(candidateDir, baseName + "." + "candidates.cid"); int numberOfCandidates = 4 + rand.nextInt(10); List<ECPoint> candidateNumbers = new ArrayList<>(numberOfCandidates); for (int candidateNo = 0; candidateNo != numberOfCandidates; candidateNo++) { candidateNumbers.add(generatePoint(ecParams, pointRandom)); }/*from w w w . j av a2 s . co m*/ int numberOfBallots = ballotSize + rand.nextInt(ballotSize / 10); ECPair[][] ballots = new ECPair[numberOfBallots][]; for (int ballotNo = 0; ballotNo != numberOfBallots; ballotNo++) { Collections.shuffle(candidateNumbers, rand); ECPair[] ballot = new ECPair[numberOfCandidates]; for (int i = 0; i != ballot.length; i++) { ballot[i] = encryptor.encrypt(candidateNumbers.get(i)); } ballots[ballotNo] = ballot; } OutputStream fOut = new BufferedOutputStream(new FileOutputStream(ballotFile)); for (int j = 0; j != ballots.length; j++) { fOut.write(new PairSequence(ballots[j]).getEncoded()); } fOut.close(); createCandidateList(baseName, candidateFile, "ATL", candidateNumbers); }
From source file:org.cryptoworkshop.ximix.demo.ballot.Main.java
License:Apache License
private static void generatePackedBallots(File ballotDir, File candidateDir, String baseName, Random rand, int ballotSize, ECElGamalEncryptor encryptor, ECDomainParameters ecParams, SecureRandom pointRandom, Map<Preferences, ECPoint> preferenceMap, ECPoint paddingPoint) throws IOException { File ballotFile = new File(ballotDir, baseName + ".blt"); File candidateFile = new File(candidateDir, baseName + "." + "candidates.cid"); int numberOfCandidates = 4 + rand.nextInt(10); List<ECPoint> candidateNumbers = new ArrayList<>(numberOfCandidates); for (int candidateNo = 0; candidateNo != numberOfCandidates; candidateNo++) { candidateNumbers.add(generatePoint(ecParams, pointRandom)); }//w ww .ja v a2s. c o m createCandidateList(baseName, candidateFile, "BTL", candidateNumbers); int numberOfBallots = ballotSize + rand.nextInt(ballotSize / 10); ECPair[][] ballots = new ECPair[numberOfBallots][]; List<Byte> preferences = new ArrayList<>(); for (int i = 0; i != numberOfCandidates; i++) { preferences.add((byte) (i + 1)); } for (int ballotNo = 0; ballotNo != numberOfBallots - 1; ballotNo++) { Collections.shuffle(preferences, rand); ECPair[] ballot = new ECPair[(preferences.size() + 2) / 3]; int index = 0; for (int i = 0; i != ballot.length; i++) { if (preferences.size() - index >= 3) { ballot[i] = encryptor.encrypt(preferenceMap.get(new Preferences(new byte[] { preferences.get(index++), preferences.get(index++), preferences.get(index++) }))); } else if (preferences.size() - index == 2) { ballot[i] = encryptor.encrypt(preferenceMap.get( new Preferences(new byte[] { preferences.get(index++), preferences.get(index++), 0 }))); } else if (preferences.size() - index == 1) { ballot[i] = encryptor.encrypt( preferenceMap.get(new Preferences(new byte[] { preferences.get(index++), 0, 0 }))); } } ballots[ballotNo] = ballot; } // add a ballot of all zeroes at the end ECPair[] ballot = new ECPair[(preferences.size() + 2) / 3]; for (int i = 0; i != ballot.length; i++) { ballot[i] = encryptor.encrypt(paddingPoint); } ballots[numberOfBallots - 1] = ballot; OutputStream fOut = new BufferedOutputStream(new FileOutputStream(ballotFile)); for (int j = 0; j != ballots.length; j++) { fOut.write(new PairSequence(ballots[j]).getEncoded()); } fOut.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/* www. j av a 2 s. com*/ 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.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 w w w . j a v a2s. 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 w w. j av a2 s.co m // // 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); //// www . j a v a 2 s . com // 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 w ww . j a v a2s .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 = 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); ///*from w ww . j a va2 s .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 = 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(); }
From source file:org.cryptoworkshop.ximix.test.tests.PeersTest.java
License:Apache License
/** * Test a network failure where 5 nodes are used for encryption but one fails before decryption. * Decryption should be successful.// w w w . j a va2 s . c o m * * @throws Exception */ private void doTestInsufficientPeers(int peerCount, int threshold, int fail) throws Exception { SquelchingThrowableHandler handler = new SquelchingThrowableHandler(); handler.squelchType(SocketException.class); // // 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(threshold).withNodes(getPeerList(peerCount)).build(); byte[] encPubKey = keyGenerationService.generatePublicKey("ECKEY", keyGenOptions); keyGenerationService.shutdown(); CommandService commandService = adminRegistrar.connect(CommandService.class); commandService.createBoard("FRED", new BoardCreationOptions.Builder("B").build()); 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]) }); commandService.uploadMessage("FRED", encrypted.getEncoded()); } // we're going to shutdown some nodes - make sure we disconnect and // reconnect in case we're talking to the one we shutdown commandService.shutdown(); // // Here we shut down on nodes, the remainder should still pass. // if (fail == 1) { TestCase.assertTrue("Node 5, failed to shutdown.", nodeFive.shutdown(10, TimeUnit.SECONDS)); } else if (fail == 2) { TestCase.assertTrue("Node 5, failed to shutdown.", nodeFive.shutdown(30, TimeUnit.SECONDS)); nodeFour.shutdown(30, TimeUnit.SECONDS); } else { TestCase.fail("unknown fail count"); } 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 AtomicReference<Thread> decryptThread = new AtomicReference<>(); commandService = adminRegistrar.connect(CommandService.class); Operation<DownloadOperationListener> op = commandService.downloadBoardContents("FRED", new DownloadOptions.Builder().withKeyID("ECKEY").withThreshold(threshold) .withNodes(getPeerList(peerCount)).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); encryptLatch.countDown(); TestUtil.checkThread(decryptThread); } @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(); TestUtil.checkThread(decryptThread); } }); 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()); encryptLatch.await(); // // 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])); } NodeTestUtil.shutdownNodes(); commandService.shutdown(); }