Example usage for org.bouncycastle.cms SignerInformation getSID

List of usage examples for org.bouncycastle.cms SignerInformation getSID

Introduction

In this page you can find the example usage for org.bouncycastle.cms SignerInformation getSID.

Prototype

public SignerId getSID() 

Source Link

Usage

From source file:org.apache.james.mailet.crypto.KeyStoreHolder.java

License:Apache License

/**
 * Verifies the signature of a SMIME message.
 * /* ww w.j a v a  2s. co m*/
 * 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, MessagingException {
    CertStore certs = signed.getCertificatesAndCRLs("Collection", "BC");
    SignerInformationStore siginfo = signed.getSignerInfos();
    Collection<SignerInformation> sigCol = siginfo.getSigners();
    Iterator<SignerInformation> sigIterator = sigCol.iterator();
    List<SMIMESignerInfo> result = new ArrayList<SMIMESignerInfo>(sigCol.size());
    // I iterate over the signer collection 
    // checking if the signatures put
    // on the message are valid.
    for (int i = 0; sigIterator.hasNext(); i++) {
        SignerInformation info = sigIterator.next();
        // I get the signer's certificate
        Collection certCollection = certs.getCertificates(info.getSID());
        Iterator<X509Certificate> certIter = certCollection.iterator();
        if (certIter.hasNext()) {
            X509Certificate signerCert = certIter.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(signerCert, "BC")) {
                    result.add(new SMIMESignerInfo(signerCert, path, true));
                }
            } catch (Exception e) {
                result.add(new SMIMESignerInfo(signerCert, path, false));
            }
        }
    }
    return result;
}

From source file:org.apache.james.security.KeyStoreHolder.java

License:Apache License

/**
 * Verifies the signature of a SMIME message.
 * /*from w  ww.  jav  a  2  s  .  c  om*/
 * 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 verifySignatures(SMIMESigned signed) throws Exception, MessagingException {
    CertStore certs = signed.getCertificatesAndCRLs("Collection", "BC");
    SignerInformationStore siginfo = signed.getSignerInfos();
    Collection sigCol = siginfo.getSigners();
    Iterator sigIterator = sigCol.iterator();
    List result = new ArrayList(sigCol.size());
    // I iterate over the signer collection 
    // checking if the signatures put
    // on the message are valid.
    for (int i = 0; sigIterator.hasNext(); i++) {
        SignerInformation info = (SignerInformation) sigIterator.next();
        // I get the signer's certificate
        Collection certCollection = certs.getCertificates(info.getSID());
        Iterator certIter = certCollection.iterator();
        if (certIter.hasNext()) {
            X509Certificate signerCert = (X509Certificate) certIter.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(signerCert, "BC")) {
                    result.add(new SMIMESignerInfo(signerCert, path, true));
                }
            } catch (Exception e) {
                result.add(new SMIMESignerInfo(signerCert, path, false));
            }
        }
    }
    return result;
}

From source file:org.apache.james.transport.KeyStoreHolder.java

License:Apache License

