Example usage for java.security.cert CertificateFactory getInstance

List of usage examples for java.security.cert CertificateFactory getInstance

Introduction

In this page you can find the example usage for java.security.cert CertificateFactory getInstance.

Prototype

public static final CertificateFactory getInstance(String type) throws CertificateException 

Source Link

Document

Returns a certificate factory object that implements the specified certificate type.

Usage

From source file:org.apache.cxf.ws.security.sts.provider.operation.IssueDelegate.java

private X509Certificate getCertificateFromRequest(Object requestObject) throws CertificateException {
    UseKeyType useKeyType = extractType(requestObject, UseKeyType.class);
    byte[] x509 = null;
    if (null != useKeyType) {
        KeyInfoType keyInfoType = extractType(useKeyType.getAny(), KeyInfoType.class);
        if (null != keyInfoType) {
            for (Object keyInfoContent : keyInfoType.getContent()) {
                X509DataType x509DataType = extractType(keyInfoContent, X509DataType.class);
                if (null != x509DataType) {
                    for (Object x509Object : x509DataType.getX509IssuerSerialOrX509SKIOrX509SubjectName()) {
                        x509 = extractType(x509Object, byte[].class);
                        if (null != x509) {
                            break;
                        }// w w  w  . jav a  2  s  .  c  om
                    }
                }
            }
        } else {
            Element elementNSImpl = (Element) useKeyType.getAny();
            NodeList x509CertData = elementNSImpl.getElementsByTagNameNS(Constants.SignatureSpecNS,
                    Constants._TAG_X509CERTIFICATE);
            if (x509CertData != null && x509CertData.getLength() > 0) {
                x509 = Base64.decodeBase64(x509CertData.item(0).getTextContent().getBytes());
            }
        }
        if (x509 != null) {
            CertificateFactory cf = CertificateFactory.getInstance(X_509);
            Certificate certificate = cf.generateCertificate(new ByteArrayInputStream(x509));
            X509Certificate x509Cert = (X509Certificate) certificate;
            return x509Cert;
        }

    }
    return null;
}

From source file:cc.abstra.trantor.security.ssl.OwnSSLProtocolSocketFactory.java

/**
 * Describe <code>verifyHostname</code> method here.
 *
 * @param socket a <code>SSLSocket</code> value
 * @exception SSLPeerUnverifiedException  If there are problems obtaining
 * the server certificates from the SSL session, or the server host name 
 * does not match with the "Common Name" in the server certificates 
 * SubjectDN./*from  w w w .  j  av  a2s . co  m*/
 * @exception UnknownHostException  If we are not able to resolve
 * the SSL sessions returned server host name. 
 */
private void verifyHostname(SSLSocket socket) throws SSLPeerUnverifiedException, UnknownHostException {
    if (sslManager == null) {
        return;
    }
    ISSLErrorManager errorMng = sslManager.getSSLErrorManager();
    if (errorMng == null) {
        return;
    }

    SSLSession session = socket.getSession();
    String hostname = session.getPeerHost();
    try {
        InetAddress.getByName(hostname);
    } catch (UnknownHostException uhe) {
        throw new UnknownHostException("Could not resolve SSL sessions " + "server hostname: " + hostname);
    }

    X509Certificate[] certs = session.getPeerCertificateChain();
    if (certs == null || certs.length == 0)
        throw new SSLPeerUnverifiedException("No server certificates found!");

    //get the servers DN in its string representation
    String dn = certs[0].getSubjectDN().getName();

    //might be useful to print out all certificates we receive from the
    //server, in case one has to debug a problem with the installed certs.
    if (LOG.isDebugEnabled()) {
        LOG.debug("Server certificate chain:");
        for (int i = 0; i < certs.length; i++) {
            LOG.debug("X509Certificate[" + i + "]=" + certs[i]);
        }
    }
    //get the common name from the first cert
    String cn = getCN(dn);
    if (hostname.equalsIgnoreCase(cn)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Target hostname valid: " + cn);
        }
    } else {
        try {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            java.security.cert.X509Certificate servCert = (java.security.cert.X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(certs[0].getEncoded()));
            if (!errorMng.continueErrorPeer(hostname, servCert)) {
                throw new SSLPeerUnverifiedException(
                        "HTTPS hostname invalid: expected '" + hostname + "', received '" + cn + "'");
            }
        } catch (CertificateException ex) {
            LOG.error(ex.getMessage(), ex);
            throw new SSLPeerUnverifiedException(
                    "Unexpected error checking HTTPS hostname: " + ex.getMessage());
        } catch (CertificateEncodingException ex) {
            LOG.error(ex.getMessage(), ex);
            throw new SSLPeerUnverifiedException(
                    "Unexpected error checking HTTPS hostname: " + ex.getMessage());
        }
    }
}

