Java Code Examples for org.bouncycastle.cms.SignerInformation#verify()

The following examples show how to use org.bouncycastle.cms.SignerInformation#verify() . 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: CmsSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public SignatureVerificationResult verify(byte[] signedByteArray, Map<String, Object> options) throws TechnicalConnectorException {
   SignatureVerificationResult result = new SignatureVerificationResult();

   try {
      CMSSignedData signedData = new CMSSignedData(signedByteArray);
      this.extractChain(result, signedData);
      this.validateChain(result, options);
      Iterator signerInfos = signedData.getSignerInfos().iterator();

      while(signerInfos.hasNext()) {
         SignerInformation signer = (SignerInformation)signerInfos.next();
         if (!signer.verify(verifierBuilder.build(result.getSigningCert().getPublicKey()))) {
            result.getErrors().add(SignatureVerificationError.SIGNATURE_COULD_NOT_BE_VERIFIED);
         }
      }
   } catch (Exception var7) {
      LOG.error("Unable to verify signature", var7);
      result.getErrors().add(SignatureVerificationError.SIGNATURE_COULD_NOT_BE_VERIFIED);
   }

   return result;
}
 
Example 2
Source File: CmsSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public SignatureVerificationResult verify(byte[] signedByteArray, Map<String, Object> options) throws TechnicalConnectorException {
   SignatureVerificationResult result = new SignatureVerificationResult();

   try {
      CMSSignedData signedData = new CMSSignedData(signedByteArray);
      this.extractChain(result, signedData);
      this.validateChain(result, options);
      Iterator signerInfos = signedData.getSignerInfos().iterator();

      while(signerInfos.hasNext()) {
         SignerInformation signer = (SignerInformation)signerInfos.next();
         if (!signer.verify(verifierBuilder.build(result.getSigningCert().getPublicKey()))) {
            result.getErrors().add(SignatureVerificationError.SIGNATURE_COULD_NOT_BE_VERIFIED);
         }
      }
   } catch (Exception var7) {
      LOG.error("Unable to verify signature", var7);
      result.getErrors().add(SignatureVerificationError.SIGNATURE_COULD_NOT_BE_VERIFIED);
   }

   return result;
}
 
Example 3
Source File: CmsSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public SignatureVerificationResult verify(byte[] signedByteArray, Map<String, Object> options) throws TechnicalConnectorException {
   SignatureVerificationResult result = new SignatureVerificationResult();

   try {
      CMSSignedData signedData = new CMSSignedData(signedByteArray);
      this.extractChain(result, signedData);
      this.validateChain(result, options);
      Iterator signerInfos = signedData.getSignerInfos().iterator();

      while(signerInfos.hasNext()) {
         SignerInformation signer = (SignerInformation)signerInfos.next();
         if (!signer.verify(verifierBuilder.build(result.getSigningCert().getPublicKey()))) {
            result.getErrors().add(SignatureVerificationError.SIGNATURE_COULD_NOT_BE_VERIFIED);
         }
      }
   } catch (Exception var7) {
      LOG.error("Unable to verify signature", var7);
      result.getErrors().add(SignatureVerificationError.SIGNATURE_COULD_NOT_BE_VERIFIED);
   }

   return result;
}
 
Example 4
Source File: CmsSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public SignatureVerificationResult verify(byte[] signedByteArray, Map<String, Object> options) throws TechnicalConnectorException {
   SignatureVerificationResult result = new SignatureVerificationResult();

   try {
      CMSSignedData signedData = new CMSSignedData(signedByteArray);
      this.extractChain(result, signedData);
      this.validateChain(result, options);
      Iterator signerInfos = signedData.getSignerInfos().iterator();

      while(signerInfos.hasNext()) {
         SignerInformation signer = (SignerInformation)signerInfos.next();
         if (!signer.verify(verifierBuilder.build(result.getSigningCert().getPublicKey()))) {
            result.getErrors().add(SignatureVerificationError.SIGNATURE_COULD_NOT_BE_VERIFIED);
         }
      }
   } catch (Exception var7) {
      LOG.error("Unable to verify signature", var7);
      result.getErrors().add(SignatureVerificationError.SIGNATURE_COULD_NOT_BE_VERIFIED);
   }

   return result;
}
 
Example 5
Source File: CmsSignatureBuilder.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public SignatureVerificationResult verify(byte[] signedByteArray, Map<String, Object> options) throws TechnicalConnectorException {
   SignatureVerificationResult result = new SignatureVerificationResult();

   try {
      CMSSignedData signedData = new CMSSignedData(signedByteArray);
      this.extractChain(result, signedData);
      this.validateChain(result, options);
      Iterator signerInfos = signedData.getSignerInfos().iterator();

      while(signerInfos.hasNext()) {
         SignerInformation signer = (SignerInformation)signerInfos.next();
         if (!signer.verify(verifierBuilder.build(result.getSigningCert().getPublicKey()))) {
            result.getErrors().add(SignatureVerificationError.SIGNATURE_COULD_NOT_BE_VERIFIED);
         }
      }
   } catch (Exception var7) {
      LOG.error("Unable to verify signature", var7);
      result.getErrors().add(SignatureVerificationError.SIGNATURE_COULD_NOT_BE_VERIFIED);
   }

   return result;
}
 
Example 6
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 7
Source File: TimestampToken.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private boolean isValidCMSSignedData(SignerInformationVerifier signerInformationVerifier) {
	try {
		// Only validate the cryptographic validity
		SignerInformationStore signerInfos = timeStamp.toCMSSignedData().getSignerInfos();
		SignerInformation signerInformation = signerInfos.get(timeStamp.getSID());
		return signerInformation.verify(signerInformationVerifier);
	} catch (CMSException e) {
		if (LOG.isDebugEnabled()) {
			LOG.debug("Unable to validate the related CMSSignedData : ", e);
		} else {
			LOG.warn("Unable to validate the related CMSSignedData : {}", e.getMessage());
		}
		signatureInvalidityReason = e.getClass().getSimpleName() + " : " + e.getMessage();
		return false;
	}
}
 
Example 8
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 9
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 10
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 11
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 12
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 13
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 14
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;
}