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:net.sf.taverna.cagrid.activity.CaGridActivity.java

/**
 * Load the trusted caGrid CAs' certificates and store them in 
 * the Truststore and in a special folder (inside Taverna's security 
 * conf folder) so that globus can look them up as well.
 *///from  www . ja v a  2 s.  c  om
private static void loadCaGridCAsCertificates() {

    // If not already done, import the caGrid Trusted CAs' certificates into Taverna's truststore
    // Get the location of Taverna's security configuration directory
    File secConfigDirectory = CMUtil.getSecurityConfigurationDirectory();
    File caGridSecConfigDirectory = new File(secConfigDirectory, "cagrid");
    caGridSecConfigDirectory.mkdirs();
    // Tructes CAs folder
    File trustedCertsDirectory = new File(caGridSecConfigDirectory, "trusted-certificates");
    trustedCertsDirectory.mkdirs();

    // Set the system property read by Globus to determine the location 
    // of the folder containing the caGrid trusted CAs' certificates 
    System.setProperty("X509_CERT_DIR", trustedCertsDirectory.getAbsolutePath());

    // Get the file which existence implies that caGrid trusted CAs have been loaded
    File caCertsLoadedFile = new File(caGridSecConfigDirectory, "trustedCAsLoaded.txt");

    if (!caCertsLoadedFile.exists() || System.getenv("TWS_USER_PROXY") != null) {
        logger.info("caGrid plugin is loading trusted certificates \n of caGrid CAs into Credential Manager.");

        if (System.getenv("TWS_USER_PROXY") == null) {
            JOptionPane.showMessageDialog(null,
                    "caGrid plugin is loading trusted certificates \n of caGrid CAs into Credential Manager.",
                    "CaGrid plugin message", JOptionPane.INFORMATION_MESSAGE);
        }
        List<String> certificateResources = new ArrayList<String>();
        certificateResources.add("1c3f2ca8.0");
        certificateResources.add("62f4fd66.0");
        certificateResources.add("68907d53.0");
        certificateResources.add("8e3e7e54.0");
        certificateResources.add("d1b603c3.0");
        certificateResources.add("ed524cf5.0");
        certificateResources.add("0ad31d10.0");
        certificateResources.add("17e36bb5.0");
        certificateResources.add("f3b3491b.0");
        certificateResources.add("d0b62510.0");//to be replaced by its CA cert

        CredentialManager cm = null;
        try {
            //TODO something wrong here, needs correction
            cm = CredentialManager.getInstance();

        } catch (CMException cmex) {
            // We are in deep trouble here - something's wrong with Credential Manager
            String exMessage = "Failed to instantiate Credential Manager - cannot load caGrid CAs' certificates.";
            JOptionPane.showMessageDialog(null, exMessage, "CaGrid plugin message", JOptionPane.ERROR_MESSAGE);
            cmex.printStackTrace();
            logger.error(exMessage);
            return;
        }

        for (String certificate : certificateResources) {
            InputStream certStream = null;
            try {
                String certificateResourcePath = "/trusted-certificates/" + certificate;
                certStream = CaGridActivity.class.getResourceAsStream(certificateResourcePath);
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                // The following should be able to load PKCS #7 certificate chain files
                // as well as ASN.1 DER or PEM-encoded (sequences of) certificates
                Collection<? extends Certificate> chain = cf.generateCertificates(certStream);
                certStream.close();
                // Use only the first cert in the chain - we know there will be only one inside 
                X509Certificate cert = (X509Certificate) chain.iterator().next();
                // Save to Credential Manager's Truststore
                cm.saveTrustedCertificate(cert);
                // Save to the trusted-certificates directory inside cagrid security conf directory
                File certificateFile = new File(trustedCertsDirectory, certificate);
                InputStream certStreamNew = null;
                BufferedOutputStream fOut = null;
                try {
                    // Reload the certificate resource
                    certStreamNew = CaGridActivity.class.getResourceAsStream(certificateResourcePath);
                    fOut = new BufferedOutputStream(new FileOutputStream(certificateFile));
                    IOUtils.copy(certStreamNew, fOut);
                } catch (Exception ex) {
                    String exMessage = "Failed to save caGrid CA's certificate " + certificate
                            + " to cagrid security folder " + certificateFile + " for globus.";
                    logger.error(exMessage, ex);
                } finally {
                    if (fOut != null) {
                        try {
                            fOut.close();
                        } catch (Exception ex) {
                            logger.error("Can't close certificate resource " + certificateFile, ex);
                        }
                    }
                    if (certStreamNew != null) {
                        try {
                            certStreamNew.close();
                        } catch (Exception ex) {
                            logger.error("Can't close certificate resource " + certificate, ex);
                        }
                    }
                }
            } catch (Exception ex) {
                String exMessage = "Failed to load or save caGrid CA's certificate " + certificate
                        + " to Truststore.";
                logger.error(exMessage, ex);
            }
        }
        Writer out = null;
        try {
            out = new BufferedWriter(new FileWriter(caCertsLoadedFile));
            out.write("true"); // just write anything to the file
        } catch (IOException e) {
            // ignore
        }
        if (out != null) {
            try {
                out.close();
            } catch (Exception ex) {
                // ignore
            }
        }
    }
}