From source file:be.fedict.trust.BelgianTrustValidatorFactory.java

private static X509Certificate loadCertificate(String resourceName) {
    LOG.debug("loading certificate: " + resourceName);
    Thread currentThread = Thread.currentThread();
    ClassLoader classLoader = currentThread.getContextClassLoader();
    InputStream certificateInputStream = classLoader.getResourceAsStream(resourceName);
    if (null == certificateInputStream) {
        throw new IllegalArgumentException("resource not found: " + resourceName);
    }//from   ww  w.  jav a2  s.c o  m
    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        X509Certificate certificate = (X509Certificate) certificateFactory
                .generateCertificate(certificateInputStream);
        return certificate;
    } catch (CertificateException e) {
        throw new RuntimeException("X509 error: " + e.getMessage(), e);
    }
}

From source file:be.fedict.eid.idp.admin.webapp.bean.ConfigBean.java

private X509Certificate getCertificate(byte[] certificateBytes) throws CertificateException {
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    return (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificateBytes));
}

From source file:org.apache.taverna.security.credentialmanager.impl.CredentialManagerImpl.java

public void deleteRevokedCertificates() {

    if (truststore != null) {
        // Delete the old revoked or unnecessary BioCatalogue,
        // BiodiversityCatalogue and heater's certificates, if present

        if (certificatesRevokedIndicatorFile == null) {
            certificatesRevokedIndicatorFile = new File(credentialManagerDirectory,
                    CERTIFICATES_REVOKED_INDICATOR_FILE_NAME);
        }//from  www  . j  av  a 2  s .c o m

        if (!certificatesRevokedIndicatorFile.exists()) {

            List<URL> certURLsToDelete = new ArrayList<>();
            Class<?> c = CredentialManager.class;
            //certURLsToDelete.add(c.getResource("/trusted-certificates/www.biocatalogue.org-revoked.pem"));
            //certURLsToDelete.add(c.getResource("/trusted-certificates/www.biodiversitycatalogue.org-revoked.pem"));
            //certURLsToDelete.add(c.getResource("/trusted-certificates/heater.cs.man.ac.uk-not-needed.pem"));

            for (URL certURLToDelete : certURLsToDelete) {
                try (InputStream certStreamToDelete = certURLToDelete.openStream()) {
                    // We know there will be only one cert in the chain
                    CertificateFactory cf = CertificateFactory.getInstance("X.509");
                    Certificate certToDelete = cf.generateCertificates(certStreamToDelete)
                            .toArray(new Certificate[0])[0];
                    String aliasToDelete = truststore.getCertificateAlias(certToDelete);
                    if (aliasToDelete != null) {
                        truststore.deleteEntry(aliasToDelete);
                        logger.warn("Deleting revoked/unnecessary certificate " + aliasToDelete);
                    }
                } catch (Exception ex) {
                    logger.info("Can't delete revoked certificate " + certURLToDelete, ex);
                }
            }

            // Touch the file
            try {
                FileUtils.touch(certificatesRevokedIndicatorFile);
            } catch (IOException ioex) {
                // Hmmm, ignore this?
                logger.error("Failed to touch " + certificatesRevokedIndicatorFile.getAbsolutePath(), ioex);
            }
        }

        //Save changes
        try {
            FileOutputStream fos = new FileOutputStream(truststoreFile);
            truststore.store(fos, masterPassword.toCharArray());
        } catch (Exception ex) {
            String exMessage = "Failed to save Truststore after deleting revoked certificates.";
            logger.error(exMessage, ex);
        }
    }
}

From source file:com.xwiki.authentication.saml.XWikiSAMLAuthenticator.java

