List of usage examples for org.bouncycastle.openssl PEMParser PEMParser
public PEMParser(Reader reader)
From source file:org.crsh.ssh.util.KeyPairUtils.java
License:Open Source License
public static Object readKey(Reader reader) throws Exception { try {//from w w w .j av a2 s. c o m PEMParser pemParser = new PEMParser(reader); try { return pemParser.readObject(); } finally { pemParser.close(); } } catch (NoClassDefFoundError e) { //. We use reflection here to keep compatible with old library of bouncycastle Class<?> pemReaderClass = Class.forName("org.bouncycastle.openssl.PEMReader"); PemReader r = (PemReader) pemReaderClass.getConstructor(Reader.class).newInstance(reader); try { return pemReaderClass.getMethod("readObject").invoke(r); } finally { r.close(); } } }
From source file:org.cryptoworkshop.ximix.console.applet.CommandApplet.java
License:Apache License
public void init() { if (Security.getProvider("BC") == null) { Security.addProvider(new BouncyCastleProvider()); }/* w w w . j a va2 s . c o m*/ final URL mixnetConf = getConfURL(); final URL trustCa = getCaURL(); JPanel topPanel = new JPanel(); topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.X_AXIS)); JPanel uploadPanel = new JPanel(); uploadPanel.setBorder(BorderFactory.createTitledBorder("Upload Source Directory")); JButton uploadBrowseButton = new JButton("..."); final JTextField uploadDirField = new JTextField(20); final XimixRegistrar adminRegistrar; try { PEMParser pemParser = new PEMParser(new InputStreamReader(trustCa.openStream())); trustAnchor = new JcaX509CertificateConverter().setProvider("BC") .getCertificate((X509CertificateHolder) pemParser.readObject()); adminRegistrar = XimixRegistrarFactory.createAdminServiceRegistrar(mixnetConf.openStream(), 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); } }); } catch (Exception e) { throw new IllegalStateException("Can't parse trust anchor.", e); } uploadBrowseButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int result = chooser.showDialog(CommandApplet.this, "Select"); if (result == JFileChooser.APPROVE_OPTION) { uploadDirField.setText(chooser.getSelectedFile().getAbsolutePath()); } } }); uploadPanel.add(uploadDirField); uploadPanel.add(uploadBrowseButton); JPanel downloadPanel = new JPanel(); downloadPanel.setBorder(BorderFactory.createTitledBorder("Download Directory")); JButton downloadBrowseButton = new JButton("..."); final JTextField downloadDirField = new JTextField(20); downloadBrowseButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int result = chooser.showDialog(CommandApplet.this, "Select"); if (result == JFileChooser.APPROVE_OPTION) { downloadDirField.setText(chooser.getSelectedFile().getAbsolutePath()); } } }); downloadPanel.add(downloadDirField); downloadPanel.add(downloadBrowseButton); JPanel tablePanel = new JPanel(); tablePanel.setLayout(new BoxLayout(tablePanel, BoxLayout.Y_AXIS)); JPanel topTablePanel = new JPanel(); topTablePanel.setLayout(new BoxLayout(topTablePanel, BoxLayout.X_AXIS)); final JTextField shufflePlan = new JTextField(30); final EventNotifier eventNotifier = 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); } }; final JTable boardTable = new JTable(new BoardTableModel()); JButton candidateMapBrowseButton = new JButton("..."); final JTextField configField = new JTextField(20); candidateMapBrowseButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); int result = chooser.showDialog(CommandApplet.this, "Select"); if (result == JFileChooser.APPROVE_OPTION) { configField.setText(chooser.getSelectedFile().getAbsolutePath()); } } }); JButton uploadButton = new JButton("Do Upload"); final URL finalMixnetConf = mixnetConf; uploadButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { String dirName = uploadDirField.getText().trim(); if (dirName.length() > 0) { Thread taskThread = new Thread(new FullUploadTask((BoardTableModel) boardTable.getModel(), dirName, finalMixnetConf, eventNotifier)); taskThread.setPriority(Thread.NORM_PRIORITY); taskThread.start(); } else { JOptionPane.showMessageDialog(SwingUtilities.windowForComponent(CommandApplet.this), "Please enter an upload source directory.", "Missing Field Error", JOptionPane.ERROR_MESSAGE); return; } } }); topTablePanel.add(uploadButton); JPanel shufflePanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); shufflePanel.add(new JLabel("Shuffle Plan:")); shufflePanel.add(shufflePlan); topTablePanel.add(shufflePanel); final JTextField keyID = new JTextField(15); JTextField threshold = new JTextField(3); keyID.setText("ECENCKEY"); threshold.setText("4"); JButton shuffleButton = new JButton("Shuffle and Download Selected"); shuffleButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { String planStr = shufflePlan.getText().trim(); String dirName = downloadDirField.getText().trim(); String configName = configField.getText().trim(); if (dirName.length() == 0) { JOptionPane.showMessageDialog(SwingUtilities.windowForComponent(CommandApplet.this), "Please enter a download directory.", "Missing Field Error", JOptionPane.ERROR_MESSAGE); return; } if (configName.length() == 0) { JOptionPane.showMessageDialog(SwingUtilities.windowForComponent(CommandApplet.this), "Please enter a candidate configuration file name.", "Missing Field Error", JOptionPane.ERROR_MESSAGE); return; } if (planStr.length() > 0) { String[] plan = planStr.split(","); for (int i = 0; i != plan.length; i++) { plan[i] = plan[i].trim(); if (plan[i].length() == 0) { JOptionPane.showMessageDialog(SwingUtilities.windowForComponent(CommandApplet.this), "Empty node name found.", "Syntax Error", JOptionPane.ERROR_MESSAGE); return; } } Thread taskThread = new Thread(new FullShuffleTask(new File(dirName), keyID.getText().trim(), (BoardTableModel) boardTable.getModel(), plan, finalMixnetConf, configField.getText().trim(), eventNotifier)); taskThread.setPriority(Thread.NORM_PRIORITY); taskThread.start(); } else { JOptionPane.showMessageDialog(SwingUtilities.windowForComponent(CommandApplet.this), "Please enter a shuffle plan.", "Missing Field Error", JOptionPane.ERROR_MESSAGE); } } }); JPanel downloadControlPanel = new JPanel(); downloadControlPanel.setLayout(new BoxLayout(downloadControlPanel, BoxLayout.Y_AXIS)); JPanel downloadKeyPanel = new JPanel(); downloadKeyPanel.setLayout(new BoxLayout(downloadKeyPanel, BoxLayout.X_AXIS)); JButton exportButton = new JButton("Export Key"); exportButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); int result = chooser.showDialog(CommandApplet.this, "Save"); if (result == JFileChooser.APPROVE_OPTION) { try { KeyService keyService = adminRegistrar.connect(KeyService.class); byte[] encPubKey = keyService.fetchPublicKey(keyID.getText().trim()); PEMWriter pWrt = new PEMWriter(new FileWriter(chooser.getSelectedFile().getAbsolutePath())); pWrt.writeObject(new MiscPEMGenerator(SubjectPublicKeyInfo.getInstance(encPubKey))); pWrt.close(); keyService.shutdown(); } catch (Exception e) { // TODO: e.printStackTrace(); } } } }); JPanel keyIDPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); keyIDPanel.add(new JLabel("Key ID: ")); keyIDPanel.add(keyID); JPanel thresholdPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); thresholdPanel.add(new JLabel("Threshold")); thresholdPanel.add(threshold); downloadKeyPanel.add(keyIDPanel); downloadKeyPanel.add(thresholdPanel); downloadKeyPanel.add(exportButton); JPanel candidateMapPanel = new JPanel(); candidateMapPanel.add(new JLabel("Candidate Config: ")); candidateMapPanel.add(configField); candidateMapPanel.add(candidateMapBrowseButton); JPanel downloadButtonPanel = new JPanel(); downloadButtonPanel.setLayout(new BoxLayout(downloadButtonPanel, BoxLayout.X_AXIS)); final JButton selectAllButton = new JButton("Select All"); selectAllButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { BoardTableModel tableModel = (BoardTableModel) boardTable.getModel(); if (selectAllButton.getText().startsWith("Sele")) { selectAllButton.setText("Deselect All"); for (BoardEntry entry : tableModel.getEntries()) { entry.setSelected(true); } } else { selectAllButton.setText("Select All"); for (BoardEntry entry : tableModel.getEntries()) { entry.setSelected(false); } } } }); downloadButtonPanel.add(selectAllButton); downloadButtonPanel.add(shuffleButton); downloadControlPanel.add(downloadKeyPanel); downloadControlPanel.add(candidateMapPanel); downloadControlPanel.add(downloadButtonPanel); topTablePanel.add(downloadControlPanel); topTablePanel.add(Box.createHorizontalGlue()); boardTable.getTableHeader().setPreferredSize( new Dimension(boardTable.getColumnModel().getTotalColumnWidth(), boardTable.getRowHeight(0) * 2)); tablePanel.add(topTablePanel); tablePanel.add(new JScrollPane(boardTable)); JPanel basePanel = new JPanel(); basePanel.setLayout(new BoxLayout(basePanel, BoxLayout.Y_AXIS)); topPanel.add(uploadPanel); topPanel.add(Box.createHorizontalGlue()); topPanel.add(downloadPanel); basePanel.add(topPanel); basePanel.add(tablePanel); try { MonitorService monitor = adminRegistrar.connect(MonitorService.class); monitor.addBulletinBoardListener(new NetworkBoardListener() { @Override public void boardChanged(String boardName, BoardDetail boardDetail) { BoardTableModel tableModel = (BoardTableModel) boardTable.getModel(); BoardEntry entry = tableModel.getEntry(boardName, boardDetail.getHost(), boardDetail.getBackupHost()); entry.setMessageCount(boardDetail.getMessageCount()); } }); } catch (RegistrarServiceException e) { // TODO: e.printStackTrace(); } this.getContentPane().add(basePanel); }
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 a v a 2 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); } }); 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.node.core.XimixNodeContext.java
License:Apache License
public XimixNodeContext(Map<String, ServicesConnection> peerMap, final Config nodeConfig, EventNotifier eventNotifier) throws ConfigException { this.description = nodeConfig.getConfigObject("description", new DescriptionConfigFactory()) .getDescription();/* ww w .j a va2 s . co m*/ this.peerMap = Collections.synchronizedMap(new HashMap<>(peerMap)); this.decouplers.put(Decoupler.BOARD_LISTENER, Executors.newSingleThreadExecutor()); this.decouplers.put(Decoupler.BOARD_REGISTRY, Executors.newSingleThreadExecutor()); this.decouplers.put(Decoupler.LISTENER, Executors.newSingleThreadExecutor()); this.decouplers.put(Decoupler.SERVICES, Executors.newSingleThreadExecutor()); this.decouplers.put(Decoupler.SHARING, Executors.newSingleThreadExecutor()); this.decouplers.put(Decoupler.MONITOR, Executors.newSingleThreadExecutor()); this.eventNotifier = eventNotifier; this.name = nodeConfig.getStringProperty("name"); // TODO: this.homeDirectory = nodeConfig.getHomeDirectory(); this.peerMap.remove(this.name); this.ecKeyManager = new ECKeyManager(this); this.blsKeyManager = new BLSKeyManager(this); try { this.keyManagerCaStore = KeyStore.getInstance("PKCS12", "BC"); } catch (GeneralSecurityException e) { throw new ConfigException("unable to create key store object: " + e.getMessage(), e); } if (homeDirectory != null) { try { PEMParser pParse = new PEMParser(new FileReader( new File(homeDirectory, nodeConfig.getStringProperty("trustAnchor") + ".pem"))); trustAnchor = new JcaX509CertificateConverter().setProvider("BC") .getCertificate((X509CertificateHolder) pParse.readObject()); pParse.close(); } catch (Exception e) { throw new ConfigException("unable to read trust anchor: " + e.getMessage(), e); } try { File keyManagerCaStoreFile = new File(homeDirectory, nodeConfig.getStringProperty("keyManagerStore") + ".p12"); char[] keyManagerPasswd = nodeConfig.getStringProperty("keyManagerPassword").toCharArray(); keyManagerCaStore.load(new FileInputStream(keyManagerCaStoreFile), keyManagerPasswd); setupKeyManager(homeDirectory, keyManagerPasswd, ecKeyManager); setupKeyManager(homeDirectory, keyManagerPasswd, blsKeyManager); } catch (GeneralSecurityException e) { throw new ConfigException("unable to create node key store: " + e.getMessage(), e); } catch (IOException e) { throw new ConfigException("unable to read node key store: " + e.getMessage(), e); } } else { // running in memory only mode. try { PEMParser pParse = new PEMParser(new InputStreamReader(this.getClass() .getResourceAsStream("/conf/" + nodeConfig.getStringProperty("trustAnchor") + ".pem"))); trustAnchor = new JcaX509CertificateConverter().setProvider("BC") .getCertificate((X509CertificateHolder) pParse.readObject()); pParse.close(); } catch (Exception e) { throw new ConfigException("unable to read trust anchor: " + e.getMessage(), e); } try { char[] keyManagerPasswd = nodeConfig.getStringProperty("keyManagerPassword").toCharArray(); keyManagerCaStore.load( this.getClass().getResourceAsStream( "/conf/" + nodeConfig.getStringProperty("keyManagerStore") + ".p12"), keyManagerPasswd); } catch (GeneralSecurityException e) { throw new ConfigException("unable to create node key store: " + e.getMessage(), e); } catch (IOException e) { throw new ConfigException("unable to read node key store: " + e.getMessage(), e); } } remoteServicesCache = new RemoteServicesCache(this); this.listeningSocketInfo = new ListeningSocketInfo(name, nodeConfig.getIntegerProperty("portNo"), nodeConfig.getIntegerProperty("portBacklog"), nodeConfig.getStringProperty("portAddress")); // // we schedule this bit to a new thread as the services require node context as an argument // and we want to make sure they are well formed. // this.getDecoupler(Decoupler.SERVICES).execute(new Runnable() { @Override public void run() { try { List<ServiceConfig> configs = nodeConfig.getConfigObjects("services", new NodeConfigFactory()); for (ServiceConfig config : configs) { if (config.getThrowable() != null) { getEventNotifier().notify(EventNotifier.Level.ERROR, config.getThrowable()); } } } catch (ConfigException e) { getEventNotifier().notify(EventNotifier.Level.ERROR, "Configuration error: " + e.getMessage(), e); } finally { setupCompleteLatch.countDown(); } } }); // now activate our peer connections for (final String node : getPeerMap().keySet()) { connectionExecutor.submit(new Runnable() { @Override public void run() { try { getPeerMap().get(node).activate(); } catch (Exception e) { getEventNotifier().notify(EventNotifier.Level.WARN, "Node " + node + " currently unavailable: " + e.getMessage(), e); } } }); } }
From source file:org.cryptoworkshop.ximix.test.tests.ShuffleDownloadDecryptionTest.java
License:Apache License
private void doShuffleDownloadTest(int numberOfPoints) throws Exception { SquelchingThrowableHandler handler = new SquelchingThrowableHandler(); handler.squelchType(SocketException.class); PEMParser pemParser = new PEMParser( new InputStreamReader(this.getClass().getResourceAsStream("/conf/trustCa.pem"))); X509Certificate trustAnchor;/* w ww .ja v a 2s. c om*/ try { trustAnchor = new JcaX509CertificateConverter().setProvider("BC") .getCertificate((X509CertificateHolder) pemParser.readObject()); } catch (Exception e) { throw new IllegalStateException("Can't parse trust anchor.", e); } // // Set up nodes. // File tmpDir = File.createTempFile("xmx", ".wrk"); tmpDir.delete(); tmpDir.mkdir(); XimixNode nodeOne = getXimixNode(new File(tmpDir, "node1"), "/conf/mixnet.xml", "/conf/node1.xml", handler); NodeTestUtil.launch(nodeOne); XimixNode nodeTwo = getXimixNode(new File(tmpDir, "node2"), "/conf/mixnet.xml", "/conf/node2.xml", handler); NodeTestUtil.launch(nodeTwo); XimixNode nodeThree = getXimixNode(new File(tmpDir, "node3"), "/conf/mixnet.xml", "/conf/node3.xml", handler); NodeTestUtil.launch(nodeThree); XimixNode nodeFour = getXimixNode(new File(tmpDir, "node4"), "/conf/mixnet.xml", "/conf/node4.xml", handler); NodeTestUtil.launch(nodeFour); XimixNode nodeFive = getXimixNode(new File(tmpDir, "node5"), "/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. // final ECPoint[] plainText1 = new ECPoint[numberOfPoints]; final ECPoint[] plainText2 = new ECPoint[numberOfPoints]; final Set<ECPoint> plain1 = new HashSet<>(); final 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<>(); 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 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"); 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()); Map<String, byte[][]> seedAndWitnessesMap = commandService.downloadShuffleSeedsAndWitnesses("FRED", shuffleOp.getOperationNumber(), "A", "C", "D"); 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", "D"); transcriptCompleted.await(); LinkIndexVerifier.Builder builder = new LinkIndexVerifier.Builder(numberOfPoints); 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 { fail("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))) { fail("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) .build(), transcriptListener, "A", "C", "D"); witnessTranscriptCompleted.await(); for (Integer step : witnessTranscripts.keySet()) { byte[] bytes = witnessTranscripts.get(step); if (!signatureVerifier.signatureVerified(new CMSSignedDataParser( new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(), bytes))) { fail("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, false, 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("ECKEY").withThreshold(4) .withPairingEnabled(true).withNodes("A", "B", "C", "D").build(), streamSeedCommitments, streamSeedsAndWitnesses, streamGeneralTranscripts, streamWitnessTranscripts, new DownloadOperationListener() { @Override public void messageDownloaded(int index, byte[] message, List<byte[]> proofs) { PointSequence decrypted = PointSequence.getInstance(pubKey.getParameters().getCurve(), message); Assert.assertTrue(plain1.remove(decrypted.getECPoints()[0]) && plain2.remove(decrypted.getECPoints()[1])); } @Override public void completed() { shuffleOutputDownloadCompleted.countDown(); } @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(); TestCase.assertTrue(plain1.isEmpty()); TestCase.assertTrue(plain2.isEmpty()); NodeTestUtil.shutdownNodes(); client.shutdown(); commandService.shutdown(); delete(tmpDir); }
From source file:org.cryptoworkshop.ximix.test.tests.ShuffleDownloadDecryptionTest.java
License:Apache License
private void doTestWithPairingFlag(int numberOfPoints, boolean isPairingEnabled) throws Exception { SquelchingThrowableHandler handler = new SquelchingThrowableHandler(); handler.squelchType(SocketException.class); PEMParser pemParser = new PEMParser( new InputStreamReader(this.getClass().getResourceAsStream("/conf/trustCa.pem"))); X509Certificate trustAnchor;/*www . jav a2 s. c o m*/ try { trustAnchor = new JcaX509CertificateConverter().setProvider("BC") .getCertificate((X509CertificateHolder) pemParser.readObject()); } catch (Exception e) { throw new IllegalStateException("Can't parse trust anchor.", e); } // // Set up nodes. // File tmpDir = File.createTempFile("xmx", ".wrk"); tmpDir.delete(); tmpDir.mkdir(); XimixNode nodeOne = getXimixNode(new File(tmpDir, "node1"), "/conf/mixnet.xml", "/conf/node1.xml", handler); NodeTestUtil.launch(nodeOne); XimixNode nodeTwo = getXimixNode(new File(tmpDir, "node2"), "/conf/mixnet.xml", "/conf/node2.xml", handler); NodeTestUtil.launch(nodeTwo); XimixNode nodeThree = getXimixNode(new File(tmpDir, "node3"), "/conf/mixnet.xml", "/conf/node3.xml", handler); NodeTestUtil.launch(nodeThree); XimixNode nodeFour = getXimixNode(new File(tmpDir, "node4"), "/conf/mixnet.xml", "/conf/node4.xml", handler); NodeTestUtil.launch(nodeFour); XimixNode nodeFive = getXimixNode(new File(tmpDir, "node5"), "/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. // final ECPoint[] plainText1 = new ECPoint[numberOfPoints]; final ECPoint[] plainText2 = new ECPoint[numberOfPoints]; final Set<ECPoint> plain1 = new HashSet<>(); final 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<>(); 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 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", "A", "C", "D"); 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()); Map<String, byte[][]> seedAndWitnessesMap = commandService.downloadShuffleSeedsAndWitnesses("FRED", shuffleOp.getOperationNumber(), "A", "C", "D"); 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).withPairingEnabled(isPairingEnabled) .build(), transcriptListener, "A", "C", "D"); transcriptCompleted.await(); LinkIndexVerifier.Builder builder = new LinkIndexVerifier.Builder(numberOfPoints); 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 { fail("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))) { fail("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(isPairingEnabled).build(), transcriptListener, "A", "C", "D"); 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, isPairingEnabled, 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(); } 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("ECKEY").withThreshold(4) .withPairingEnabled(isPairingEnabled).withNodes("A", "B", "C", "D").build(), streamSeedCommitments, streamSeedsAndWitnesses, streamGeneralTranscripts, streamWitnessTranscripts, new DownloadOperationListener() { @Override public void messageDownloaded(int index, byte[] message, List<byte[]> proofs) { PointSequence decrypted = PointSequence.getInstance(pubKey.getParameters().getCurve(), message); Assert.assertTrue(plain1.remove(decrypted.getECPoints()[0]) && plain2.remove(decrypted.getECPoints()[1])); } @Override public void completed() { shuffleOutputDownloadCompleted.countDown(); } @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(); TestCase.assertTrue(plain1.isEmpty()); TestCase.assertTrue(plain2.isEmpty()); NodeTestUtil.shutdownNodes(); client.shutdown(); commandService.shutdown(); delete(tmpDir); }
From source file:org.curioswitch.common.server.framework.crypto.KeyUtil.java
License:Open Source License
private static PEMParser newParser(byte[] encodedKey) { return new PEMParser(new InputStreamReader(new ByteArrayInputStream(encodedKey), StandardCharsets.UTF_8)); }
From source file:org.dataone.proto.trove.net.SocketFactoryManager.java
License:Apache License
/** * Load PEM file contents into in-memory keystore NOTE: this implementation uses Bouncy Castle security provider * * @return the keystore that will provide the material * @throws KeyStoreException//from w w w .j a v a 2s. c om * @throws CertificateException * @throws NoSuchAlgorithmException * @throws IOException */ private KeyStore getKeyStore() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { // if the location has been set, use it KeyStore keyStore = null; Object pemObject = null; keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, keyStorePassword.toCharArray()); // get the private key and certificate from the PEM // TODO: find a way to do this with default Java provider (not Bouncy Castle)? Security.addProvider(new BouncyCastleProvider()); PEMParser pemReader = new PEMParser(new FileReader(clientCertificateLocation)); X509Certificate certificate = null; PrivateKey privateKey = null; KeyPair keyPair = null; while ((pemObject = pemReader.readObject()) != null) { if (pemObject instanceof PrivateKey) { privateKey = (PrivateKey) pemObject; } else if (pemObject instanceof KeyPair) { keyPair = (KeyPair) pemObject; privateKey = keyPair.getPrivate(); } else if (pemObject instanceof X509Certificate) { certificate = (X509Certificate) pemObject; } } if (certificate == null) { log.warn("Certificate is null"); } else { if (certificate.getSubjectX500Principal().getName(X500Principal.RFC2253) .equals(certificate.getIssuerX500Principal().getName(X500Principal.RFC2253))) { log.warn("Certificate is Self Signed"); } } Certificate[] chain = new Certificate[] { certificate }; // set the entry keyStore.setKeyEntry("cilogon", privateKey, keyStorePassword.toCharArray(), chain); return keyStore; }
From source file:org.diqube.ticket.TicketRsaKeyManager.java
License:Open Source License
@PostConstruct public void initialize() { List<RSAKeyParameters> allPublicKeys = new ArrayList<>(); publicValidationKeys = Collections.unmodifiableList(allPublicKeys); provider.getPemFiles().whenComplete((pemFiles, error) -> { if (error != null) throw new RuntimeException("Exception while identifying .pem files!", error); if (pemFiles.isEmpty()) throw new RuntimeException("No .pem files configured that can be used to sign/validate tickets!"); for (int i = 0; i < pemFiles.size(); i++) { String pemFileName = pemFiles.get(i).getLeft(); String pemPassword = pemFiles.get(i).getRight(); try (InputStream pemStream = pemFiles.get(i).getMiddle().get()) { Reader pemReader = new InputStreamReader(pemStream); try (PEMParser parser = new PEMParser(pemReader)) { Object o = parser.readObject(); SubjectPublicKeyInfo publicKeyInfo = null; PrivateKeyInfo privateKeyInfo = null; if (o instanceof PEMEncryptedKeyPair) { if (pemPassword == null) throw new RuntimeException("PEM file '" + pemFileName + "' is password protected, but the password is not configured."); PEMDecryptorProvider decryptionProvider = new JcePEMDecryptorProviderBuilder() .build(pemPassword.toCharArray()); PEMEncryptedKeyPair encryptedKeyPair = (PEMEncryptedKeyPair) o; PEMKeyPair keyPair = encryptedKeyPair.decryptKeyPair(decryptionProvider); publicKeyInfo = keyPair.getPublicKeyInfo(); privateKeyInfo = keyPair.getPrivateKeyInfo(); } else if (o instanceof PEMKeyPair) { PEMKeyPair keyPair = (PEMKeyPair) o; publicKeyInfo = keyPair.getPublicKeyInfo(); privateKeyInfo = keyPair.getPrivateKeyInfo(); } else if (o instanceof SubjectPublicKeyInfo) publicKeyInfo = (SubjectPublicKeyInfo) o; else throw new RuntimeException("Could not identify content of pem file '" + pemFileName + "': " + o.toString()); if (publicKeyInfo == null) throw new RuntimeException("Could not load '" + pemFileName + "' because it did not contain a public key."); if (privateKeyInfo == null) logger.info("Loading public key from '{}'.", pemFileName); else if (!provider.filesWithPrivateKeyAreRequired()) throw new RuntimeException("File '" + pemFileName + "' contains a private key, but only public keys are " + "accepted. Please extract the public key from the current file and configure diqube to use " + "that new file."); allPublicKeys.add((RSAKeyParameters) PublicKeyFactory.createKey(publicKeyInfo)); if (i == 0 && privateKeyInfo != null) { logger.info("Loading private key from '{}' and will use that for signing tickets.", pemFileName); privateSigningKey = (RSAPrivateCrtKeyParameters) PrivateKeyFactory .createKey(privateKeyInfo); }/*from w w w .j ava 2 s .c o m*/ } } catch (IOException e) { throw new RuntimeException("Could not interact with '" + pemFileName + "'. Correct password?", e); } } if (privateSigningKey == null && provider.filesWithPrivateKeyAreRequired()) throw new RuntimeException("A .pem file containing a private key for signing tickets is required. " + "Make sure that the first configured .pem file contains a private key."); initialized = true; }); }
From source file:org.eclipse.che.infrastructure.docker.client.DockerCertificates.java
License:Open Source License
private static PrivateKey getPrivateKey(Path clientKeyPath) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { final PEMKeyPair clientKeyPair; try (Reader reader = Files.newBufferedReader(clientKeyPath, Charset.defaultCharset())) { try (PEMParser parser = new PEMParser(reader)) { clientKeyPair = (PEMKeyPair) parser.readObject(); }/* w w w. ja v a 2s . c o m*/ } final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(clientKeyPair.getPrivateKeyInfo().getEncoded()); final KeyFactory kf = KeyFactory.getInstance("RSA"); return kf.generatePrivate(spec); }