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:com.blackducksoftware.integration.hub.jenkins.site.BlackDuckHubUpdateSite.java

static X509Certificate loadLicenseCaCertificate() throws CertificateException {
    final CertificateFactory cf = CertificateFactory.getInstance("X.509");
    final InputStream stream = BlackDuckHubUpdateSite.class
            .getResourceAsStream("/blackduck-hub-root-cacert.pem");
    try {//ww  w  . j  av a2 s .  co m
        return stream != null ? (X509Certificate) cf.generateCertificate(stream) : null;
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

From source file:de.extra.client.plugins.outputplugin.transport.ExtraTransportHttp.java

/**
 * Sets up the Truststore.//from  www.ja v  a 2 s.c  o  m
 * 
 * @param extraConnectData
 * @return
 */
private void setupTruststore(final HttpOutputPluginConnectConfiguration extraConnectData)
        throws ExtraTransportException {

    // Load TrustStoreLocation from properties
    String truststoreLocation = extraConnectData.getSslTruststoreLocation();

    LOG.debug("TruststoreLoc: " + truststoreLocation);

    // If no location specified -> fallback to JRE default
    if (truststoreLocation == null || truststoreLocation.length() == 0) {
        truststoreLocation = System.getProperty("java.home") + File.separatorChar + "lib" + File.separatorChar
                + "security" + File.separatorChar + "cacerts";
    }

    LOG.debug("TruststoreLoc: " + truststoreLocation);

    try {
        // Create keystore instance
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        // KeyStore ks = KeyStore.getInstance("PKCS12");

        // Load keystore values
        FileInputStream fi = new FileInputStream(truststoreLocation);
        ks.load(fi, extraConnectData.getSslTruststorePassword().toCharArray());
        fi.close();

        // Create new certificate based on stored value
        java.security.cert.CertificateFactory certFactory = CertificateFactory.getInstance("X.509");

        X509Certificate cert = (X509Certificate) certFactory
                .generateCertificate(new ByteArrayInputStream(extraConnectData.getSslCertificate().getBytes()));

        // Check if certificate is not already stored -> store and save
        if (extraConnectData.isSslCertificateRefresh() || ks.getCertificateAlias(cert) == null) {

            LOG.info("Zertifikat wird eingetragen");

            ks.store(new FileOutputStream(truststoreLocation),
                    extraConnectData.getSslTruststorePassword().toCharArray());

        }

        // Set truststore location
        System.setProperty("javax.net.ssl.trustStore", truststoreLocation);

    } catch (KeyStoreException e) {
        throw new ExtraTransportException("Fehler bei Zugriff auf Keystore.", e);
    } catch (FileNotFoundException e) {
        throw new ExtraTransportException("Fehler beim Laden des Keystore.", e);
    } catch (NoSuchAlgorithmException e) {
        throw new ExtraTransportException("Fehler beim Laden des Crypto-Algorithmus.", e);
    } catch (CertificateException e) {
        throw new ExtraTransportException("Fehler beim Prfen des Zertifikats.", e);
    } catch (IOException e) {
        throw new ExtraTransportException("Fehler bei I/O-Operation.", e);
    }
}

From source file:net.sf.jsignpdf.utils.KeyStoreUtils.java

/**
 * Loads a {@link X509Certificate} from the given path. Returns null if the
 * certificate can't be loaded./*from ww  w .j a va2s. c o  m*/
 * 
 * @param filePath
 * @return
 */
public static X509Certificate loadCertificate(final String filePath) {
    if (StringUtils.isEmpty(filePath)) {
        LOGGER.debug("Empty file path");
        return null;
    }
    FileInputStream inStream = null;
    X509Certificate cert = null;
    try {
        final CertificateFactory certFac = CertificateFactory.getInstance(Constants.CERT_TYPE_X509); // X.509
        inStream = FileUtils.openInputStream(new File(filePath));
        cert = (X509Certificate) certFac.generateCertificate(inStream);
    } catch (Exception e) {
        LOGGER.debug("Unable to load certificate", e);
    } finally {
        IOUtils.closeQuietly(inStream);
    }
    return cert;
}

From source file:com.esri.geoevent.datastore.GeoEventDataStoreProxy.java

synchronized private void readSiteCertificates(ServletContext servletContext) {
    if (trustedCerts != null)
        return;/*from  w w  w .ja  v  a 2s.  c  o  m*/

    trustedCerts = new ArrayList<>();

    // Now to add the other certificates added to the site
    File certsDirectory = new File(servletContext.getRealPath("/WEB-INF/classes/certificates"));
    try {
        if (certsDirectory.exists()) {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            String[] certs = certsDirectory.list(new FilenameFilter() {

                @Override
                public boolean accept(File dir, String fileName) {
                    return fileName.endsWith(".crt") || fileName.endsWith(".cer") || fileName.endsWith(".pem");
                }

            });
            if (certs != null) {
                X509Certificate x509Cert;
                for (String cert : certs) {
                    try (FileInputStream fis = new FileInputStream(new File(certsDirectory, cert))) {
                        x509Cert = (X509Certificate) cf.generateCertificate(fis);
                    }
                    if (x509Cert != null && !trustedCerts.contains(x509Cert)) {
                        trustedCerts.add(x509Cert);
                    }
                }
            }
        }
    } catch (Throwable e1) {
        LOG.log(Level.INFO, "Failed to load certificates from diretory " + certsDirectory.getAbsolutePath(),
                e1);
    }
}

From source file:org.casbah.provider.openssl.OpenSslCAProvider.java

private X509CRL loadCrlFromFile()
        throws FileNotFoundException, IOException, CRLException, CertificateException {
    FileInputStream fis = new FileInputStream(new File(caRootDir, CRL_FILE));
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509CRL result = (X509CRL) cf.generateCRL(fis);
    fis.close();/* ww  w  .jav  a  2s.c om*/
    return result;
}

From source file:edu.lternet.pasta.gatekeeper.GatekeeperFilter.java

private Boolean isValidSignature(String tokenString, byte[] signature) {

    Boolean isValid = false;//from   w w  w .  j  a v a2s .c  om

    File lterCert = ConfigurationListener.getLterCertificate();

    try {

        FileInputStream certFis = new FileInputStream(lterCert);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) cf.generateCertificate(certFis);

        PublicKey pubKey = cert.getPublicKey();

        Signature sig = Signature.getInstance("MD5withRSA");
        sig.initVerify(pubKey);

        sig.update(tokenString.getBytes());
        isValid = sig.verify(signature);

    } catch (FileNotFoundException e) {
        logger.error("Gatekeeper.validateSignature :" + e.getMessage());
        e.printStackTrace();
    } catch (CertificateException e) {
        logger.error("Gatekeeper.validateSignature :" + e.getMessage());
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        logger.error("Gatekeeper.validateSignature :" + e.getMessage());
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        logger.error("Gatekeeper.validateSignature :" + e.getMessage());
        e.printStackTrace();
    } catch (SignatureException e) {
        logger.error("Gatekeeper.validateSignature :" + e.getMessage());
        e.printStackTrace();
    }

    return isValid;

}

From source file:eu.stork.peps.auth.engine.core.impl.SignSW.java

/**
 * @param tokenSaml token SAML//from ww w  . j  av  a 2 s.c  o m
 * @return the SAMLObject validated.
 * @throws SAMLEngineException error validate signature
 * @see eu.stork.peps.auth.engine.core.SAMLEngineSignI#validateSignature(org.opensaml.common.SignableSAMLObject)
 */
public final SAMLObject validateSignature(final SignableSAMLObject tokenSaml) throws SAMLEngineException {
    LOG.info("Start signature validation.");
    try {

        // Validate structure signature
        final SAMLSignatureProfileValidator sigProfValidator = new SAMLSignatureProfileValidator();
        try {
            // Indicates signature id conform to SAML Signature profile
            sigProfValidator.validate(tokenSaml.getSignature());
        } catch (ValidationException e) {
            LOG.error("ValidationException: signature isn't conform to SAML Signature profile.");
            throw new SAMLEngineException(e);
        }

        String aliasCert = null;
        X509Certificate certificate;

        final List<Credential> trustCred = new ArrayList<Credential>();

        for (final Enumeration<String> e = storkOwnKeyStore.aliases(); e.hasMoreElements();) {
            aliasCert = e.nextElement();
            final BasicX509Credential credential = new BasicX509Credential();
            certificate = (X509Certificate) storkOwnKeyStore.getCertificate(aliasCert);
            credential.setEntityCertificate(certificate);
            trustCred.add(credential);
        }

        final KeyInfo keyInfo = tokenSaml.getSignature().getKeyInfo();

        final org.opensaml.xml.signature.X509Certificate xmlCert = keyInfo.getX509Datas().get(0)
                .getX509Certificates().get(0);

        final CertificateFactory certFact = CertificateFactory.getInstance("X.509");
        final ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decode(xmlCert.getValue()));
        final X509Certificate cert = (X509Certificate) certFact.generateCertificate(bis);

        // Exist only one certificate
        final BasicX509Credential entityX509Cred = new BasicX509Credential();
        entityX509Cred.setEntityCertificate(cert);

        try {
            cert.checkValidity();
        } catch (CertificateExpiredException exp) {
            throw new SAMLEngineException("Certificate expired.");
        } catch (CertificateNotYetValidException exp) {
            throw new SAMLEngineException("Certificate not yet valid.");
        }

        /* A better use of PKI based validation but not wanted for STORK... 
          boolean trusted = false;
                
        for (final Enumeration<String> e = storkOwnKeyStore.aliases(); e.hasMoreElements();) 
         {
            aliasCert = e.nextElement();      
            certificate = (X509Certificate) storkOwnKeyStore.getCertificate(aliasCert);               
            try {
               cert.verify(certificate.getPublicKey());
               trusted = true;
               break;
            }
            catch (Exception ex) {
               //Do nothing - cert not trusted yet
            }
         }
                
        if (!trusted)
            throw new SAMLEngineException("Certificate is not trusted.");*/

        // Validate trust certificates
        final ExplicitX509CertificateTrustEvaluator chainTrustEvaluator = new ExplicitX509CertificateTrustEvaluator();

        if (!chainTrustEvaluator.validate(entityX509Cred, trustCred)) {
            throw new SAMLEngineException("Certificate is not trusted.");
        }
        final ExplicitKeyTrustEvaluator keyTrustEvaluator = new ExplicitKeyTrustEvaluator();

        if (!keyTrustEvaluator.validate(entityX509Cred, trustCred)) {
            throw new SAMLEngineException("Certificate is not trusted.");
        }

        // Validate signature
        final SignatureValidator sigValidator = new SignatureValidator(entityX509Cred);
        sigValidator.validate(tokenSaml.getSignature());

    } catch (ValidationException e) {
        LOG.error("ValidationException.");
        throw new SAMLEngineException(e);
    } catch (KeyStoreException e) {
        LOG.error("KeyStoreException.", e);
        throw new SAMLEngineException(e);
    } catch (GeneralSecurityException e) {
        LOG.error("GeneralSecurityException.", e);
        throw new SAMLEngineException(e);
    }
    LOG.info(tokenSaml.getSignatureReferenceID());
    LOG.info("Start signature validation - END.");
    return tokenSaml;
}

