org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder Java Examples

The following examples show how to use org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PdfPKCS7.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Verifies a timestamp against a KeyStore.
 * @param ts the timestamp
 * @param keystore the <CODE>KeyStore</CODE>
 * @param provider the provider or <CODE>null</CODE> to use the BouncyCastle provider
 * @return <CODE>true</CODE> is a certificate was found
 * @since	2.1.6
 */    
public static boolean verifyTimestampCertificates(TimeStampToken ts, KeyStore keystore, String provider) {
    if (provider == null)
        provider = "BC";
    try {
        for (Enumeration aliases = keystore.aliases(); aliases.hasMoreElements();) {
            try {
                String alias = (String)aliases.nextElement();
                if (!keystore.isCertificateEntry(alias))
                    continue;
                X509Certificate certStoreX509 = (X509Certificate)keystore.getCertificate(alias);
                SignerInformationVerifier siv = new JcaSimpleSignerInfoVerifierBuilder().setProvider(provider).build(certStoreX509);
                ts.validate(siv);
                return true;
            }
            catch (Exception ex) {
            }
        }
    }
    catch (Exception e) {
    }
    return false;
}
 
Example #2
Source File: ValidateSignature.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/41116833/pdf-signature-validation">
 * PDF Signature Validation
 * </a>
 * <br/>
 * <a href="https://drive.google.com/file/d/0BzEmZ9pRWLhPOUJSYUdlRjg2eEU/view?usp=sharing">
 * SignatureVlidationTest.pdf
 * </a>
 * <p>
 * The code completely ignores the <b>SubFilter</b> of the signature.
 * It is appropriate for signatures with <b>SubFilter</b> values
 * <b>adbe.pkcs7.detached</b> and <b>ETSI.CAdES.detached</b>
 * but will fail for signatures with <b>SubFilter</b> values
 * <b>adbe.pkcs7.sha1</b> and <b>adbe.x509.rsa.sha1</b>.
 * </p>
 * <p>
 * The example document has been signed with a signatures with
 * <b>SubFilter</b> value <b>adbe.pkcs7.sha1</b>.
 * </p>
 */
@Test
public void testValidateSignatureVlidationTest() throws Exception
{
    System.out.println("\nValidate signature in SignatureVlidationTest.pdf; original code.");
    byte[] pdfByte;
    PDDocument pdfDoc = null;
    SignerInformationVerifier verifier = null;
    try
    {
        pdfByte = IOUtils.toByteArray(this.getClass().getResourceAsStream("SignatureVlidationTest.pdf"));
        pdfDoc = Loader.loadPDF(new ByteArrayInputStream(pdfByte));
        PDSignature signature = pdfDoc.getSignatureDictionaries().get(0);

        byte[] signatureAsBytes = signature.getContents(pdfByte);
        byte[] signedContentAsBytes = signature.getSignedContent(pdfByte);
        CMSSignedData cms = new CMSSignedData(new CMSProcessableByteArray(signedContentAsBytes), signatureAsBytes);
        SignerInformation signerInfo = (SignerInformation) cms.getSignerInfos().getSigners().iterator().next();
        X509CertificateHolder cert = (X509CertificateHolder) cms.getCertificates().getMatches(signerInfo.getSID())
                .iterator().next();
        verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider(new BouncyCastleProvider()).build(cert);

        // result if false
        boolean verifyRt = signerInfo.verify(verifier);
        System.out.println("Verify result: " + verifyRt);
    }
    finally
    {
        if (pdfDoc != null)
        {
            pdfDoc.close();
        }
    }
}
 
Example #3
Source File: BouncyCastleCrypto.java    From tutorials with MIT License 6 votes vote down vote up
public static boolean verifSignData(final byte[] signedData) throws CMSException, IOException, OperatorCreationException, CertificateException {
    ByteArrayInputStream bIn = new ByteArrayInputStream(signedData);
    ASN1InputStream aIn = new ASN1InputStream(bIn);
    CMSSignedData s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject()));
    aIn.close();
    bIn.close();
    Store certs = s.getCertificates();
    SignerInformationStore signers = s.getSignerInfos();
    Collection<SignerInformation> c = signers.getSigners();
    SignerInformation signer = c.iterator().next();
    Collection<X509CertificateHolder> certCollection = certs.getMatches(signer.getSID());
    Iterator<X509CertificateHolder> certIt = certCollection.iterator();
    X509CertificateHolder certHolder = certIt.next();
    boolean verifResult = signer.verify(new JcaSimpleSignerInfoVerifierBuilder().build(certHolder));
    if (!verifResult) {
        return false;
    }
    return true;
}
 