/**
 * Verifies the signature of a SMIME message.
 * //  w  ww  .ja  va 2  s .c  o  m
 * 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<SMIMESignerInfo>(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;
}

From source file:org.apache.jmeter.assertions.SMIMEAssertion.java

License:Apache License

private static AssertionResult verifySignature(SMIMEAssertionTestElement testElement, SMIMESignedParser s,
        String name) throws CMSException {
    AssertionResult res = new AssertionResult(name);

    try {/*from  w w  w.j  a  v  a2  s . c  o m*/
        Store certs = s.getCertificates();
        SignerInformationStore signers = s.getSignerInfos();
        Iterator<?> signerIt = signers.getSigners().iterator();

        if (signerIt.hasNext()) {

            SignerInformation signer = (SignerInformation) signerIt.next();
            Iterator<?> certIt = certs.getMatches(signer.getSID()).iterator();

            if (certIt.hasNext()) {
                // the signer certificate
                X509CertificateHolder cert = (X509CertificateHolder) certIt.next();

                if (testElement.isVerifySignature()) {

                    SignerInformationVerifier verifier = null;
                    try {
                        verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert);
                    } catch (OperatorCreationException e) {
                        log.error("Can't create a provider", e);
                    }
                    if (verifier == null || !signer.verify(verifier)) {
                        res.setFailure(true);
                        res.setFailureMessage("Signature is invalid");
                    }
                }

                if (testElement.isSignerCheckConstraints()) {
                    StringBuilder failureMessage = new StringBuilder();

                    String serial = testElement.getSignerSerial();
                    if (!JOrphanUtils.isBlank(serial)) {
                        BigInteger serialNbr = readSerialNumber(serial);
                        if (!serialNbr.equals(cert.getSerialNumber())) {
                            res.setFailure(true);
                            failureMessage.append("Serial number ").append(serialNbr)
                                    .append(" does not match serial from signer certificate: ")
                                    .append(cert.getSerialNumber()).append("\n");
                        }
                    }

                    String email = testElement.getSignerEmail();
                    if (!JOrphanUtils.isBlank(email)) {
                        List<String> emailFromCert = getEmailFromCert(cert);
                        if (!emailFromCert.contains(email)) {
                            res.setFailure(true);
                            failureMessage.append("Email address \"").append(email)
                                    .append("\" not present in signer certificate\n");
                        }

                    }

                    String subject = testElement.getSignerDn();
                    if (subject.length() > 0) {
                        final X500Name certPrincipal = cert.getSubject();
                        log.debug("DN from cert: " + certPrincipal.toString());
                        X500Name principal = new X500Name(subject);
                        log.debug("DN from assertion: " + principal.toString());
                        if (!principal.equals(certPrincipal)) {
                            res.setFailure(true);
                            failureMessage.append("Distinguished name of signer certificate does not match \"")
                                    .append(subject).append("\"\n");
                        }
                    }

                    String issuer = testElement.getIssuerDn();
                    if (issuer.length() > 0) {
                        final X500Name issuerX500Name = cert.getIssuer();
                        log.debug("IssuerDN from cert: " + issuerX500Name.toString());
                        X500Name principal = new X500Name(issuer);
                        log.debug("IssuerDN from assertion: " + principal);
                        if (!principal.equals(issuerX500Name)) {
                            res.setFailure(true);
                            failureMessage
                                    .append("Issuer distinguished name of signer certificate does not match \"")
                                    .append(subject).append("\"\n");
                        }
                    }

                    if (failureMessage.length() > 0) {
                        res.setFailureMessage(failureMessage.toString());
                    }
                }

                if (testElement.isSignerCheckByFile()) {
                    CertificateFactory cf = CertificateFactory.getInstance("X.509");
                    X509CertificateHolder certFromFile;
                    InputStream inStream = null;
                    try {
                        inStream = new BufferedInputStream(
                                new FileInputStream(testElement.getSignerCertFile()));
                        certFromFile = new JcaX509CertificateHolder(
                                (X509Certificate) cf.generateCertificate(inStream));
                    } finally {
                        IOUtils.closeQuietly(inStream);
                    }

                    if (!certFromFile.equals(cert)) {
                        res.setFailure(true);
                        res.setFailureMessage("Signer certificate does not match certificate "
                                + testElement.getSignerCertFile());
                    }
                }

            } else {
                res.setFailure(true);
                res.setFailureMessage("No signer certificate found in signature");
            }

        }

        // TODO support multiple signers
        if (signerIt.hasNext()) {
            log.warn("SMIME message contains multiple signers! Checking multiple signers is not supported.");
        }

    } catch (GeneralSecurityException e) {
        log.error(e.getMessage(), e);
        res.setError(true);
        res.setFailureMessage(e.getMessage());
    } catch (FileNotFoundException e) {
        res.setFailure(true);
        res.setFailureMessage("certificate file not found: " + e.getMessage());
    }

    return res;
}

From source file:org.apache.kerby.pkix.SignedDataEngine.java

License:Apache License

/**
 * Validates a CMS SignedData using the public key corresponding to the private
 * key used to sign the structure.//  w w w  .j av  a2 s  . c o m
 *
 * @param s
 * @return true if the signature is valid.
 * @throws Exception
 */