From source file:be.fedict.eid.tsl.TrustService.java

public X509Certificate getServiceDigitalIdentity() {
    TSPServiceInformationType tspServiceInformation = this.tspService.getServiceInformation();
    DigitalIdentityListType digitalIdentityList = tspServiceInformation.getServiceDigitalIdentity();
    try {/*from ww  w  . j a  va2 s  .  c  om*/
        final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        for (final DigitalIdentityType digitalIdentity : digitalIdentityList.getDigitalId()) {
            byte[] x509CertificateData = digitalIdentity.getX509Certificate();
            if (x509CertificateData != null) {
                try {
                    X509Certificate certificate = (X509Certificate) certificateFactory
                            .generateCertificate(new ByteArrayInputStream(x509CertificateData));
                    return certificate;
                } catch (CertificateException e) {
                    throw new RuntimeException("X509 error: " + e.getMessage(), e);
                }
            }
        }
        throw new RuntimeException("No X509Certificate identity specified");
    } catch (CertificateException e) {
        throw new RuntimeException("X509 error: " + e.getMessage(), e);
    }
}

From source file:eu.stork.peps.auth.engine.core.impl.SignP12.java

/**
 * Validate signature.//from   w  ww  .  j  a v  a2s  . c  om
 * 
 * @param tokenSaml token SAML
 * 
 * @return the SAMLObject validated.
 * 
 * @throws SAMLEngineException error validate signature
 * 
 */