Example #4
Source File: PKCS7Manager.java    From Websocket-Smart-Card-Signer with GNU Affero General Public License v3.0 5 votes vote down vote up
public static boolean verifySignature(CMSSignedData cmsSignedData, X509Certificate cert) {
    try {
        if (Security.getProvider("BC") == null)
            Security.addProvider(new BouncyCastleProvider());

        Collection<SignerInformation> signers = cmsSignedData.getSignerInfos().getSigners();
        X509CertificateHolder ch = new X509CertificateHolder(cert.getEncoded());
        for (SignerInformation si : signers)
            if (si.getSID().match(ch))
                if (si.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(ch)))
                    return true;
    } catch (Exception e) {}
    return false;
}
 
Example #5
Source File: PKCS7Manager.java    From Websocket-Smart-Card-Signer with GNU Affero General Public License v3.0 5 votes vote down vote up
public static boolean verifyAllSignatures(CMSSignedData cmsSignedData) {
    try {
        if (Security.getProvider("BC") == null)
            Security.addProvider(new BouncyCastleProvider());

        Collection<SignerInformation> signers = cmsSignedData.getSignerInfos().getSigners();

        for (SignerInformation si : signers) {
            @SuppressWarnings("unchecked")
            Collection<X509CertificateHolder> certList = cmsSignedData.getCertificates().getMatches(si.getSID());
            if (certList.size() == 0)
                throw new Exception("ERROR: Impossible to find a Certificate using the Signer ID: " + si.getSID());

            X509CertificateHolder cert = certList.iterator().next(); // Take only the first certificate of the chain

            if (!si.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert)))
                throw new Exception("ATTENTION: At least a signature is invalid!");

            boolean certOK = true;
            String msg = "";
            try {
                X509Utils.checkAllOnCertificate(X509Utils.getX509Certificate(cert.getEncoded()));
            } catch (Exception ex) {
                msg = ex.getMessage();
                certOK = false;
            }
            if (!certOK)
                throw new Exception("ATTENTION: The certificate is invalid:\n" + msg);
        }

        return true;
    } catch (Exception e) {
        e.printStackTrace();
    }

    return false;
}
 
Example #6
Source File: ValidateSignature.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/41116833/pdf-signature-validation">
 * PDF Signature Validation
 * </a>
 * <br/>
 * <a href="https://drive.google.com/file/d/0BzEmZ9pRWLhPOUJSYUdlRjg2eEU/view?usp=sharing">
 * SignatureVlidationTest.pdf
 * </a>
 * <p>
 * This code also ignores the <b>SubFilter</b> of the signature,
 * it is appropriate for signatures with <b>SubFilter</b> value
 * <b>adbe.pkcs7.sha1</b> which the example document has been
 * signed with.
 * </p>
 */
@Test
public void testValidateSignatureVlidationTestAdbePkcs7Sha1() throws Exception
{
    System.out.println("\nValidate signature in SignatureVlidationTest.pdf; special adbe.pkcs7.sha1 code.");
    byte[] pdfByte;
    PDDocument pdfDoc = null;
    SignerInformationVerifier verifier = null;
    try
    {
        pdfByte = IOUtils.toByteArray(this.getClass().getResourceAsStream("SignatureVlidationTest.pdf"));
        pdfDoc = Loader.loadPDF(new ByteArrayInputStream(pdfByte));
        PDSignature signature = pdfDoc.getSignatureDictionaries().get(0);

        byte[] signatureAsBytes = signature.getContents(pdfByte);
        CMSSignedData cms = new CMSSignedData(new ByteArrayInputStream(signatureAsBytes));
        SignerInformation signerInfo = (SignerInformation) cms.getSignerInfos().getSigners().iterator().next();
        X509CertificateHolder cert = (X509CertificateHolder) cms.getCertificates().getMatches(signerInfo.getSID())
                .iterator().next();
        verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider(new BouncyCastleProvider()).build(cert);

        boolean verifyRt = signerInfo.verify(verifier);
        System.out.println("Verify result: " + verifyRt);

        byte[] signedContentAsBytes = signature.getSignedContent(pdfByte);
        MessageDigest md = MessageDigest.getInstance("SHA1");
        byte[] calculatedDigest = md.digest(signedContentAsBytes);
        byte[] signedDigest = (byte[]) cms.getSignedContent().getContent();
        System.out.println("Document digest equals: " + Arrays.equals(calculatedDigest, signedDigest));
    }
    finally
    {
        if (pdfDoc != null)
        {
            pdfDoc.close();
        }
    }
}
 