public static boolean validateSignedData(CMSSignedData s) throws Exception {

    Store certStore = s.getCertificates();
    Store crlStore = s.getCRLs();
    SignerInformationStore signers = s.getSignerInfos();

    Collection c = signers.getSigners();
    Iterator it = c.iterator();

    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        Collection certCollection = certStore.getMatches(signer.getSID());

        Iterator certIt = certCollection.iterator();
        X509CertificateHolder cert = (X509CertificateHolder) certIt.next();

        if (!signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert))) {
            return false;
        }
    }

    Collection certColl = certStore.getMatches(null);
    Collection crlColl = crlStore.getMatches(null);

    if (certColl.size() != s.getCertificates().getMatches(null).size()
            || crlColl.size() != s.getCRLs().getMatches(null).size()) {
        return false;
    }
    return true;
}

From source file:org.apache.pdfbox.examples.pdmodel.TestCreateSignature.java

License:Apache License

private void checkSignature(File file)
        throws IOException, CMSException, OperatorCreationException, GeneralSecurityException {
    PDDocument document = PDDocument.load(file);
    List<PDSignature> signatureDictionaries = document.getSignatureDictionaries();
    if (signatureDictionaries.isEmpty()) {
        Assert.fail("no signature found");
    }/* w w  w. ja v  a  2s  .c  o  m*/
    for (PDSignature sig : document.getSignatureDictionaries()) {
        COSString contents = (COSString) sig.getCOSObject().getDictionaryObject(COSName.CONTENTS);

        FileInputStream fis = new FileInputStream(file);
        byte[] buf = sig.getSignedContent(fis);
        fis.close();

        // inspiration:
        // http://stackoverflow.com/a/26702631/535646
        // http://stackoverflow.com/a/9261365/535646
        CMSSignedData signedData = new CMSSignedData(new CMSProcessableByteArray(buf), contents.getBytes());
        Store certificatesStore = signedData.getCertificates();
        Collection<SignerInformation> signers = signedData.getSignerInfos().getSigners();
        SignerInformation signerInformation = signers.iterator().next();
        Collection matches = certificatesStore.getMatches(signerInformation.getSID());
        X509CertificateHolder certificateHolder = (X509CertificateHolder) matches.iterator().next();
        X509Certificate certFromSignedData = new JcaX509CertificateConverter()
                .getCertificate(certificateHolder);

        Assert.assertEquals(certificate, certFromSignedData);

        // CMSVerifierCertificateNotValidException means that the keystore wasn't valid at signing time
        if (!signerInformation.verify(new JcaSimpleSignerInfoVerifierBuilder().build(certFromSignedData))) {
            Assert.fail("Signature verification failed");
        }
        break;
    }
    document.close();
}

From source file:org.apache.pdfbox.examples.signature.ShowSignature.java

License:Apache License

/**
 * Verify a PKCS7 signature.//from  ww w .  j  a  v  a2  s. c  o m
 *
 * @param byteArray the byte sequence that has been signed
 * @param contents the /Contents field as a COSString
 * @param sig the PDF signature (the /V dictionary)
 * @throws CertificateException
 * @throws CMSException
 * @throws StoreException
 * @throws OperatorCreationException
 */
private void verifyPKCS7(byte[] byteArray, COSString contents, PDSignature sig)
        throws CMSException, CertificateException, StoreException, OperatorCreationException {
    // inspiration:
    // http://stackoverflow.com/a/26702631/535646
    // http://stackoverflow.com/a/9261365/535646
    CMSProcessable signedContent = new CMSProcessableByteArray(byteArray);
    CMSSignedData signedData = new CMSSignedData(signedContent, contents.getBytes());
    Store certificatesStore = signedData.getCertificates();
    Collection<SignerInformation> signers = signedData.getSignerInfos().getSigners();
    SignerInformation signerInformation = signers.iterator().next();
    Collection matches = certificatesStore.getMatches(signerInformation.getSID());
    X509CertificateHolder certificateHolder = (X509CertificateHolder) matches.iterator().next();
    X509Certificate certFromSignedData = new JcaX509CertificateConverter().getCertificate(certificateHolder);
    System.out.println("certFromSignedData: " + certFromSignedData);
    certFromSignedData.checkValidity(sig.getSignDate().getTime());

    if (signerInformation.verify(new JcaSimpleSignerInfoVerifierBuilder().build(certFromSignedData))) {
        System.out.println("Signature verified");
    } else {
        System.out.println("Signature verification failed");
    }
}