@Override
public SAMLObject validateSignature(final SignableSAMLObject tokenSaml) throws SAMLEngineException {
    LOG.info("Start signature validation.");
    try {

        // Validate structure signature
        final SAMLSignatureProfileValidator sigProfValidator = new SAMLSignatureProfileValidator();
        try {
            // Indicates signature id conform to SAML Signature profile
            sigProfValidator.validate(tokenSaml.getSignature());
        } catch (ValidationException e) {
            LOG.error("ValidationException: signature isn't conform to SAML Signature profile.");
            throw new SAMLEngineException(e);
        }

        String aliasCert = null;
        X509Certificate certificate;

        final List<Credential> trustCred = new ArrayList<Credential>();

        for (final Enumeration<String> e = trustStore.aliases(); e.hasMoreElements();) {
            aliasCert = e.nextElement();
            final BasicX509Credential credential = new BasicX509Credential();
            certificate = (X509Certificate) trustStore.getCertificate(aliasCert);
            credential.setEntityCertificate(certificate);
            trustCred.add(credential);
        }

        final KeyInfo keyInfo = tokenSaml.getSignature().getKeyInfo();

        final org.opensaml.xml.signature.X509Certificate xmlCert = keyInfo.getX509Datas().get(0)
                .getX509Certificates().get(0);

        final CertificateFactory certFact = CertificateFactory.getInstance("X.509");
        final ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decode(xmlCert.getValue()));
        final X509Certificate cert = (X509Certificate) certFact.generateCertificate(bis);

        // Exist only one certificate
        final BasicX509Credential entityX509Cred = new BasicX509Credential();
        entityX509Cred.setEntityCertificate(cert);

        /* A better use of PKI based validation but not wanted for STORK...
        boolean trusted = false;
                
        for (final Enumeration<String> e = trustStore.aliases(); e.hasMoreElements();) 
        {
           aliasCert = e.nextElement();      
           certificate = (X509Certificate) trustStore.getCertificate(aliasCert);               
           try {
              cert.verify(certificate.getPublicKey());
              trusted = true;
              break;
           }
           catch (Exception ex) {
              //Do nothing - cert not trusted yet
           }
        }
                
        if (!trusted)
           throw new SAMLEngineException("Certificate is not trusted.");*/

        // Validate trust certificates
        final ExplicitKeyTrustEvaluator keyTrustEvaluator = new ExplicitKeyTrustEvaluator();
        if (!keyTrustEvaluator.validate(entityX509Cred, trustCred)) {
            throw new SAMLEngineException("Certificate it is not trusted.");
        }

        // Validate signature
        final SignatureValidator sigValidator = new SignatureValidator(entityX509Cred);
        sigValidator.validate(tokenSaml.getSignature());

    } catch (ValidationException e) {
        LOG.error("ValidationException.");
        throw new SAMLEngineException(e);
    } catch (KeyStoreException e) {
        LOG.error("KeyStoreException.", e);
        throw new SAMLEngineException(e);
    } catch (GeneralSecurityException e) {
        LOG.error("GeneralSecurityException.", e);
        throw new SAMLEngineException(e);
    }
    return tokenSaml;
}