/**
 * {@inheritDoc}//from w  ww  .j  av a2s. c  o m
 *
 * @see com.xpn.xwiki.user.impl.xwiki.AppServerTrustedAuthServiceImpl#checkSAMLResponse(com.xpn.xwiki.XWikiContext)
 */
public boolean checkSAMLResponse(XWikiContext context) throws XWikiException {
    // read from SAMLResponse
    XWikiRequest request = context.getRequest();
    Map attributes = new HashMap();

    String samlResponse = request.getParameter("SAMLResponse");
    if (samlResponse == null)
        return false;

    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Reading SAML Response");
        }
        samlResponse = new String(Base64.decode(samlResponse), "UTF-8");

        if (LOG.isDebugEnabled()) {
            LOG.debug("SAML Response is " + samlResponse);
        }

        // Get parser pool manager
        BasicParserPool ppMgr = new BasicParserPool();
        ppMgr.setNamespaceAware(true);
        Document inCommonMDDoc;

        inCommonMDDoc = ppMgr.parse(new StringReader(samlResponse));
        Element ResponseRoot = inCommonMDDoc.getDocumentElement();
        // Get apropriate unmarshaller
        UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
        Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(ResponseRoot);
        // Unmarshall using the document root element, an EntitiesDescriptor
        Response response = (Response) unmarshaller.unmarshall(ResponseRoot);

        // reading cert
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        String cert = getSAMLCertificate(context);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Verification signature using certificate " + cert);
        }
        InputStream sis = context.getEngineContext().getResourceAsStream(cert);
        X509Certificate certificate = (X509Certificate) cf.generateCertificate(sis);
        sis.close();

        response.validate(true);
        Signature signature = response.getSignature();
        SAMLSignatureProfileValidator pv = new SAMLSignatureProfileValidator();
        pv.validate(signature);
        BasicX509Credential credential = new BasicX509Credential();
        credential.setEntityCertificate(certificate);
        SignatureValidator sigValidator = new SignatureValidator(credential);
        sigValidator.validate(signature);

        Assertion subjectAssertion = null;
        boolean isValidDate = true;

        if (LOG.isDebugEnabled()) {
            LOG.debug("Reading SAML User data");
        }

        // Verify assertions
        for (Assertion a : response.getAssertions()) {
            // Find subject assertions
            if (a.getAuthnStatements().size() > 0) {
                if (a.getConditions().getNotOnOrAfter().isBeforeNow())
                    isValidDate = false;
            }

            // Process all attributes
            for (AttributeStatement attStatement : a.getAttributeStatements()) {
                for (Attribute att : attStatement.getAttributes()) {
                    for (XMLObject val : att.getAttributeValues()) {
                        attributes.put(att.getName(), ((XSStringImpl) val).getValue());
                    }
                }
                for (EncryptedAttribute att : attStatement.getEncryptedAttributes()) {
                    for (XMLObject val : ((Attribute) att).getAttributeValues()) {
                        attributes.put(((Attribute) att).getName(), ((XSStringImpl) val).getValue());
                    }
                }
            }
        }

        String samlid1 = response.getInResponseTo();
        String samlid2 = (String) request.getSession().getAttribute("saml_id");
        if (isValidDate == false) {
            // invalid ID
            if (LOG.isErrorEnabled()) {
                LOG.error("SAML Dates are invalid");
            }
            return false;
        }
        if (!samlid1.equals(samlid2)) {
            // invalid ID
            if (LOG.isErrorEnabled()) {
                LOG.error("SAML ID do not match " + samlid1 + " " + samlid2);
            }
            return false;
        }
    } catch (Exception e1) {
        // failed to read SAMLResponse
        if (LOG.isErrorEnabled()) {
            LOG.error("Failed Reading SAML Response", e1);
        }
        return false;
    }

    // let's map the data
    Map<String, String> userData = getExtendedInformations(attributes, context);

    String nameID = (String) attributes.get(getIdFieldName(context));
    if (LOG.isDebugEnabled()) {
        LOG.debug("SAML ID is " + nameID);
        LOG.debug("SAML attributes are " + attributes);
        LOG.debug("SAML user data are " + userData);
    }

    String sql = "select distinct doc.fullName from XWikiDocument as doc, BaseObject as obj, StringProperty as nameidprop where doc.fullName=obj.name and obj.className='XWiki.SAMLAuthClass' and obj.id=nameidprop.id.id and nameidprop.id.name='nameid' and nameidprop.value='"
            + nameID + "'";
    List list = context.getWiki().search(sql, context);
    String validFullUserName = null;
    String validUserName = null;

    if (list.size() == 0) {
        // User does not exist. Let's generate a unique page name      
        if (LOG.isDebugEnabled()) {
            LOG.debug("Did not find XWiki User. Generating it.");
        }
        String userName = generateXWikiUsername(userData, context);
        if (userName.equals(""))
            userName = "user";
        validUserName = context.getWiki().getUniquePageName("XWiki", userName, context);
        validFullUserName = "XWiki." + validUserName;
        if (LOG.isDebugEnabled()) {
            LOG.debug("Generated XWiki User Name " + validFullUserName);
        }
    } else {
        validFullUserName = (String) list.get(0);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Found XWiki User " + validFullUserName);
        }
    }

    // we found a user or generated a unique user name       
    if (validFullUserName != null) {
        // check if we need to create/update a user page
        String database = context.getDatabase();
        try {
            // Switch to main wiki to force users to be global users
            context.setDatabase(context.getMainXWiki());

            // test if user already exists
            if (!context.getWiki().exists(validFullUserName, context)) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Need to create user " + validFullUserName);
                }

                // create user
                userData.put("active", "1");

                int result = context.getWiki().createUser(validUserName, userData, "XWiki.XWikiUsers",
                        "#includeForm(\"XWiki.XWikiUserSheet\")", "edit", context);
                if (result < 0) {
                    if (LOG.isErrorEnabled()) {
                        LOG.error("Failed to create user " + validFullUserName + " with code " + result);
                    }
                    return false;
                }
                XWikiDocument userDoc = context.getWiki().getDocument(validFullUserName, context);
                BaseObject obj = userDoc.newObject("XWiki.SAMLAuthClass", context);
                obj.set("nameid", nameID, context);
                context.getWiki().saveDocument(userDoc, context);

                if (LOG.isDebugEnabled()) {
                    LOG.debug("User " + validFullUserName + " has been successfully created");
                }
            } else {
                XWikiDocument userDoc = context.getWiki().getDocument(validFullUserName, context);
                BaseObject userObj = userDoc.getObject("XWiki.XWikiUsers");
                boolean updated = false;

                for (Map.Entry<String, String> entry : userData.entrySet()) {
                    String field = entry.getKey();
                    String value = entry.getValue();
                    BaseProperty prop = (BaseProperty) userObj.get(field);
                    String currentValue = (prop == null || prop.getValue() == null) ? null
                            : prop.getValue().toString();
                    if (value != null && !value.equals(currentValue)) {
                        userObj.set(field, value, context);
                        updated = true;
                    }
                }

                if (updated == true) {
                    context.getWiki().saveDocument(userDoc, context);

                    if (LOG.isDebugEnabled()) {
                        LOG.debug("User " + validFullUserName + " has been successfully updated");
                    }
                }

            }
        } catch (Exception e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Failed to create user " + validFullUserName, e);
            }
            return false;
        } finally {
            context.setDatabase(database);
        }
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Setting authentication in session for user " + validFullUserName);
    }

    // mark that we have authenticated the user in the session
    context.getRequest().getSession().setAttribute(getAuthFieldName(context), validFullUserName);

    // need to redirect now
    try {
        String sourceurl = (String) request.getSession().getAttribute("saml_url");
        if (LOG.isDebugEnabled()) {
            LOG.debug("Redirecting after valid authentication to " + sourceurl);
        }
        context.getResponse().sendRedirect(sourceurl);
        context.setFinished(true);
        return true;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return false;
}