From source file:org.bitrepository.protocol.security.BasicMessageAuthenticator.java

License:Open Source License

@Override
public SignerId authenticateMessage(byte[] messageData, byte[] signatureData)
        throws MessageAuthenticationException {
    try {//from w ww .j  a  va2s.com
        CMSSignedData s = new CMSSignedData(new CMSProcessableByteArray(messageData), signatureData);
        SignerInformation signer = (SignerInformation) s.getSignerInfos().getSigners().iterator().next();
        X509Certificate signingCert = permissionStore.getCertificate(signer.getSID());
        SignerInformationVerifier verifier = new JcaSimpleSignerInfoVerifierBuilder()
                .setProvider(SecurityModuleConstants.BC).build(signingCert);

        if (!signer.verify(verifier)) {
            throw new MessageAuthenticationException("Signature does not match the message. Indicated "
                    + "certificate did not sign message. Certificate issuer: "
                    + signingCert.getIssuerX500Principal().getName() + ", serial: "
                    + signingCert.getSerialNumber());
        }
        return signer.getSID();
    } catch (PermissionStoreException e) {
        throw new MessageAuthenticationException(e.getMessage(), e);
    } catch (CMSException e) {
        throw new SecurityException(e.getMessage(), e);
    } catch (OperatorCreationException e) {
        throw new SecurityException(e.getMessage(), e);
    }
}

From source file:org.bitrepository.protocol.security.BasicSecurityManager.java

License:Open Source License

/** 
 * Method to authorize the use of a certificate
 * @param certificateUser the user who signed the message
 * @param messageData the data of the message request.
 * @param signature the signature belonging to the message request.
 * @throws CertificateUseException in case the certificate use could not be authorized. 
 *//* w  w  w .j ava  2 s. com*/
public void authorizeCertificateUse(String certificateUser, String messageData, String signature)
        throws CertificateUseException {
    if (repositorySettings.getProtocolSettings().isRequireOperationAuthorization()) {
        byte[] decodeSig = Base64.decode(signature.getBytes());
        CMSSignedData s;
        try {
            s = new CMSSignedData(new CMSProcessableByteArray(messageData.getBytes()), decodeSig);
        } catch (CMSException e) {
            throw new SecurityException(e.getMessage(), e);
        }

        SignerInformation signer = (SignerInformation) s.getSignerInfos().getSigners().iterator().next();
        authorizer.authorizeCertificateUse(certificateUser, signer.getSID());
    }
}

From source file:org.bitrepository.protocol.security.BasicSecurityManager.java

License:Open Source License

/**
 * Method to authorize an operation /*from ww w .j a  v a2  s .  c  o  m*/
 * @param operationType the type of operation that is to be authorized.
 * @param messageData the data of the message request.
 * @param signature the signature belonging to the message request.
 * @throws OperationAuthorizationException in case of failure. 
 */
public void authorizeOperation(String operationType, String messageData, String signature)
        throws OperationAuthorizationException {
    if (repositorySettings.getProtocolSettings().isRequireOperationAuthorization()) {
        byte[] decodeSig = Base64.decode(signature.getBytes());
        CMSSignedData s;
        try {
            s = new CMSSignedData(new CMSProcessableByteArray(messageData.getBytes()), decodeSig);
        } catch (CMSException e) {
            throw new SecurityException(e.getMessage(), e);
        }

        SignerInformation signer = (SignerInformation) s.getSignerInfos().getSigners().iterator().next();
        try {
            authorizer.authorizeOperation(operationType, signer.getSID());
        } catch (UnregisteredPermissionException e) {
            log.info(e.getMessage());
        }

    }
}