List of usage examples for org.bouncycastle.cert.jcajce JcaX509CertificateConverter JcaX509CertificateConverter
public JcaX509CertificateConverter()
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()); }//from w w w. ja v a 2 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 .co 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();//w ww .j a v a 2 s.com 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;/*from w w w. j av 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", "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;//from w ww .j ava 2s .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.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESChecker.java
License:Open Source License
/** * Validation is done only on digital signatures with a single signer. Valid * only with content of type DATA.: OID ContentType 1.2.840.113549.1.9.3 = * OID Data 1.2.840.113549.1.7.1/*from w w w. j a va 2s.co m*/ * * @param content Is only necessary to inform if the PKCS7 package is NOT * ATTACHED type. If it is of type attached, this parameter will be * replaced by the contents of the PKCS7 package. * @param signedData Value in bytes of the PKCS7 package, such as the * contents of a ".p7s" file. It is not only signature as in the * case of PKCS1. */ // TODO: Implementar validao de co-assinaturas public boolean check(byte[] content, byte[] signedData) throws SignerException { Security.addProvider(new BouncyCastleProvider()); CMSSignedData cmsSignedData = null; try { if (content == null) { if (this.checkHash) { cmsSignedData = new CMSSignedData(this.hashes, signedData); this.checkHash = false; } else { cmsSignedData = new CMSSignedData(signedData); } } else { if (this.getAttached(signedData, false) != null) { cmsSignedData = new CMSSignedData(signedData); } else { cmsSignedData = new CMSSignedData(new CMSProcessableByteArray(content), signedData); } } } catch (CMSException ex) { throw new SignerException(cadesMessagesBundle.getString("error.invalid.bytes.pkcs7"), ex); } // Quantidade inicial de assinaturas validadas int verified = 0; Store<?> certStore = cmsSignedData.getCertificates(); SignerInformationStore signers = cmsSignedData.getSignerInfos(); Iterator<?> it = signers.getSigners().iterator(); // Realizao da verificao bsica de todas as assinaturas while (it.hasNext()) { SignatureInformations signatureInfo = new SignatureInformations(); try { SignerInformation signerInfo = (SignerInformation) it.next(); SignerInformationStore signerInfoStore = signerInfo.getCounterSignatures(); logger.info("Foi(ram) encontrada(s) " + signerInfoStore.size() + " contra-assinatura(s)."); @SuppressWarnings("unchecked") Collection<?> certCollection = certStore.getMatches(signerInfo.getSID()); Iterator<?> certIt = certCollection.iterator(); X509CertificateHolder certificateHolder = (X509CertificateHolder) certIt.next(); X509Certificate varCert = new JcaX509CertificateConverter().getCertificate(certificateHolder); CRLValidator cV = new CRLValidator(); try { cV.validate(varCert); } catch (CertificateValidatorCRLException cvce) { signatureInfo.getValidatorErrors().add(cvce.getMessage()); logger.info(cvce.getMessage()); } catch (CertificateRevocationException cre) { signatureInfo.getValidatorErrors().add(cre.getMessage()); logger.info("certificado revogado"); } PeriodValidator pV = new PeriodValidator(); try { pV.validate(varCert); } catch (CertificateValidatorException cve) { signatureInfo.getValidatorErrors().add(cve.getMessage()); } if (signerInfo.verify( new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certificateHolder))) { verified++; logger.info(cadesMessagesBundle.getString("info.signature.valid.seq", verified)); } // recupera atributos assinados logger.info(cadesMessagesBundle.getString("info.signed.attribute")); String varOIDPolicy = PKCSObjectIdentifiers.id_aa_ets_sigPolicyId.getId(); AttributeTable signedAttributes = signerInfo.getSignedAttributes(); if ((signedAttributes == null) || (signedAttributes != null && signedAttributes.size() == 0)) { signatureInfo.getValidatorErrors() .add(cadesMessagesBundle.getString("error.signed.attribute.table.not.found")); logger.info(cadesMessagesBundle.getString("error.signed.attribute.table.not.found")); //throw new SignerException(cadesMessagesBundle.getString("error.signed.attribute.table.not.found")); } else { //Validando atributos assinados de acordo com a politica Attribute idSigningPolicy = null; idSigningPolicy = signedAttributes.get(new ASN1ObjectIdentifier(varOIDPolicy)); if (idSigningPolicy == null) { signatureInfo.getValidatorErrors().add( cadesMessagesBundle.getString("error.pcks7.attribute.not.found", varOIDPolicy)); } else { for (Enumeration<?> p = idSigningPolicy.getAttrValues().getObjects(); p .hasMoreElements();) { String policyOnSignature = p.nextElement().toString(); for (PolicyFactory.Policies pv : PolicyFactory.Policies.values()) { if (policyOnSignature.contains(pv.getUrl())) { setSignaturePolicy(pv); break; } } } } } Date dataHora = null; if (signedAttributes != null) { // Valida o atributo ContentType Attribute attributeContentType = signedAttributes.get(CMSAttributes.contentType); if (attributeContentType == null) { signatureInfo.getValidatorErrors().add( cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "ContentType")); //throw new SignerException(cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "ContentType")); logger.info( cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "ContentType")); } if (!attributeContentType.getAttrValues().getObjectAt(0).equals(ContentInfo.data)) { signatureInfo.getValidatorErrors() .add(cadesMessagesBundle.getString("error.content.not.data")); //throw new SignerException(cadesMessagesBundle.getString("error.content.not.data")); logger.info(cadesMessagesBundle.getString("error.content.not.data")); } // Validando o atributo MessageDigest Attribute attributeMessageDigest = signedAttributes.get(CMSAttributes.messageDigest); if (attributeMessageDigest == null) { throw new SignerException( cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "MessageDigest")); } // Mostra data e hora da assinatura, no carimbo de tempo Attribute timeAttribute = signedAttributes.get(CMSAttributes.signingTime); if (timeAttribute != null) { dataHora = (((ASN1UTCTime) timeAttribute.getAttrValues().getObjectAt(0)).getDate()); logger.info(cadesMessagesBundle.getString("info.date.utc", dataHora)); } else { logger.info(cadesMessagesBundle.getString("info.date.utc", "N/D")); } } if (signaturePolicy == null) { signatureInfo.getValidatorErrors().add( cadesMessagesBundle.getString("error.policy.on.component.not.found", varOIDPolicy)); logger.info(cadesMessagesBundle.getString("error.policy.on.component.not.found")); } else { if (signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules() .getSignerAndVeriferRules().getSignerRules().getMandatedSignedAttr() .getObjectIdentifiers() != null) { for (ObjectIdentifier objectIdentifier : signaturePolicy.getSignPolicyInfo() .getSignatureValidationPolicy().getCommonRules().getSignerAndVeriferRules() .getSignerRules().getMandatedSignedAttr().getObjectIdentifiers()) { String oi = objectIdentifier.getValue(); Attribute signedAtt = signedAttributes.get(new ASN1ObjectIdentifier(oi)); logger.info(oi); if (signedAtt == null) { signatureInfo.getValidatorErrors().add(cadesMessagesBundle.getString( "error.signed.attribute.not.found", oi, signaturePolicy.getSignPolicyInfo().getSignPolicyIdentifier().getValue())); } } } } // recupera os atributos NO assinados logger.info(cadesMessagesBundle.getString("info.unsigned.attribute")); AttributeTable unsignedAttributes = signerInfo.getUnsignedAttributes(); if ((unsignedAttributes == null) || (unsignedAttributes != null && unsignedAttributes.size() == 0)) { // Apenas info pois a RB no tem atributos no assinados logger.info(cadesMessagesBundle.getString("error.unsigned.attribute.table.not.found")); } if (signaturePolicy != null) { // Validando atributos NO assinados de acordo com a politica if (signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules() .getSignerAndVeriferRules().getSignerRules().getMandatedUnsignedAttr() .getObjectIdentifiers() != null) { for (ObjectIdentifier objectIdentifier : signaturePolicy.getSignPolicyInfo() .getSignatureValidationPolicy().getCommonRules().getSignerAndVeriferRules() .getSignerRules().getMandatedUnsignedAttr().getObjectIdentifiers()) { String oi = objectIdentifier.getValue(); Attribute unSignedAtt = unsignedAttributes.get(new ASN1ObjectIdentifier(oi)); logger.info(oi); if (unSignedAtt == null) { signatureInfo.getValidatorErrors().add(cadesMessagesBundle.getString( "error.unsigned.attribute.not.found", oi, signaturePolicy.getSignPolicyInfo().getSignPolicyIdentifier().getValue())); } if (oi.equalsIgnoreCase(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken.getId())) { //Verificando timeStamp try { byte[] varSignature = signerInfo.getSignature(); Timestamp varTimeStampSigner = validateTimestamp(unSignedAtt, varSignature); signatureInfo.setTimeStampSigner(varTimeStampSigner); } catch (Exception ex) { signatureInfo.getValidatorErrors().add(ex.getMessage()); // nas assinaturas feitas na applet o unsignedAttributes.get gera exceo. } } if (oi.equalsIgnoreCase("1.2.840.113549.1.9.16.2.25")) { logger.info("++++++++++ EscTimeStamp ++++++++++++"); } } } } LinkedList<X509Certificate> varChain = (LinkedList<X509Certificate>) CAManager.getInstance() .getCertificateChain(varCert); if (varChain.size() < 3) { signatureInfo.getValidatorErrors() .add(cadesMessagesBundle.getString("error.no.ca", varCert.getIssuerDN())); logger.info(cadesMessagesBundle.getString("error.no.ca", varCert.getIssuerDN())); } signatureInfo.setSignDate(dataHora); signatureInfo.setChain(varChain); signatureInfo.setSignaturePolicy(signaturePolicy); this.getSignaturesInfo().add(signatureInfo); } catch (OperatorCreationException | java.security.cert.CertificateException ex) { signatureInfo.getValidatorErrors().add(ex.getMessage()); logger.info(ex.getMessage()); } catch (CMSException ex) { // When file is mismatch with sign if (ex instanceof CMSSignerDigestMismatchException) { signatureInfo.getValidatorErrors() .add(cadesMessagesBundle.getString("error.signature.mismatch")); logger.info(cadesMessagesBundle.getString("error.signature.mismatch")); throw new SignerException(cadesMessagesBundle.getString("error.signature.mismatch"), ex); } else { signatureInfo.getValidatorErrors() .add(cadesMessagesBundle.getString("error.signature.invalid")); logger.info(cadesMessagesBundle.getString("error.signature.invalid")); throw new SignerException(cadesMessagesBundle.getString("error.signature.invalid"), ex); } } catch (ParseException e) { signatureInfo.getValidatorErrors().add(e.getMessage()); logger.info(e.getMessage()); } } logger.info(cadesMessagesBundle.getString("info.signature.verified", verified)); // TODO Efetuar o parsing da estrutura CMS return true; }
From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESSigner.java
License:Open Source License
/** * Validation is done only on digital signatures with a single signer. Valid * only with content of type DATA.: OID ContentType 1.2.840.113549.1.9.3 = * OID Data 1.2.840.113549.1.7.1/* w w w.j a v a 2 s . c o m*/ * * @param content Is only necessary to inform if the PKCS7 package is NOT * ATTACHED type. If it is of type attached, this parameter will be * replaced by the contents of the PKCS7 package. * @param signedData Value in bytes of the PKCS7 package, such as the * contents of a ".p7s" file. It is not only signature as in the * case of PKCS1. * @deprecated moved to CadESChecker */ @SuppressWarnings("unchecked") @Override public boolean check(byte[] content, byte[] signedData) throws SignerException { Security.addProvider(new BouncyCastleProvider()); CMSSignedData cmsSignedData = null; try { if (content == null) { if (this.checkHash) { cmsSignedData = new CMSSignedData(this.hashes, signedData); this.checkHash = false; } else { cmsSignedData = new CMSSignedData(signedData); } } else { cmsSignedData = new CMSSignedData(new CMSProcessableByteArray(content), signedData); } } catch (CMSException ex) { throw new SignerException(cadesMessagesBundle.getString("error.invalid.bytes.pkcs7"), ex); } // Quantidade inicial de assinaturas validadas int verified = 0; Store<?> certStore = cmsSignedData.getCertificates(); SignerInformationStore signers = cmsSignedData.getSignerInfos(); Iterator<?> it = signers.getSigners().iterator(); // Realizao da verificao bsica de todas as assinaturas while (it.hasNext()) { try { SignerInformation signer = (SignerInformation) it.next(); SignerInformationStore s = signer.getCounterSignatures(); SignatureInformations si = new SignatureInformations(); logger.info("Foi(ram) encontrada(s) " + s.size() + " contra-assinatura(s)."); Collection<?> certCollection = certStore.getMatches(signer.getSID()); Iterator<?> certIt = certCollection.iterator(); X509CertificateHolder certificateHolder = (X509CertificateHolder) certIt.next(); X509Certificate varCert = new JcaX509CertificateConverter().getCertificate(certificateHolder); PeriodValidator pV = new PeriodValidator(); try { pV.validate(varCert); } catch (CertificateValidatorException cve) { si.getValidatorErrors().add(cve.getMessage()); } CRLValidator cV = new CRLValidator(); try { cV.validate(varCert); } catch (CertificateValidatorCRLException cvce) { si.getValidatorErrors().add(cvce.getMessage()); } if (signer.verify( new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certificateHolder))) { verified++; logger.info(cadesMessagesBundle.getString("info.signature.valid.seq", verified)); } // Realiza a verificao dos atributos assinados logger.info(cadesMessagesBundle.getString("info.signed.attribute")); AttributeTable signedAttributes = signer.getSignedAttributes(); if ((signedAttributes == null) || (signedAttributes != null && signedAttributes.size() == 0)) { throw new SignerException( cadesMessagesBundle.getString("error.signed.attribute.table.not.found")); } // Realiza a verificao dos atributos no assinados logger.info(cadesMessagesBundle.getString("info.unsigned.attribute")); AttributeTable unsignedAttributes = signer.getUnsignedAttributes(); if ((unsignedAttributes == null) || (unsignedAttributes != null && unsignedAttributes.size() == 0)) { logger.info(cadesMessagesBundle.getString("error.unsigned.attribute.table.not.found")); } // Mostra data e hora da assinatura, no carimbo de tempo Attribute signingTime = signedAttributes.get(CMSAttributes.signingTime); Date dataHora = null; if (signingTime != null) { dataHora = (((ASN1UTCTime) signingTime.getAttrValues().getObjectAt(0)).getDate()); logger.info(cadesMessagesBundle.getString("info.date.utc", dataHora)); } else { logger.info(cadesMessagesBundle.getString("info.date.utc", "N/D")); } logger.info(cadesMessagesBundle.getString("info.attribute.validation")); // Valida o atributo ContentType Attribute attributeContentType = signedAttributes.get(CMSAttributes.contentType); if (attributeContentType == null) { throw new SignerException( cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "ContentType")); } if (!attributeContentType.getAttrValues().getObjectAt(0).equals(ContentInfo.data)) { throw new SignerException(cadesMessagesBundle.getString("error.content.not.data")); } // Validando o atributo MessageDigest Attribute attributeMessageDigest = signedAttributes.get(CMSAttributes.messageDigest); if (attributeMessageDigest == null) { throw new SignerException( cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "MessageDigest")); } // Validando o atributo MessageDigest Attribute idSigningPolicy = null; idSigningPolicy = signedAttributes .get(new ASN1ObjectIdentifier(PKCSObjectIdentifiers.id_aa_ets_sigPolicyId.getId())); if (idSigningPolicy == null) { throw new SignerException( cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "idSigningPolicy")); } //Verificando timeStamp try { Attribute attributeTimeStamp = null; attributeTimeStamp = unsignedAttributes.get( new ASN1ObjectIdentifier(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken.getId())); if (attributeTimeStamp != null) { byte[] varSignature = signer.getSignature(); Timestamp varTimeStampSigner = validateTimestamp(attributeTimeStamp, varSignature); si.setTimeStampSigner(varTimeStampSigner); } } catch (Exception ex) { // nas assinaturas feitas na applet o unsignedAttributes.get gera exceo. } LinkedList<X509Certificate> varChain = (LinkedList<X509Certificate>) CAManager.getInstance() .getCertificateChain(varCert); si.setSignDate(dataHora); si.setChain(varChain); si.setSignaturePolicy(signaturePolicy); this.getSignatureInfo().add(si); } catch (OperatorCreationException | java.security.cert.CertificateException ex) { throw new SignerException(ex); } catch (CMSException ex) { // When file is mismatch with sign if (ex instanceof CMSSignerDigestMismatchException) throw new SignerException(cadesMessagesBundle.getString("error.signature.mismatch"), ex); else throw new SignerException(cadesMessagesBundle.getString("error.signature.invalid"), ex); } catch (ParseException e) { throw new SignerException(e); } } logger.info(cadesMessagesBundle.getString("info.signature.verified", verified)); // TODO Efetuar o parsing da estrutura CMS return true; }
From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESSigner.java
License:Open Source License
private Collection<X509Certificate> getSignersCertificates(CMSSignedData previewSignerData) { Collection<X509Certificate> result = new HashSet<X509Certificate>(); Store<?> certStore = previewSignerData.getCertificates(); SignerInformationStore signers = previewSignerData.getSignerInfos(); Iterator<?> it = signers.getSigners().iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); @SuppressWarnings("unchecked") Collection<?> certCollection = certStore.getMatches(signer.getSID()); Iterator<?> certIt = certCollection.iterator(); X509CertificateHolder certificateHolder = (X509CertificateHolder) certIt.next(); try {//w w w . jav a 2 s. c o m result.add(new JcaX509CertificateConverter().getCertificate(certificateHolder)); } catch (CertificateException error) { } } return result; }
From source file:org.eclipse.andmore.android.certmanager.core.KeyStoreUtils.java
License:Apache License
/** * Create a new X509 certificate for a given KeyPair * //ww w . ja va 2 s . c o m * @param keyPair * the {@link KeyPair} used to create the certificate, * RSAPublicKey and RSAPrivateKey are mandatory on keyPair, * IllegalArgumentExeption will be thrown otherwise. * @param issuerName * The issuer name to be used on the certificate * @param ownerName * The owner name to be used on the certificate * @param expireDate * The expire date * @return The {@link X509Certificate} * @throws IOException * @throws OperatorCreationException * @throws CertificateException */ public static X509Certificate createX509Certificate(KeyPair keyPair, CertificateDetailsInfo certDetails) throws IOException, OperatorCreationException, CertificateException { PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); if (!(publicKey instanceof RSAPublicKey) || !(privateKey instanceof RSAPrivateKey)) { throw new IllegalArgumentException(CertificateManagerNLS.KeyStoreUtils_RSA_Keys_Expected); } RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey; // Transform the PublicKey into the BouncyCastle expected format ASN1InputStream asn1InputStream = null; X509Certificate x509Certificate = null; try { asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(rsaPublicKey.getEncoded())); SubjectPublicKeyInfo pubKey = new SubjectPublicKeyInfo((ASN1Sequence) asn1InputStream.readObject()); X500NameBuilder nameBuilder = new X500NameBuilder(new BCStrictStyle()); addField(BCStyle.C, certDetails.getCountry(), nameBuilder); addField(BCStyle.ST, certDetails.getState(), nameBuilder); addField(BCStyle.L, certDetails.getLocality(), nameBuilder); addField(BCStyle.O, certDetails.getOrganization(), nameBuilder); addField(BCStyle.OU, certDetails.getOrganizationUnit(), nameBuilder); addField(BCStyle.CN, certDetails.getCommonName(), nameBuilder); X500Name subjectName = nameBuilder.build(); X500Name issuerName = subjectName; X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuerName, BigInteger.valueOf(new SecureRandom().nextInt()), Calendar.getInstance().getTime(), certDetails.getExpirationDate(), subjectName, pubKey); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA"); //$NON-NLS-1$ AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); BcContentSignerBuilder sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId); // Create RSAKeyParameters, the private key format expected by // Bouncy Castle RSAKeyParameters keyParams = new RSAKeyParameters(true, rsaPrivateKey.getPrivateExponent(), rsaPrivateKey.getModulus()); ContentSigner contentSigner = sigGen.build(keyParams); X509CertificateHolder certificateHolder = certBuilder.build(contentSigner); // Convert the X509Certificate from BouncyCastle format to the // java.security format JcaX509CertificateConverter certConverter = new JcaX509CertificateConverter(); x509Certificate = certConverter.getCertificate(certificateHolder); } finally { if (asn1InputStream != null) { try { asn1InputStream.close(); } catch (IOException e) { AndmoreLogger .error("Could not close stream while creating X509 certificate. " + e.getMessage()); } } } return x509Certificate; }
From source file:org.eclipse.milo.opcua.stack.core.util.SelfSignedCertificateGenerator.java
License:Open Source License
public X509Certificate generateSelfSigned(KeyPair keyPair, Date notBefore, Date notAfter, @Nullable String commonName, @Nullable String organization, @Nullable String organizationalUnit, @Nullable String localityName, @Nullable String stateName, @Nullable String countryCode, @Nullable String applicationUri, List<String> dnsNames, List<String> ipAddresses, String signatureAlgorithm) throws Exception { X500NameBuilder nameBuilder = new X500NameBuilder(); if (commonName != null) { nameBuilder.addRDN(BCStyle.CN, commonName); }/*ww w.jav a2 s .c om*/ if (organization != null) { nameBuilder.addRDN(BCStyle.O, organization); } if (organizationalUnit != null) { nameBuilder.addRDN(BCStyle.OU, organizationalUnit); } if (localityName != null) { nameBuilder.addRDN(BCStyle.L, localityName); } if (stateName != null) { nameBuilder.addRDN(BCStyle.ST, stateName); } if (countryCode != null) { nameBuilder.addRDN(BCStyle.C, countryCode); } X500Name name = nameBuilder.build(); // Using the current timestamp as the certificate serial number BigInteger certSerialNumber = new BigInteger(Long.toString(System.currentTimeMillis())); SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo .getInstance(keyPair.getPublic().getEncoded()); X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(name, certSerialNumber, notBefore, notAfter, name, subjectPublicKeyInfo); BasicConstraints basicConstraints = new BasicConstraints(true); // Authority Key Identifier addAuthorityKeyIdentifier(certificateBuilder, keyPair); // Basic Constraints addBasicConstraints(certificateBuilder, basicConstraints); // Key Usage addKeyUsage(certificateBuilder); // Extended Key Usage addExtendedKeyUsage(certificateBuilder); // Subject Alternative Name addSubjectAlternativeNames(certificateBuilder, keyPair, applicationUri, dnsNames, ipAddresses); ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithm) .setProvider(new BouncyCastleProvider()).build(keyPair.getPrivate()); X509CertificateHolder certificateHolder = certificateBuilder.build(contentSigner); return new JcaX509CertificateConverter().getCertificate(certificateHolder); }