From source file:eu.europa.ejusticeportal.dss.applet.DssApplet.java

/** 
 * This methods checks if the data coming from the server can be trusted.
 * The hash provided by the server is checked using the public key.
 * @param data the data coming from the server.
 * @param serverHash the hash of the data coming from the server.
 * @param algo the algorithm used for the server hash.
 * @return <code>true</code> if the serverHash can be verified with the public key.
 *//*from  w w  w . ja  v a 2 s. c  o  m*/
private boolean canTrustServerHash(final String data, final String serverHash, final String algo) {
    Certificate certificate;
    InputStream pemInputStream;
    try {
        pemInputStream = getClass().getClassLoader().getResourceAsStream("certificate.pem");
        if (pemInputStream == null) {
            LOG.log(Level.SEVERE,
                    "Missing certificate.pem file. Impossible to check if the data coming from the server can be trusted.");
            return false;
        }
    } catch (Exception e) {
        LOG.log(Level.SEVERE,
                "Missing certificate.pem file. Impossible to check if the data coming from the server can be trusted.");
        return false;
    }

    try {
        certificate = CertificateFactory.getInstance("X.509").generateCertificate(pemInputStream);
        PublicKey publicKey = certificate.getPublicKey();
        Signature sigVerify = Signature.getInstance(new String(Base64.decodeBase64(algo)), "BC");
        sigVerify.initVerify(publicKey);
        sigVerify.update(data.getBytes("UTF-8"));

        boolean signatureMatch = sigVerify.verify(Base64.decodeBase64(serverHash));
        if (signatureMatch) {
            LOG.log(Level.INFO, "The data coming from the server can be trusted.");
            return true;
        } else {
            LOG.log(Level.SEVERE, "!!! Tampered data received !!!");
            LOG.log(Level.INFO, serverHash);
            LOG.log(Level.INFO, data);
            return false;
        }
    } catch (CertificateException e) {
        LOG.error(e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        LOG.error(e.getMessage(), e);
    } catch (NoSuchProviderException e) {
        LOG.error(e.getMessage(), e);
    } catch (InvalidKeyException e) {
        LOG.error(e.getMessage(), e);
    } catch (SignatureException e) {
        LOG.error(e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        LOG.error(e.getMessage(), e);
    }
    LOG.log(Level.SEVERE, "Impossible to check if the data coming from the server can be trusted.");
    return false;
}