From source file:org.hyperledger.fabric.sdk.security.CryptoPrimitives.java

/**
 * Resets curve name, hash algorithm and cert factory. Call this method when a config value changes
 *
 * @throws CryptoException// w w w.j a  va 2 s.c  o  m
 * @throws InvalidArgumentException
 */
private void resetConfiguration() throws CryptoException, InvalidArgumentException {

    setSecurityLevel(securityLevel);

    setHashAlgorithm(hashAlgorithm);

    try {
        cf = CertificateFactory.getInstance(CERTIFICATE_FORMAT);
    } catch (CertificateException e) {
        CryptoException ex = new CryptoException(
                "Cannot initialize " + CERTIFICATE_FORMAT + " certificate factory. Error = " + e.getMessage(),
                e);
        logger.error(ex.getMessage(), ex);
        throw ex;
    }
}

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

private static X509Certificate loadCertificateFromResource(String resourceName) {
    Thread currentThread = Thread.currentThread();
    ClassLoader classLoader = currentThread.getContextClassLoader();
    InputStream certificateInputStream = classLoader.getResourceAsStream(resourceName);
    if (null == certificateInputStream) {
        throw new IllegalArgumentException("could not load certificate resource: " + resourceName);
    }//from   w ww.  j a v a  2 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("certificate factory error: " + e.getMessage(), e);
    }
}

From source file:eu.eidas.auth.engine.SAMLEngineUtils.java

public static Credential getKeyCredential(SAMLEngineModuleI module, KeyInfo keyInfo)
        throws SAMLEngineException {
    Credential credential;//from   ww w.j ava 2 s  .  com
    try {
        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);

        credential = new BasicX509Credential();
        ((BasicX509Credential) credential).setEntityCertificate(cert);
        if (module != null) {
            module.checkCertificateIssuer(cert);
            module.checkCertificateValidityPeriod(cert);
        }
    } catch (CertificateException ce) {
        throw new SAMLEngineException(EIDASErrors.SAML_ENGINE_INVALID_CERTIFICATE.errorCode(),
                EIDASErrors.SAML_ENGINE_INVALID_CERTIFICATE.errorMessage(), ce);
    }
    return credential;
}

From source file:com.vmware.identity.saml.impl.TokenAuthorityImpl.java

/**
 * Create a SignInfo instance with signCertificateChain from samlAuthorityConfig.
 * @param samlAuthorityConfig/*from   www  . j  a va 2s.  c  o m*/
 * @return created SignInfo.
 */
private static SignInfo getSignInfo(SamlAuthorityConfiguration samlAuthorityConfig) {
    List<Certificate> signingCertificateChain = samlAuthorityConfig.getSigningCertificateChain();

    final CertPath certPath;
    try {
        final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        certPath = certificateFactory.generateCertPath(signingCertificateChain);
    } catch (CertificateException e) {
        throw new RuntimeException(e);
    }

    SignInfo signInfo = new SignInfo(samlAuthorityConfig.getAuthorityKey(), certPath, null); // TODO provider

    return signInfo;
}

From source file:org.atricore.idbus.capabilities.sso.support.core.signature.JSR105SamlR2SignerImpl.java

protected X509Certificate getX509Certificate(RoleDescriptorType md) {

    byte[] x509CertificateBin = getBinCertificate(md);
    if (x509CertificateBin == null)
        return null;

    try {//ww w .  j a v  a2 s .  c  o  m
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate x509Cert = (X509Certificate) cf
                .generateCertificate(new ByteArrayInputStream(x509CertificateBin));

        return x509Cert;

    } catch (CertificateException e) {
        logger.error("Cannot get X509 Certificate " + e.getMessage(), e);

    }

    return null;

}

From source file:com.mhise.util.MHISEUtil.java

public static boolean verifyMobiusChain(String path, Context context) {
    try {/*from  w  w  w  .j a  va  2 s. co m*/
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");

        java.security.cert.X509Certificate[] certs = {};
        File file = addBeginEndCertificateTag(context, new File(path), path);
        FileInputStream fis = new FileInputStream(file);
        certs = (X509Certificate[]) certificateFactory.generateCertificates(fis).toArray(certs);
        fis.close();
        boolean flag = false;

        for (int i = 0; i < certs.length; i++) {
            if (certs[i].getIssuerDN().toString().contains("MobiusCA")) {
                flag = true;
            } else {
                flag = false;
            }
        }
        return flag;

    } catch (Exception e) {
        e.printStackTrace();
        Logger.debug("MHISEUtil-->TAG", "Exception path : " + path);
    }

    return false;
}

From source file:com.tremolosecurity.openunison.util.OpenUnisonUtils.java