Example #7
Source File: DefaultTimeStampVerificationProvider.java    From xades4j with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Inject
public DefaultTimeStampVerificationProvider(
        CertificateValidationProvider certificateValidationProvider,
        MessageDigestEngineProvider messageDigestProvider)
{
    this.certificateValidationProvider = certificateValidationProvider;
    this.messageDigestProvider = messageDigestProvider;

    Provider bcProv = new BouncyCastleProvider();
    this.signerInfoVerifierBuilder = new JcaSimpleSignerInfoVerifierBuilder().setProvider(bcProv);
    this.x509CertificateConverter = new JcaX509CertificateConverter().setProvider(bcProv);
    this.x509CertSelectorConverter = new JcaX509CertSelectorConverter();
}
 
Example #8
Source File: TimestampToken.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private SignerInformationVerifier getSignerInformationVerifier(final CertificateToken candidate) {
	try {
		final JcaSimpleSignerInfoVerifierBuilder verifier = new JcaSimpleSignerInfoVerifierBuilder();
		verifier.setProvider(DSSSecurityProvider.getSecurityProviderName());
		return verifier.build(candidate.getCertificate());
	} catch (OperatorException e) {
		throw new DSSException("Unable to build an instance of SignerInformationVerifier", e);
	}
}
 
Example #9
Source File: PKCS7Manager.java    From Websocket-Smart-Card-Signer with GNU Affero General Public License v3.0 4 votes vote down vote up
public static boolean verifySignatureOfUser(byte[] PKCS7Content, String userCF) {
    try {
        if (userCF == null || userCF.equals(""))
            throw new Exception("ERROR: userCF can not be null or empty");

        if (Security.getProvider("BC") == null)
            Security.addProvider(new BouncyCastleProvider());

        CMSSignedData cmsSignedData = new CMSSignedData(PKCS7Content);
        boolean findedCert = false;
        int invalidCerts = 0;
        Collection<SignerInformation> signers = cmsSignedData.getSignerInfos().getSigners();
        for (SignerInformation si : signers) {
            @SuppressWarnings("unchecked")
            Collection<X509CertificateHolder> certList = cmsSignedData.getCertificates().getMatches(si.getSID());
            X509CertificateHolder cert = certList.iterator().next();

            if (cert.getSubject().toString().toLowerCase().contains(userCF.toLowerCase())) {
                findedCert = true;
                if (si.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert))) {
                    boolean certOK = true;
                    try {
                        X509Utils.checkAllOnCertificate(X509Utils.getX509Certificate(cert.getEncoded()));
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        certOK = false;
                    }
                    if (certOK)
                        return true;
                    else
                        invalidCerts++;
                } else
                    invalidCerts++;
            }
        }
        if (!findedCert)
            throw new Exception("ATTENTION: No certificate found in the PKCS7 data that contain the CF " + userCF + " in its subjectDN");
        if (invalidCerts != 0)
            throw new Exception("ATTENTION: N. " + invalidCerts + " certificates associated to the user " + userCF + " seems to be invalid. Please check them!");
    } catch (Exception e) {
        e.printStackTrace();
    }

    return false;
}
 
Example #10
Source File: PDFVerify.java    From signer with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void testValidateSignatureVlidationTestAdbePkcs7Sha1() throws Exception
 {
     String filePath = "caminho arquivo";
     
     byte[] pdfByte;
     PDDocument pdfDoc = null;
     SignerInformationVerifier verifier = null;
     try
     {
         //pdfByte = IOUtils.toByteArray(this.getClass().getResourceAsStream("Teste_AI_Assinado_Assinador_Livre.pdf"));
         pdfDoc = PDDocument.load(new File(filePath));
         PDSignature signature = pdfDoc.getSignatureDictionaries().get(0);
         byte[] signedContentAsBytes = signature.getSignedContent(new FileInputStream(filePath));

         byte[] signatureAsBytes = signature.getContents(new FileInputStream(filePath));
         
         PAdESChecker checker = new PAdESChecker();
         checker.checkDetachedSignature(signedContentAsBytes, signatureAsBytes);
                     
         CMSSignedData cms = new CMSSignedData(new ByteArrayInputStream(signatureAsBytes));
                     
         SignerInformation signerInfo = (SignerInformation) cms.getSignerInfos().getSigners().iterator().next();
         @SuppressWarnings("unchecked")
X509CertificateHolder cert = (X509CertificateHolder) cms.getCertificates().getMatches(signerInfo.getSID())
                 .iterator().next();
         verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider(new BouncyCastleProvider()).build(cert);

         boolean verifyRt = signerInfo.verify(verifier);
         System.out.println("Verify result: " + verifyRt);

         
         MessageDigest md = MessageDigest.getInstance("SHA1");
         byte[] calculatedDigest = md.digest(signedContentAsBytes);
         byte[] signedDigest = (byte[]) cms.getSignedContent().getContent();
         System.out.println("Document digest equals: " + Arrays.equals(calculatedDigest, signedDigest));
         
         
     		

     }
     finally
     {
         if (pdfDoc != null)
         {
             pdfDoc.close();
         }
     }
 }
 