From source file:org.panbox.core.crypto.CryptCore.java

/**
 * Creates an X509 Certificate for a given byte array
 * //from   w w  w. j  a v  a  2s . co m
 * @param certBytes
 * @return
 */
public static X509Certificate createCertificateFromBytes(byte[] certBytes) {
    X509Certificate cert = null;
    CertificateFactory certFactory;
    try {
        certFactory = CertificateFactory.getInstance("X.509");

        InputStream in = new ByteArrayInputStream(certBytes);
        cert = (X509Certificate) certFactory.generateCertificate(in);

    } catch (CertificateException e) {
        logger.warn("Excpetion caught in CryptCore." + "createCertificateFromBytes, returning null", e);
    }

    return cert;
}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImpl.java

/**
 * Delete the old revoked or unnecessary BioCatalogue, BiodiversityCatalogue
 * and heater's certificates, if present
 *///from   ww w . j a  va  2  s  .c om
public void deleteRevokedCertificates() {
    if (truststore == null)
        return;
    if (certificatesRevokedIndicatorFile == null)
        certificatesRevokedIndicatorFile = new File(credentialManagerDirectory,
                CERTIFICATES_REVOKED_INDICATOR_FILE_NAME);

    boolean saveFile = false;
    if (!certificatesRevokedIndicatorFile.exists()) {
        List<URL> certURLsToDelete = new ArrayList<>();
        Class<?> c = CredentialManager.class;
        certURLsToDelete.add(c.getResource("/trusted-certificates/www.biocatalogue.org-revoked.pem"));
        certURLsToDelete.add(c.getResource("/trusted-certificates/www.biodiversitycatalogue.org-revoked.pem"));
        certURLsToDelete.add(c.getResource("/trusted-certificates/heater.cs.man.ac.uk-not-needed.pem"));

        for (URL certURLToDelete : certURLsToDelete) {
            try (InputStream certStreamToDelete = certURLToDelete.openStream()) {
                // We know there will be only one cert in the chain
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                Certificate certToDelete = cf.generateCertificates(certStreamToDelete)
                        .toArray(new Certificate[0])[0];
                String aliasToDelete = truststore.getCertificateAlias(certToDelete);
                if (aliasToDelete != null) {
                    truststore.deleteEntry(aliasToDelete);
                    logger.warn("Deleting revoked/unnecessary certificate " + aliasToDelete);
                    saveFile = true;
                }
            } catch (Exception ex) {
                logger.info("Can't delete revoked certificate " + certURLToDelete, ex);
            }
        }

        // Touch the file
        try {
            touch(certificatesRevokedIndicatorFile);
        } catch (IOException ioex) {
            // Hmmm, ignore this?
            logger.error("Failed to touch " + certificatesRevokedIndicatorFile.getAbsolutePath(), ioex);
        }
    }

    if (saveFile) {
        // Save changes
        try (FileOutputStream fos = new FileOutputStream(truststoreFile)) {
            truststore.store(fos, masterPassword.toCharArray());
        } catch (Exception ex) {
            logger.error("Failed to save Truststore after deleting revoked certificates.", ex);
        }
    }
}