private static void importMetaData(KeyStore ks, EntityDescriptor ed, IDPSSODescriptor idp,
        AuthMechType currentMechanism, HashMap<String, ParamType> params)
        throws Base64DecodingException, CertificateException, KeyStoreException {
    setProperty("entityID", ed.getEntityID(), params, currentMechanism);
    setProperty("entityID", ed.getEntityID(), params, currentMechanism);

    for (SingleSignOnService sso : idp.getSingleSignOnServices()) {
        if (sso.getBinding().equalsIgnoreCase("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST")) {
            setProperty("idpURL", sso.getLocation(), params, currentMechanism);

        } else if (sso.getBinding().equalsIgnoreCase("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect")) {

            setProperty("idpRedirURL", sso.getLocation(), params, currentMechanism);
        }/*  ww  w. j  av  a 2s  .  c  o  m*/
    }

    for (SingleLogoutService slo : idp.getSingleLogoutServices()) {
        if (slo.getBinding().equalsIgnoreCase("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect")) {

            setProperty("idpRedirLogoutURL", slo.getLocation(), params, currentMechanism);
        }
    }

    for (KeyDescriptor kd : idp.getKeyDescriptors()) {

        if (kd.getUse().equals(UsageType.SIGNING)) {
            String base64 = kd.getKeyInfo().getX509Datas().get(0).getX509Certificates().get(0).getValue();
            String name = "verify-" + ed.getEntityID() + "-idp-sig";

            ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decode(base64));
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            Collection<? extends Certificate> c = cf.generateCertificates(bais);

            if (c.size() > 1) {
                int j = 0;
                Iterator<? extends Certificate> i = c.iterator();
                while (i.hasNext()) {
                    Certificate certificate = (Certificate) i.next();
                    ks.setCertificateEntry(name + "-" + j, certificate);
                }
            } else {
                ks.setCertificateEntry(name, c.iterator().next());
            }

            setProperty("idpSigKeyName", name, params, currentMechanism);

        }

    }
}

From source file:eu.eidas.auth.engine.SAMLEngineUtils.java

/**
 * validates a metadata entitydescriptor's signature against a trustkeystore
 * @param ed//  ww  w .  j  a  va 2 s  . co m
 * @param trustKeyStore
 * @throws SAMLEngineException
 */
public static void validateEntityDescriptorSignature(SignableXMLObject ed, KeyStore trustKeyStore)
        throws SAMLEngineException {
    if (ed == null) {
        throw new SAMLEngineException("invalid entity descriptor");
    }
    try {
        SAMLSignatureProfileValidator sigProfValidator = new SAMLSignatureProfileValidator();
        org.opensaml.xml.signature.Signature signature = ed.getSignature();
        sigProfValidator.validate(signature);
        //check that EntityDescriptor matches the signature
        final KeyInfo keyInfo = ed.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);

        final BasicX509Credential entityX509Cred = new BasicX509Credential();
        entityX509Cred.setEntityCertificate(cert);
        final SignatureValidator sigValidator = new SignatureValidator(entityX509Cred);
        sigValidator.validate(signature);
        if (trustKeyStore != null) {
            SAMLEngineUtils.checkTrust(entityX509Cred, trustKeyStore);
        }
    } catch (ValidationException exc) {
        throw new SAMLEngineException(EIDASErrors.INVALID_SIGNATURE_ALGORITHM.errorCode(), exc);
    } catch (CertificateException exc) {
        throw new SAMLEngineException(EIDASErrors.INVALID_SIGNATURE_ALGORITHM.errorCode(), exc);
    }

}

From source file:com.google.android.gms.common.GooglePlayServicesUtil.java

private static byte[] m107a(PackageInfo packageInfo, byte[]... bArr) {
    try {//  w ww  .  j a  v a 2 s.c  om
        CertificateFactory instance = CertificateFactory.getInstance("X509");
        if (packageInfo.signatures.length != 1) {
            Log.w("GooglePlayServicesUtil", "Package has more than one signature.");
            return null;
        }
        try {
            try {
                ((X509Certificate) instance
                        .generateCertificate(new ByteArrayInputStream(packageInfo.signatures[0].toByteArray())))
                                .checkValidity();
                byte[] toByteArray = packageInfo.signatures[0].toByteArray();
                for (byte[] bArr2 : bArr) {
                    if (Arrays.equals(bArr2, toByteArray)) {
                        return bArr2;
                    }
                }
                if (Log.isLoggable("GooglePlayServicesUtil", 2)) {
                    Log.v("GooglePlayServicesUtil",
                            "Signature not valid.  Found: \n" + Base64.encodeToString(toByteArray, 0));
                }
                return null;
            } catch (CertificateExpiredException e) {
                Log.w("GooglePlayServicesUtil", "Certificate has expired.");
                return null;
            } catch (CertificateNotYetValidException e2) {
                Log.w("GooglePlayServicesUtil", "Certificate is not yet valid.");
                return null;
            }
        } catch (CertificateException e3) {
            Log.w("GooglePlayServicesUtil", "Could not generate certificate.");
            return null;
        }
    } catch (CertificateException e4) {
        Log.w("GooglePlayServicesUtil", "Could not get certificate instance.");
        return null;
    }
}