Example #11
Source File: KeyStoreHolder.java    From james-project with Apache License 2.0 4 votes vote down vote up
/**
 * Verifies the signature of a SMIME message.
 * 
 * It checks also if the signer's certificate is trusted using the loaded
 * keystore as trusted certificate store.
 * 
 * @param signed
 *            the signed mail to check.
 * @return a list of SMIMESignerInfo which keeps the data of each mail
 *         signer.
 * @throws Exception
 * @throws MessagingException
 */
public List<SMIMESignerInfo> verifySignatures(SMIMESigned signed) throws Exception {

    CertStore certs = new JcaCertStoreBuilder()
        .addCertificates(signed.getCertificates())
        .addCRLs(signed.getCRLs())
        .build();
    SignerInformationStore siginfo = signed.getSignerInfos();
    Collection<SignerInformation> sigCol = siginfo.getSigners();
    List<SMIMESignerInfo> result = new ArrayList<>(sigCol.size());
    // I iterate over the signer collection 
    // checking if the signatures put
    // on the message are valid.
    for (SignerInformation info: sigCol) {
        // I get the signer's certificate
        X509CertificateHolderSelector x509CertificateHolderSelector = new X509CertificateHolderSelector(info.getSID().getSubjectKeyIdentifier());
        X509CertSelector certSelector = new JcaX509CertSelectorConverter().getCertSelector(x509CertificateHolderSelector);
        @SuppressWarnings("unchecked")
        Collection<X509Certificate> certCollection = (Collection<X509Certificate>) certs.getCertificates(certSelector);
        if (!certCollection.isEmpty()) {
            X509Certificate signerCert = certCollection.iterator().next();
            // The issuer's certifcate is searched in the list of trusted certificate.
            CertPath path = verifyCertificate(signerCert, certs, keyStore);

            try {
                // if the signature is valid the SMIMESignedInfo is 
                // created using "true" as last argument. If it is  
                // invalid an exception is thrown by the "verify" method
                // and the SMIMESignerInfo is created with "false".
                //
                // The second argument "path" is not null if the 
                // certificate can be trusted (it can be connected 
                // by a chain of trust to a trusted certificate), null
                // otherwise.
                if (info.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(signerCert))) {
                    result.add(new SMIMESignerInfo(signerCert, path, true));
                }
            } catch (Exception e) { 
                result.add(new SMIMESignerInfo(signerCert,path, false)); 
            }
        }
    }
    return result;
}
 
Example #12
Source File: CounterSignatureValidationTest.java    From dss with GNU Lesser General Public License v2.1 3 votes vote down vote up
@Override
protected DSSDocument getSignedDocument() {
	FileDocument fileDocument = new FileDocument("src/test/resources/validation/counterSig.p7m");
	
	try (InputStream is = fileDocument.openStream()) {
		CMSSignedData cms = new CMSSignedData(is);
		Collection<SignerInformation> signers = cms.getSignerInfos().getSigners();
		assertEquals(1, signers.size());

		Store<X509CertificateHolder> certificates = cms.getCertificates();

		SignerInformation signerInformation = signers.iterator().next();

		Collection<X509CertificateHolder> matches = certificates.getMatches(signerInformation.getSID());
		X509CertificateHolder cert = matches.iterator().next();

		SignerInformationVerifier verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider(new BouncyCastleProvider()).build(cert);

		assertTrue(signerInformation.verify(verifier));

		SignerInformationStore counterSignatures = signerInformation.getCounterSignatures();
		for (SignerInformation counterSigner : counterSignatures) {

			Collection<X509CertificateHolder> matchesCounter = certificates.getMatches(counterSigner.getSID());
			X509CertificateHolder counterCert = matchesCounter.iterator().next();

			SignerInformationVerifier counterVerifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider(new BouncyCastleProvider()).build(counterCert);

			assertTrue(counterSigner.verify(counterVerifier));
		}
	} catch (Exception e) {
		fail(e);
	}
	
	return fileDocument;
	
}