List of usage examples for org.bouncycastle.cms CMSSignedDataParser getSignerInfos
public SignerInformationStore getSignerInfos() throws CMSException
From source file:com.wewebu.ow.server.util.jar.OwJarVerifier.java
License:Open Source License
/** * Get Signature Certificates/*from ww w. j a va2 s . co m*/ * @return {@link X509Certificate}[] * @throws IOException * @throws CMSException */ @SuppressWarnings("rawtypes") public X509CertificateHolder[] getSignatureCertificates() throws IOException, CMSException { JarEntry signatureBlockEntry = getSignatureBlockEntry(); if (null != signatureBlockEntry) { InputStream inputStream = null; try { inputStream = jarFile.getInputStream(signatureBlockEntry); CMSSignedDataParser sp = new CMSSignedDataParser(new BcDigestCalculatorProvider(), new BufferedInputStream(inputStream, 1024)); Store certStore = sp.getCertificates(); SignerInformationStore signers = sp.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); List<X509CertificateHolder> certificates = new ArrayList<X509CertificateHolder>(); while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); Collection certCollection = certStore.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder) certIt.next(); certificates.add(cert); } return certificates.toArray(new X509CertificateHolder[certificates.size()]); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException ex) { } } inputStream = null; } } return new X509CertificateHolder[] {}; }
From source file:de.mendelson.util.security.BCCryptoHelper.java
/** * Returns the digest OID algorithm from a signature. The return value * for sha1 is e.g. "1.3.14.3.2.26"./*from w ww. j a va 2s . c om*/ */ public String getDigestAlgOIDFromSignature(InputStream signed, Certificate cert) throws Exception { CMSSignedDataParser parser = new CMSSignedDataParser( new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(), signed); parser.getSignedContent().drain(); SignerInformationStore signers = parser.getSignerInfos(); Collection signerCollection = signers.getSigners(); Iterator it = signerCollection.iterator(); boolean verified = false; X509CertificateHolder certHolder = new X509CertificateHolder(cert.getEncoded()); SignerInformationVerifier verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC") .build(certHolder); while (it.hasNext()) { SignerInformation signerInformation = (SignerInformation) it.next(); if (!verified) { verified = signerInformation.verify(verifier); if (verified) { return (signerInformation.getDigestAlgOID()); } } } throw new GeneralSecurityException("getDigestAlgOIDFromSignature: Unable to identify signature algorithm."); }
From source file:de.mendelson.util.security.BCCryptoHelper.java
/** * Verifies a signature of a passed content against the passed certificate *///w w w . j a va 2s.c o m public boolean verify(byte[] content, byte[] signature, Certificate cert) throws Exception { if (content == null) { throw new GeneralSecurityException("verify: Content is absent"); } if (signature == null) { throw new GeneralSecurityException("verify: Signature is absent"); } if (signature.length == 0) { throw new Exception("verify: Signature length is 0"); } CMSTypedStream signedContent = new CMSTypedStream(new ByteArrayInputStream(content)); CMSSignedDataParser dataParser = new CMSSignedDataParser(new BcDigestCalculatorProvider(), signedContent, new ByteArrayInputStream(signature)); dataParser.getSignedContent().drain(); SignerInformationStore signers = dataParser.getSignerInfos(); Collection signerCollection = signers.getSigners(); Iterator it = signerCollection.iterator(); X509CertificateHolder certHolder = new X509CertificateHolder(cert.getEncoded()); SignerInformationVerifier verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC") .build(certHolder); boolean verified = false; while (it.hasNext()) { SignerInformation signerInformation = (SignerInformation) it.next(); if (!verified) { verified = signerInformation.verify(verifier); } if (verified) { break; } } return (verified); }
From source file:de.mendelson.util.security.BCCryptoHelper.java
public boolean verifySignatureCMS(InputStream signed, Certificate cert) throws Exception { CMSSignedDataParser parser = new CMSSignedDataParser( new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(), signed); parser.getSignedContent().drain();/*ww w . ja v a 2 s.co m*/ SignerInformationStore signers = parser.getSignerInfos(); Collection signerCollection = signers.getSigners(); Iterator it = signerCollection.iterator(); boolean verified = false; X509CertificateHolder certHolder = new X509CertificateHolder(cert.getEncoded()); SignerInformationVerifier verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC") .build(certHolder); while (it.hasNext()) { SignerInformation signerInformation = (SignerInformation) it.next(); if (!verified) { verified = signerInformation.verify(verifier); } if (verified) { break; } } return (verified); }
From source file:eu.europa.ec.markt.dss.validation.cades.CAdESSignature.java
License:Open Source License
@Override public boolean checkIntegrity(Document detachedDocument) { JcaSimpleSignerInfoVerifierBuilder verifier = new JcaSimpleSignerInfoVerifierBuilder(); try {//from w w w .j a v a 2s.co m boolean ret = false; SignerInformation si = null; if (detachedDocument != null) { // Recreate a SignerInformation with the content using a CMSSignedDataParser CMSSignedDataParser sp = new CMSSignedDataParser(new CMSTypedStream(detachedDocument.openStream()), cmsSignedData.getEncoded()); sp.getSignedContent().drain(); si = sp.getSignerInfos().get(signerInformation.getSID()); } else { si = this.signerInformation; } ret = si.verify(verifier.build(getSigningCertificate())); return ret; } catch (OperatorCreationException e) { return false; } catch (CMSException e) { return false; } catch (IOException e) { return false; } }
From source file:eu.europa.ec.markt.dss.validation102853.cades.CAdESSignature.java
License:Open Source License
@Override public SignatureCryptographicVerification checkSignatureIntegrity() { if (signatureCryptographicVerification != null) { return signatureCryptographicVerification; }/* w ww . j ava2 s.c o m*/ signatureCryptographicVerification = new SignatureCryptographicVerification(); try { final List<SigningCertificateValidity> signingCertificateValidityList; if (providedSigningCertificateToken == null) { // To determine the signing certificate it is necessary to browse through all candidates found before. final CandidatesForSigningCertificate candidatesForSigningCertificate = getCandidatesForSigningCertificate(); signingCertificateValidityList = candidatesForSigningCertificate .getSigningCertificateValidityList(); if (signingCertificateValidityList.size() == 0) { signatureCryptographicVerification .setErrorMessage("There is no signing certificate within the signature."); return signatureCryptographicVerification; } } else { candidatesForSigningCertificate = new CandidatesForSigningCertificate(); final SigningCertificateValidity signingCertificateValidity = new SigningCertificateValidity( providedSigningCertificateToken); candidatesForSigningCertificate.add(signingCertificateValidity); signingCertificateValidityList = candidatesForSigningCertificate .getSigningCertificateValidityList(); } boolean detached = cmsSignedData.getSignedContent() == null || cmsSignedData.getSignedContent().getContent() == null ? true : false; final SignerInformation signerInformationToCheck; if (detached) { if (detachedContents == null || detachedContents.size() == 0) { if (signingCertificateValidityList.size() > 0) { candidatesForSigningCertificate .setTheSigningCertificateValidity(signingCertificateValidityList.get(0)); } signatureCryptographicVerification.setErrorMessage("Detached file not found!"); return signatureCryptographicVerification; } // Recreate a SignerInformation with the content using a CMSSignedDataParser final DSSDocument dssDocument = detachedContents.get(0); // only one element for CAdES Signature final InputStream inputStream = dssDocument.openStream(); final CMSTypedStream signedContent = new CMSTypedStream(inputStream); final CMSSignedDataParser sp = new CMSSignedDataParser(new BcDigestCalculatorProvider(), signedContent, cmsSignedData.getEncoded()); sp.getSignedContent().drain(); // Closes the stream final SignerId sid = signerInformation.getSID(); signerInformationToCheck = sp.getSignerInfos().get(sid); } else { // if (detachedContents == null || detachedContents.size() == 0) { signerInformationToCheck = signerInformation; } LOG.debug("CHECK SIGNATURE VALIDITY: "); for (final SigningCertificateValidity signingCertificateValidity : signingCertificateValidityList) { try { // In the case where one of the mandatory attributes is missing we set already the candidate for the signing certificate. // see: validation.at.nqs.bdc.TestNotQualifiedBDC.test1() candidatesForSigningCertificate.setTheSigningCertificateValidity(signingCertificateValidity); final JcaSimpleSignerInfoVerifierBuilder verifier = new JcaSimpleSignerInfoVerifierBuilder(); final CertificateToken certificateToken = signingCertificateValidity.getCertificateToken(); final X509Certificate certificate = certificateToken.getCertificate(); final SignerInformationVerifier signerInformationVerifier = verifier.build(certificate); LOG.debug(" - WITH SIGNING CERTIFICATE: " + certificateToken.getAbbreviation()); boolean signatureIntact = signerInformationToCheck.verify(signerInformationVerifier); signatureCryptographicVerification.setReferenceDataFound(signatureIntact); signatureCryptographicVerification.setReferenceDataIntact(signatureIntact); signatureCryptographicVerification.setSignatureIntact(signatureIntact); if (signatureIntact) { break; } } catch (RuntimeOperatorException e) { // Cest un problme de compatibilit avec Java 7. Limplmentation de la classe sun.security.rsa.RSASignature a chang entre la version 6 et 7. Bouncy castle ne // prend pas correctement en compte ce changement. En effet, une exception est leve par la version 7 que BC ne catch pas correctement ce qui se traduit par // lenvoi dune exception : org.bouncycastle.operator.RuntimeOperatorException (Bob) LOG.warn(e.getMessage(), e); } catch (CMSSignerDigestMismatchException e) { LOG.error(e.getMessage(), e); signatureCryptographicVerification.setReferenceDataFound(true); signatureCryptographicVerification.setReferenceDataIntact(false); signatureCryptographicVerification.setSignatureIntact(false); signatureCryptographicVerification.setErrorMessage(e.getMessage()); } catch (OperatorCreationException e) { LOG.error(e.getMessage(), e); signatureCryptographicVerification.setErrorMessage(e.getMessage()); } catch (CMSException e) { LOG.error(e.getMessage(), e); signatureCryptographicVerification.setErrorMessage(e.getMessage()); } catch (IllegalArgumentException e) { // Can arrive when for example: // java.lang.IllegalArgumentException: Unknown signature type requested: RIPEMD160WITH0.4.0.127.0.7.1.1.4.1.6 // at org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder.generate(Unknown Source) ~[bcpkix-jdk15on-1.49.jar:1.49.0] LOG.error(e.getMessage(), e); signatureCryptographicVerification.setErrorMessage(e.getMessage()); } } } catch (CMSException e) { LOG.error(e.getMessage(), e); signatureCryptographicVerification.setErrorMessage(e.getMessage()); } catch (IOException e) { LOG.error(e.getMessage(), e); signatureCryptographicVerification.setErrorMessage(e.getMessage()); } LOG.debug(" - RESULT: " + signatureCryptographicVerification.isReferenceDataFound() + "/" + signatureCryptographicVerification.isReferenceDataIntact() + "/" + signatureCryptographicVerification.isSignatureIntact()); return signatureCryptographicVerification; }
From source file:eu.europa.esig.dss.cades.validation.CAdESSignature.java
License:Open Source License
/** * This method recreates a {@code SignerInformation} with the content using * a {@code CMSSignedDataParser}./*from www . java 2 s .c o m*/ * * @return * @throws CMSException * @throws IOException */ private SignerInformation recreateSignerInformation() throws CMSException, IOException { final DSSDocument dssDocument = detachedContents.get(0); // only one element for CAdES Signature final InputStream inputStream = dssDocument.openStream(); final CMSTypedStream signedContent = new CMSTypedStream(inputStream); final CMSSignedDataParser cmsSignedDataParser = new CMSSignedDataParser(new BcDigestCalculatorProvider(), signedContent, cmsSignedData.getEncoded()); cmsSignedDataParser.getSignedContent().drain(); // Closes the stream final SignerId signerId = signerInformation.getSID(); final SignerInformation signerInformationToCheck = cmsSignedDataParser.getSignerInfos().get(signerId); return signerInformationToCheck; }
From source file:net.ripe.rpki.commons.crypto.cms.RpkiSignedObjectParser.java
License:BSD License
private SignerInformationStore getSignerStore(CMSSignedDataParser sp) { try {/*w ww . ja v a 2 s.c om*/ return sp.getSignerInfos(); } catch (CMSException e) { return null; // Caller will validate that the SignerInformationStore is not null } catch (RuntimeException e) { return null; // Caller will validate that the SignerInformationStore is not null } }
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; SignerId currentSID;/*from w ww .j av a 2 s .c o m*/ 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.client.verify.SignedDataVerifier.java
License:Apache License
/** * Verify the passed in CMS signed data, return false on failure. * <p>/*from w w w . j ava 2s. c o m*/ * Note: this method assumes the parser has been freshly created and its content not read or drained. * </p> * * @param cmsParser a CMSSignedData object. * @return true if signature checks out, false if there is a problem with the signature or the path to its verifying certificate. */ public boolean signatureVerified(CMSSignedDataParser cmsParser) throws IOException, CMSException { cmsParser.getSignedContent().drain(); Store certs = cmsParser.getCertificates(); SignerInformationStore signers = cmsParser.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); SignerInformation signer = (SignerInformation) it.next(); try { PKIXCertPathBuilderResult result = checkCertPath(signer.getSID(), certs); X509Certificate cert = (X509Certificate) result.getCertPath().getCertificates().get(0); return signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert)); } catch (Exception e) { // TODO: logging? return false; } }