From source file:net.jsign.PESignerCLI.java

/**
 * Load the certificate chain from the specified PKCS#7 files.
 *//* w  ww .  j a va 2s  .c  o m*/
@SuppressWarnings("unchecked")
private Certificate[] loadCertificateChain(File file) throws IOException, CertificateException {
    FileInputStream in = null;
    try {
        in = new FileInputStream(file);
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        Collection<Certificate> certificates = (Collection<Certificate>) certificateFactory
                .generateCertificates(in);
        return certificates.toArray(new Certificate[certificates.size()]);
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            // ignore
        }
    }
}

From source file:org.jvnet.hudson.update_center.Main.java

/**
 * Loads a certificate chain and makes sure it's valid.
 *//*from  w w  w  .  ja  v a 2 s  . c o  m*/
protected List<X509Certificate> getCertificateChain() throws IOException, GeneralSecurityException {
    CertificateFactory cf = CertificateFactory.getInstance("X509");
    List<X509Certificate> certs = new ArrayList<X509Certificate>();
    for (File f : certificates) {
        X509Certificate c = loadCertificate(cf, f);
        c.checkValidity(new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(30)));
        certs.add(c);
    }

    Set<TrustAnchor> rootCAs = CertificateUtil.getDefaultRootCAs();
    rootCAs.add(new TrustAnchor(
            (X509Certificate) cf.generateCertificate(getClass().getResourceAsStream("/hudson-community.cert")),
            null));
    for (File f : rootCA) {
        rootCAs.add(new TrustAnchor(loadCertificate(cf, f), null));
    }

    try {
        CertificateUtil.validatePath(certs, rootCAs);
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
    }
    return certs;
}