List of usage examples for org.bouncycastle.operator.jcajce JcaDigestCalculatorProviderBuilder JcaDigestCalculatorProviderBuilder
public JcaDigestCalculatorProviderBuilder()
From source file:org.cesecore.certificates.ca.X509CA.java
License:Open Source License
@Override public byte[] createPKCS7(CryptoToken cryptoToken, Certificate cert, boolean includeChain) throws SignRequestSignatureException { // First verify that we signed this certificate try {//from ww w. j a v a 2 s .co m if (cert != null) { final PublicKey verifyKey; final X509Certificate cacert = (X509Certificate) getCACertificate(); if (cacert != null) { verifyKey = cacert.getPublicKey(); } else { verifyKey = cryptoToken .getPublicKey(getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)); } cert.verify(verifyKey); } } catch (CryptoTokenOfflineException e) { throw new SignRequestSignatureException("The cryptotoken was not available, could not create a PKCS7", e); } catch (InvalidKeyException e) { throw new SignRequestSignatureException("The specified certificate contains the wrong public key.", e); } catch (CertificateException e) { throw new SignRequestSignatureException("An encoding error was encountered.", e); } catch (NoSuchAlgorithmException e) { throw new SignRequestSignatureException( "The certificate provided was signed with an invalid algorithm.", e); } catch (NoSuchProviderException e) { throw new SignRequestSignatureException( "The crypto provider was not found for verification of the certificate.", e); } catch (SignatureException e) { throw new SignRequestSignatureException("Cannot verify certificate in createPKCS7(), did I sign this?", e); } Collection<Certificate> chain = getCertificateChain(); ArrayList<X509CertificateHolder> certList = new ArrayList<X509CertificateHolder>(); try { if (cert != null) { certList.add(new JcaX509CertificateHolder((X509Certificate) cert)); } if (includeChain) { for (Certificate certificate : chain) { certList.add(new JcaX509CertificateHolder((X509Certificate) certificate)); } } } catch (CertificateEncodingException e) { throw new SignRequestSignatureException("Could not encode certificate", e); } try { CMSTypedData msg = new CMSProcessableByteArray("EJBCA".getBytes()); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); final PrivateKey privateKey = cryptoToken .getPrivateKey(getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)); if (privateKey == null) { String msg1 = "createPKCS7: Private key does not exist!"; log.debug(msg1); throw new SignRequestSignatureException(msg1); } String signatureAlgorithmName = AlgorithmTools .getAlgorithmNameFromDigestAndKey(CMSSignedGenerator.DIGEST_SHA1, privateKey.getAlgorithm()); try { ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithmName) .setProvider(cryptoToken.getSignProviderName()).build(privateKey); JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME); JcaSignerInfoGeneratorBuilder builder = new JcaSignerInfoGeneratorBuilder( calculatorProviderBuilder.build()); gen.addSignerInfoGenerator(builder.build(contentSigner, (X509Certificate) getCACertificate())); } catch (OperatorCreationException e) { throw new IllegalStateException("BouncyCastle failed in creating signature provider.", e); } gen.addCertificates(new CollectionStore(certList)); CMSSignedData s = null; CAToken catoken = getCAToken(); if (catoken != null && !(cryptoToken instanceof NullCryptoToken)) { log.debug("createPKCS7: Provider=" + cryptoToken.getSignProviderName() + " using algorithm " + privateKey.getAlgorithm()); s = gen.generate(msg, true); } else { String msg1 = "CA Token does not exist!"; log.debug(msg); throw new SignRequestSignatureException(msg1); } return s.getEncoded(); } catch (CryptoTokenOfflineException e) { throw new RuntimeException(e); } catch (Exception e) { //FIXME: This right here is just nasty throw new RuntimeException(e); } }
From source file:org.codice.ddf.security.ocsp.checker.OcspChecker.java
License:Open Source License
/** * Creates an {@link OCSPReq} to send to the OCSP server for the given certificate. * * @param cert - the certificate to verify * @return the created OCSP request/*w w w . j av a 2 s . co m*/ * @throws OcspCheckerException after posting an alert to the admin console, if any error occurs */ @VisibleForTesting OCSPReq generateOcspRequest(Certificate cert) throws OcspCheckerException { try { X509CertificateHolder issuerCert = resolveIssuerCertificate(cert); JcaDigestCalculatorProviderBuilder digestCalculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder(); DigestCalculatorProvider digestCalculatorProvider = digestCalculatorProviderBuilder.build(); DigestCalculator digestCalculator = digestCalculatorProvider.get(CertificateID.HASH_SHA1); CertificateID certId = new CertificateID(digestCalculator, issuerCert, cert.getSerialNumber().getValue()); OCSPReqBuilder ocspReqGenerator = new OCSPReqBuilder(); ocspReqGenerator.addRequest(certId); return ocspReqGenerator.build(); } catch (OCSPException | OperatorCreationException e) { throw new OcspCheckerException("Unable to create an OCSP request." + NOT_VERIFIED_MSG, e); } }
From source file:org.cryptable.pki.communication.PKICMPMessages.java
License:Open Source License
/** * This creates a message to confirm a certification message * * @param x509Certificate the certificate to confirm * @return return the binary ASN.1 message to confirm certificate * @throws CertificateEncodingException// w ww . j a v a2s . c o m * @throws IOException * @throws OperatorCreationException * @throws CMPException */ public byte[] createConfirmationMessage(X509Certificate x509Certificate, BigInteger certificateID) throws CertificateEncodingException, IOException, OperatorCreationException, CMPException, PKICMPMessageException { CertificateConfirmationContentBuilder certificateConfirmationContentBuilder = new CertificateConfirmationContentBuilder(); X509CertificateHolder x509CertificateHolder = new X509CertificateHolder(x509Certificate.getEncoded()); certificateConfirmationContentBuilder.addAcceptedCertificate(x509CertificateHolder, certificateID); return createProtectedPKIMessage( new PKIBody(PKIBody.TYPE_CERT_CONFIRM, certificateConfirmationContentBuilder .build(new JcaDigestCalculatorProviderBuilder().build()).toASN1Structure())); }
From source file:org.cryptoworkshop.ximix.client.verify.LinkIndexVerifier.java
License:Apache License
public void verify(int stepNo, boolean isWithPairing, InputStream transcript) throws TranscriptVerificationException { CMSSignedDataParser cmsParser;//from w ww .j a v a 2s . co m SignerId currentSID; Set<Integer> pmIndexes = new HashSet<>(); Set<Integer> cmIndexes = new HashSet<>(); try { cmsParser = new CMSSignedDataParser(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(), transcript); ASN1InputStream aIn = new ASN1InputStream(cmsParser.getSignedContent().getContentStream()); Object obj; while ((obj = aIn.readObject()) != null) { PostedData pM = PostedData.getInstance(obj); MessageCommitment cm = MessageCommitment.getInstance(pM.getData()); pmIndexes.add(pM.getIndex()); cmIndexes.add(cm.getNewIndex()); } currentSID = ((SignerInformation) cmsParser.getSignerInfos().getSigners().iterator().next()).getSID(); } catch (Exception e) { throw new TranscriptVerificationException("Cannot parse CMS wrapper on transcript: " + e.getMessage(), e); } SHA512Digest seedDigest = new SHA512Digest(); byte[] stepSeed = new byte[seedDigest.getDigestSize()]; // we follow the formulation in "Randomized Partial Checking Revisited" where the seed is // modified by the step number, the one difference being that in our case this will only take // place at the start of a pairing, or on an individual step. seedDigest.update(this.challengeSeed, 0, this.challengeSeed.length); seedDigest.update((byte) (stepNo >>> 24)); seedDigest.update((byte) (stepNo >>> 16)); seedDigest.update((byte) (stepNo >>> 8)); seedDigest.update((byte) stepNo); seedDigest.doFinal(stepSeed, 0); IndexNumberGenerator challenger; if (boardSize != 1) { challenger = new SeededChallenger(boardSize, stepNo, stepSeed); } else { challenger = new SerialChallenger(boardSize, stepNo, stepSeed); } Set<Integer> indexes = new HashSet<>(); while (challenger.hasNext()) { indexes.add(challenger.nextIndex()); } if (boardSize != 1 && isWithPairing) { if (!currentSID.equals(lastSID)) { for (int i = 0; i != boardSize; i++) { nextIndexes.add(i); } } else { indexes = new HashSet<>(nextIndexes); } } lastSID = currentSID; if (indexes.size() != pmIndexes.size()) { throw new TranscriptVerificationException( "Entries in witness table do not correspond to seeding - step " + stepNo + " size( " + indexes.size() + ", " + pmIndexes.size() + ")"); } indexes.removeAll(pmIndexes); nextIndexes.removeAll(cmIndexes); if (!indexes.isEmpty()) { throw new TranscriptVerificationException( "Entries in witness table do not correspond to seeding - step " + stepNo + " unaccounted " + indexes.size()); } }
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 www.ja va2s . c o m*/ public void notify(Level level, Throwable throwable) { System.err.print(level + " " + throwable.getMessage()); throwable.printStackTrace(System.err); } @Override public void notify(Level level, Object detail) { System.err.println(level + " " + detail.toString()); } @Override public void notify(Level level, Object detail, Throwable throwable) { System.err.println(level + " " + detail.toString()); throwable.printStackTrace(System.err); } }); PEMParser pParse = new PEMParser(new FileReader(args[1])); X509Certificate trustAnchor = new JcaX509CertificateConverter().setProvider("BC") .getCertificate((X509CertificateHolder) pParse.readObject()); pParse.close(); KeyGenerationService keyGenerationService = adminRegistrar.connect(KeyGenerationService.class); byte[] encPubKey = keyGenerationService.fetchPublicKey("ECENCKEY"); if (encPubKey == null) { KeyGenerationOptions keyGenOptions = new KeyGenerationOptions.Builder(Algorithm.EC_ELGAMAL, "secp256r1") .withThreshold(4).withNodes("A", "B", "C", "D", "E").build(); encPubKey = keyGenerationService.generatePublicKey("ECENCKEY", keyGenOptions); } byte[] sigPubKey = keyGenerationService.fetchPublicKey("ECSIGKEY"); if (sigPubKey == null) { KeyGenerationOptions keyGenOptions = new KeyGenerationOptions.Builder(Algorithm.ECDSA, "secp256r1") .withThreshold(2).withNodes("A", "B", "C", "D", "E").build(); sigPubKey = keyGenerationService.generatePublicKey("ECSIGKEY", keyGenOptions); } byte[] blsPubKey = keyGenerationService.fetchPublicKey("BLSSIGKEY"); if (blsPubKey == null) { KeyGenerationOptions keyGenOptions = new KeyGenerationOptions.Builder(Algorithm.BLS, "d62003-159-158.param").withThreshold(3).withNodes("A", "B", "C", "D", "E").build(); blsPubKey = keyGenerationService.generatePublicKey("BLSSIGKEY", keyGenOptions); } CommandService commandService = adminRegistrar.connect(CommandService.class); if (!commandService.isBoardExisting("FRED")) { commandService.createBoard("FRED", new BoardCreationOptions.Builder("B").withBackUpHost("A").build()); } UploadService client = adminRegistrar.connect(UploadService.class); final ECPublicKeyParameters pubKey = (ECPublicKeyParameters) PublicKeyFactory.createKey(encPubKey); final ECElGamalEncryptor encryptor = new ECElGamalEncryptor(); encryptor.init(pubKey); // set up 100 "random" messages we use a seeded random here to make reload testing easier. SecureRandom pointRandom = new SecureRandom() { int counter = 1; public void nextBytes(byte[] data) { data[0] = (byte) counter++; } }; final int numMessages = 100; final Set<ECPoint> part1 = new HashSet<>(); final Set<ECPoint> part2 = new HashSet<>(); final ECPoint[] plainText1 = new ECPoint[numMessages]; final ECPoint[] plainText2 = new ECPoint[numMessages]; for (int i = 0; i != plainText1.length; i++) { plainText1[i] = generatePoint(pubKey.getParameters(), pointRandom); plainText2[i] = generatePoint(pubKey.getParameters(), pointRandom); part1.add(plainText1[i]); part2.add(plainText2[i]); PairSequence encrypted = new PairSequence( new ECPair[] { encryptor.encrypt(plainText1[i]), encryptor.encrypt(plainText2[i]) }); // two column ballot client.uploadMessage("FRED", encrypted.getEncoded()); } final Set<ECPoint> verifiedPart1 = new HashSet<>(part1); final Set<ECPoint> verifiedPart2 = new HashSet<>(part2); // board is hosted on "B" move to "A" then to "C" then back to "B" final CountDownLatch shuffleLatch = new CountDownLatch(1); final Map<String, byte[]> seedCommitmentMap = new HashMap<>(); ShuffleOperationListener shuffleListener = new ShuffleOperationListener() { @Override public void commit(Map<String, byte[]> seedCommitments) { seedCommitmentMap.putAll(seedCommitments); } @Override public void status(ShuffleStatus statusObject) { System.err.println("status: " + statusObject.getMessage()); } @Override public void completed() { shuffleLatch.countDown(); System.err.println("done"); } @Override public void failed(ShuffleStatus errorObject) { shuffleLatch.countDown(); System.err.println("failed: " + errorObject.getMessage()); } }; Operation<ShuffleOperationListener> shuffleOp = commandService.doShuffleAndMove("FRED", new ShuffleOptions.Builder(MultiColumnRowTransform.NAME).withKeyID("ECENCKEY").build(), shuffleListener, "A", "A", "C", "C", "E"); shuffleLatch.await(); // Commented out as this service not available on VEC // final CountDownLatch downloadLatch = new CountDownLatch(1); // // final ByteArrayOutputStream challengeLogStream = new ByteArrayOutputStream(); // // Operation<DownloadOperationListener> op = commandService.downloadBoardContents("FRED", // new DownloadOptions.Builder() // .withKeyID("ECENCKEY") // .withThreshold(4) // .withNodes("A", "B", "C", "D") // .build(), new DownloadOperationListener() // { // int counter = 0; // // @Override // public void messageDownloaded(int index, byte[] message, List<byte[]> proofs) // { // PointSequence decrypted = PointSequence.getInstance(pubKey.getParameters().getCurve(), message); // // if (part1.remove(decrypted.getECPoints()[0]) && part2.remove(decrypted.getECPoints()[1])) // { // System.err.println(index + " message downloaded successfully"); // } // else // { // System.err.println(index + " decryption failed"); // } // // for (int i = 0; i != proofs.size(); i++) // { // try // { // challengeLogStream.write(proofs.get(i)); // } // catch (IOException e) // { // e.printStackTrace(); // } // } // counter++; // } // // @Override // public void completed() // { // downloadLatch.countDown(); // System.err.println("completed " + (numMessages == counter)); // } // // @Override // public void status(String statusObject) // { // System.err.println("status: " + statusObject); // } // // @Override // public void failed(String errorObject) // { // downloadLatch.countDown(); // System.err.println("failed"); // } // }); // // downloadLatch.await(); // // // // // verify the decryption challenge log. // // // ECDecryptionChallengeVerifier challengeVerifier = new ECDecryptionChallengeVerifier(pubKey, new ByteArrayInputStream(challengeLogStream.toByteArray())); // // challengeVerifier.verify(); Map<String, byte[][]> seedAndWitnessesMap = commandService.downloadShuffleSeedsAndWitnesses("FRED", shuffleOp.getOperationNumber(), "A", "C", "E"); SignedDataVerifier signatureVerifier = new SignedDataVerifier(trustAnchor); final CountDownLatch transcriptCompleted = new CountDownLatch(1); final Map<Integer, byte[]> generalTranscripts = new TreeMap<>(); ShuffleTranscriptsDownloadOperationListener transcriptListener = new ShuffleTranscriptsDownloadOperationListener() { @Override public void shuffleTranscriptArrived(long operationNumber, int stepNumber, InputStream transcript) { try { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); BufferedInputStream bIn = new BufferedInputStream(transcript); int ch; while ((ch = bIn.read()) >= 0) { bOut.write(ch); } bOut.close(); generalTranscripts.put(stepNumber, bOut.toByteArray()); } catch (IOException e) { e.printStackTrace(); } } @Override public void completed() { transcriptCompleted.countDown(); } @Override public void status(String statusObject) { //To change body of implemented methods use File | Settings | File Templates. } @Override public void failed(String errorObject) { System.err.println("failed: " + errorObject); transcriptCompleted.countDown(); } }; commandService.downloadShuffleTranscripts("FRED", shuffleOp.getOperationNumber(), new ShuffleTranscriptOptions.Builder(TranscriptType.GENERAL).build(), transcriptListener, "A", "C", "E"); transcriptCompleted.await(); LinkIndexVerifier.Builder builder = new LinkIndexVerifier.Builder(numMessages); builder.setNetworkSeeds(seedCommitmentMap, seedAndWitnessesMap); for (Integer step : generalTranscripts.keySet()) { byte[] bytes = generalTranscripts.get(step); if (signatureVerifier.signatureVerified(new CMSSignedDataParser( new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(), bytes))) { builder.addTranscript(new ByteArrayInputStream(bytes)); } else { System.err.println("General commitment check signature failed"); } } LinkIndexVerifier linkVerifier = builder.build(); byte[] challengeSeed = linkVerifier.getChallengeSeed(); System.err.println("network seed: " + new String(Hex.encode(challengeSeed))); for (Integer step : generalTranscripts.keySet()) { byte[] bytes = generalTranscripts.get(step); if (!signatureVerifier.signatureVerified(new CMSSignedDataParser( new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(), bytes))) { System.err.println("General commitment check signature failed"); } } // // added the distributed seed // final Map<Integer, byte[]> witnessTranscripts = new TreeMap<>(); final CountDownLatch witnessTranscriptCompleted = new CountDownLatch(1); transcriptListener = new ShuffleTranscriptsDownloadOperationListener() { @Override public void shuffleTranscriptArrived(long operationNumber, int stepNumber, InputStream transcript) { try { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); BufferedInputStream bIn = new BufferedInputStream(transcript); int ch; while ((ch = bIn.read()) >= 0) { bOut.write(ch); } bOut.close(); witnessTranscripts.put(stepNumber, bOut.toByteArray()); } catch (IOException e) { e.printStackTrace(); } } @Override public void completed() { witnessTranscriptCompleted.countDown(); } @Override public void status(String statusObject) { //To change body of implemented methods use File | Settings | File Templates. } @Override public void failed(String errorObject) { witnessTranscriptCompleted.countDown(); } }; commandService .downloadShuffleTranscripts("FRED", shuffleOp.getOperationNumber(), new ShuffleTranscriptOptions.Builder(TranscriptType.WITNESSES) .withChallengeSeed(challengeSeed).withPairingEnabled(true).build(), transcriptListener, "A", "C", "E"); witnessTranscriptCompleted.await(); for (Integer step : witnessTranscripts.keySet()) { byte[] bytes = witnessTranscripts.get(step); if (!signatureVerifier.signatureVerified(new CMSSignedDataParser( new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(), bytes))) { System.err.println("Witness commitment check signature failed"); } } // // verify the witness transcripts are correctly generated // for (Integer step : witnessTranscripts.keySet()) { byte[] bytes = witnessTranscripts.get(step); linkVerifier.verify(step, true, new ByteArrayInputStream(bytes)); } // // verify the revealed commitments. // for (Integer key : witnessTranscripts.keySet()) { byte[] transcript = witnessTranscripts.get(key); byte[] initialTranscript = generalTranscripts.get(key); byte[] nextTranscript = generalTranscripts.get(key + 1); ECShuffledTranscriptVerifier verifier = new ECShuffledTranscriptVerifier(pubKey, new ByteArrayInputStream(transcript), new ByteArrayInputStream(initialTranscript), new ByteArrayInputStream(nextTranscript)); verifier.verify(); } System.err.println("transcripts verified"); Map<String, InputStream> streamSeedCommitments = new HashMap<>(); for (String key : seedCommitmentMap.keySet()) { streamSeedCommitments.put(key, new ByteArrayInputStream(seedCommitmentMap.get(key))); } Map<String, InputStream> streamSeedsAndWitnesses = new HashMap<>(); for (String key : seedAndWitnessesMap.keySet()) { byte[][] sAndW = seedAndWitnessesMap.get(key); streamSeedsAndWitnesses.put(key, new ByteArrayInputStream(new SeedAndWitnessMessage(sAndW[0], sAndW[1]).getEncoded())); } Map<Integer, InputStream> streamWitnessTranscripts = new HashMap<>(); for (Integer key : witnessTranscripts.keySet()) { streamWitnessTranscripts.put(key, new ByteArrayInputStream(witnessTranscripts.get(key))); } Map<Integer, InputStream> streamGeneralTranscripts = new HashMap<>(); for (Integer key : generalTranscripts.keySet()) { streamGeneralTranscripts.put(key, new ByteArrayInputStream(generalTranscripts.get(key))); } final CountDownLatch shuffleOutputDownloadCompleted = new CountDownLatch(1); commandService.downloadShuffleResult("FRED", new DownloadShuffleResultOptions.Builder().withKeyID("ECENCKEY").withThreshold(4) .withPairingEnabled(true).withNodes("A", "B", "C", "D", "E").build(), streamSeedCommitments, streamSeedsAndWitnesses, streamGeneralTranscripts, streamWitnessTranscripts, new DownloadOperationListener() { int counter = 0; @Override public void messageDownloaded(int index, byte[] message, List<byte[]> proofs) { PointSequence decrypted = PointSequence.getInstance(pubKey.getParameters().getCurve(), message); if (verifiedPart1.remove(decrypted.getECPoints()[0]) && verifiedPart2.remove(decrypted.getECPoints()[1])) { System.err.println(index + " message downloaded successfully"); } else { System.err.println(index + " decryption failed"); } counter++; } @Override public void completed() { shuffleOutputDownloadCompleted.countDown(); System.err.println("completed " + (numMessages == counter)); } @Override public void status(String statusObject) { System.err.println("status: " + statusObject); } @Override public void failed(String errorObject) { shuffleOutputDownloadCompleted.countDown(); System.err.println("failed " + errorObject); } }); shuffleOutputDownloadCompleted.await(); keyGenerationService.shutdown(); client.shutdown(); commandService.shutdown(); adminRegistrar.shutdown(); }
From source file:org.cryptoworkshop.ximix.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 ww .j a v a 2 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;/* w w w .j ava2s . co 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.dihedron.crypto.operations.sign.pkcs7.PKCS7Signer.java
License:Open Source License
/** * Constructor./*from w ww .jav a 2 s . c om*/ * * @param alias * the alias of the certificate to be used for signing. * @param keyring * the key ring containing the private key used for signing. * @param provider * the security provider backing up the key ring functionalities. * @param algorithm * the digest and encryption algorithm combination used to create the * signature. * @throws CryptoException * if any among alias, key ring and provider is null. * @throws KeyStoreException * @throws CertificateEncodingException * @throws CertificateNotYetValidException * @throws CertificateExpiredException */ public PKCS7Signer(String alias, KeyRing keyring, Provider provider, SignatureAlgorithm algorithm) throws CryptoException, KeyStoreException, CertificateEncodingException, CertificateNotYetValidException, CertificateExpiredException { super(alias, keyring, provider); logger.debug("creating PKCS#7 signer with '{}' signature algorithm", algorithm); try { logger.info("signing with alias '{}'", alias); // retrieve key and certificate Key key = keyring.getPrivateKey(alias); X509Certificate x509certificate = (X509Certificate) keyring.getCertificate(alias); // this may throw a CertificateExpiredException or CertificateNotYetValidException x509certificate.checkValidity(); logger.info("certificate is valid at current date"); // TODO: check CRL logger.info("certificate is active at current date (CRL check successful)"); // prepare the certificates store List<Certificate> certificates = new ArrayList<>(); certificates.add(x509certificate); Store store = new JcaCertStore(certificates); logger.info("certificate store is ready"); ContentSigner signer = new JcaContentSignerBuilder(algorithm.toBouncyCastleCode()) .setProvider((provider instanceof AutoCloseableProvider) ? ((AutoCloseableProvider) provider).getWrappedProvider() : provider) .build((PrivateKey) key); DigestCalculatorProvider digest = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(); SignerInfoGenerator signerinfo = new SignerInfoGeneratorBuilder(digest).setDirectSignature(false) // include signed attributes; if true it signs data only .setSignedAttributeGenerator( new PKCS7AttributeTableGenerator(algorithm.getDigestAlgorithm(), x509certificate)) // this generates the attributes that will be signed along with the data .build(signer, new JcaX509CertificateHolder(x509certificate)); // and then we build the generator logger.info("signer info generator is ready"); generator = new CMSSignedDataStreamGenerator(); generator.addSignerInfoGenerator(signerinfo); generator.addCertificates(store); //generator.addCRLs(crlStore); logger.debug("signed data stream generator for PKCS#7 is ready"); } catch (OperatorCreationException e) { logger.error("error creating operator", e); throw new CryptoException("error creating signing operator (BouncyCastle)", e); } catch (CertificateEncodingException e) { logger.error("invalid certificate encoding", e); throw e; } catch (CertificateExpiredException e) { logger.error("expired certificate", e); throw e; } catch (CertificateNotYetValidException e) { logger.error("certificate is not yet valid (may still need to be activated?)", e); throw e; } catch (CMSException e) { logger.error("error adding certificates to signature generator", e); throw new CryptoException("CMS error", e); } }
From source file:org.dihedron.crypto.operations.sign.pkcs7.PKCS7SigningStream.java
License:Open Source License
/** * Constructor.//ww w .ja va 2 s. co m * * @param output * the output stream to which data will be eventually written. * @param configurator * the output signing stream configurator. * @throws CryptoException * if any of the input parameters is null. * @throws CertificateNotYetValidException * @throws CertificateExpiredException * @throws GeneralSecurityException */ public PKCS7SigningStream(OutputStream output, SigningStreamConfigurator configurator) throws CryptoException, CertificateExpiredException, CertificateNotYetValidException, CertificateEncodingException, GeneralSecurityException { super(output, configurator); logger.info( "creating PKCS#7 signing filter output stream with '{}' signature algorithm, using certificate alias '{}'", configurator.getAlgorithm(), configurator.getAlias()); try { logger.info("signing with alias '{}'", configurator.getAlias()); // retrieve key, certificate and provider (for simplicity) Key key = configurator.getPrivateKey(); X509Certificate x509certificate = configurator.getCertificate(); Provider provider = configurator.getProvider(); SignatureAlgorithm algorithm = configurator.getAlgorithm(); // prepare the certificates store List<Certificate> certificates = new ArrayList<>(); certificates.add(x509certificate); Store store = new JcaCertStore(certificates); logger.info("certificate store is ready"); ContentSigner signer = new JcaContentSignerBuilder(algorithm.toBouncyCastleCode()) .setProvider((provider instanceof AutoCloseableProvider) ? ((AutoCloseableProvider) provider).getWrappedProvider() : provider) .build((PrivateKey) key); DigestCalculatorProvider digest = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(); SignerInfoGenerator signerinfo = new SignerInfoGeneratorBuilder(digest).setDirectSignature(false) // include signed attributes; if true it signs data only .setSignedAttributeGenerator( new PKCS7AttributeTableGenerator(algorithm.getDigestAlgorithm(), x509certificate)) // this generates the attributes that will be signed along with the data .build(signer, new JcaX509CertificateHolder(x509certificate)); // and then we build the generator logger.info("signer info generator is ready"); generator = new CMSSignedDataStreamGenerator(); generator.addSignerInfoGenerator(signerinfo); generator.addCertificates(store); //generator.addCRLs(crlStore); logger.debug("signed data stream generator for PKCS#7 is ready"); stream = generator.open(output, configurator.isEncapsulateData()); } catch (OperatorCreationException e) { logger.error("error creating operator", e); throw new CryptoException("error creating signing operator (BouncyCastle)", e); } catch (CertificateEncodingException e) { logger.error("invalid certificate encoding", e); throw e; } catch (CMSException e) { logger.error("error adding certificates to signature generator", e); throw new CryptoException("CMS error", e); } catch (IOException e) { logger.error("error establishing signature generator wrapper around output stream", e); throw new CryptoException("Error establishing signature generator wrapper around output stream", e); } }
From source file:org.dihedron.crypto.operations.verify.pkcs7.PKCS7Verifier.java
License:Open Source License
/** * @see org.dihedron.crypto.operations.verify.Verifier#verify(java.io.InputStream) *//*from ww w . j av a2 s. c om*/ @Override public boolean verify(InputStream signed) throws CryptoException { boolean result = true; try { CMSSignedDataParser parser = new CMSSignedDataParser( new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(), signed); parser.getSignedContent().drain(); Store store = parser.getCertificates(); for (Object signer : parser.getSignerInfos().getSigners()) { for (Object object : store.getMatches(((SignerInformation) signer).getSID())) { X509CertificateHolder holder = (X509CertificateHolder) object; logger.trace("verifying signer '{}'", holder.getSubject()); result = result && ((SignerInformation) signer) .verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(holder)); logger.trace("verify returns: {}", result); } } logger.trace("data {} verified", result ? "was" : "was not"); return result; } catch (OperatorCreationException | CMSException | IOException | CertificateException e) { throw new CryptoException("error verifying the signature in streaming mode", e); } }