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:eu.eidas.auth.engine.core.impl.SignSW.java

private X509Certificate getSignatureCertificate(final Signature signature) throws SAMLEngineException {
    try {/*from  w w  w. j  av  a  2 s. c om*/
        final KeyInfo keyInfo = signature.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);
        return cert;
    } catch (GeneralSecurityException e) {
        LOG.debug("ERROR : GeneralSecurityException.", e);
        LOG.warn("ERROR : GeneralSecurityException.", e.getMessage());
        throw new SAMLEngineException(e);
    }
}

From source file:com.hpe.elderberry.TaxiiConnection.java

private List<Certificate> addPemsToStore(KeyStore store, List<String> pems) throws CertificateException {
    List<Certificate> result = new ArrayList<>(pems.size());

    CertificateFactory factory = CertificateFactory.getInstance("X.509");
    pems.forEach(pem -> {//  w  w  w. ja  v  a2s .  co m
        try {
            X509Certificate cert = (X509Certificate) factory.generateCertificate(toInputStream(pem));
            store.setCertificateEntry(randomUUID().toString(), cert);
            result.add(cert);
        } catch (Exception e) {
            throw new RuntimeException("unable to load PEM: " + pem + ", " + e.getMessage(), e);
        }
    });

    return result;
}

From source file:org.opendaylight.aaa.cert.impl.ODLMdsalKeyTool.java

private X509Certificate getCertificate(String certificate) {
    if (certificate.isEmpty()) {
        return null;
    }//from ww w . j  a  va2s .  c o m

    if (certificate.contains(KeyStoreConstant.BEGIN_CERTIFICATE)) {
        final int fIdx = certificate.indexOf(KeyStoreConstant.BEGIN_CERTIFICATE)
                + KeyStoreConstant.BEGIN_CERTIFICATE.length();
        final int sIdx = certificate.indexOf(KeyStoreConstant.END_CERTIFICATE);
        certificate = certificate.substring(fIdx, sIdx);
    }
    final byte[] byteCert = Base64.decodeBase64(certificate);
    final InputStream inputStreamCert = new ByteArrayInputStream(byteCert);
    CertificateFactory certFactory;
    try {
        certFactory = CertificateFactory.getInstance("X.509");
        final X509Certificate newCert = (X509Certificate) certFactory.generateCertificate(inputStreamCert);
        newCert.checkValidity();
        return newCert;
    } catch (final CertificateException e) {
        LOG.error("Failed to get certificate", e);
        return null;
    }
}

From source file:org.eclipse.emf.emfstore.internal.client.model.connectionmanager.KeyStoreManager.java

/**
 * {@inheritDoc}// w  w  w .jav  a 2 s . c om
 * 
 * @see org.eclipse.emf.emfstore.client.provider.ESKeyStoreManager#addCertificate(java.lang.String,
 *      java.io.InputStream)
 */
public void addCertificate(String alias, InputStream certificate) throws ESCertificateException {
    if (!isDefaultCertificate(alias)) {
        loadKeyStore();
        try {
            final CertificateFactory factory = CertificateFactory.getInstance(CERTIFICATE_TYPE);
            final Certificate newCertificate = factory.generateCertificate(certificate);
            keyStore.setCertificateEntry(alias, newCertificate);
            storeKeyStore();
        } catch (final CertificateException e) {
            final String message = Messages.KeyStoreManager_Choose_Valid_Certificate;
            throw new ESCertificateException(message);
        } catch (final KeyStoreException e) {
            final String message = "Storing certificate failed!"; //$NON-NLS-1$
            WorkspaceUtil.logException(message, e);
            throw new ESCertificateException(message, e);
        }
    }
}

From source file:net.sf.keystore_explorer.crypto.x509.X509CertUtil.java

/**
 * Load a CRL from the specified stream.
 *
 * @param is/*from  w  w w  .  jav  a2 s .c  o  m*/
 *            Stream to load CRL from
 * @return The CRL
 * @throws CryptoException
 *             Problem encountered while loading the CRL
 */
public static X509CRL loadCRL(InputStream is) throws CryptoException {
    try {
        CertificateFactory cf = CertificateFactory.getInstance(X509_CERT_TYPE);
        X509CRL crl = (X509CRL) cf.generateCRL(is);
        return crl;
    } catch (CertificateException ex) {
        throw new CryptoException(res.getString("NoLoadCrl.exception.message"), ex);
    } catch (CRLException ex) {
        throw new CryptoException(res.getString("NoLoadCrl.exception.message"), ex);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:org.panlab.tgw.restclient.PtmInfoParser.java

private static void processCertificate(String alias, X509Certificate x509, URL url) {
    try {/*from   www .  j av  a  2s .  c  o  m*/
        String store = System.getProperty("javax.net.ssl.trustStore");
        String password = System.getProperty("javax.net.ssl.trustStorePassword");

        KeyStore keystore = KeyStore.getInstance("JKS");
        keystore.load(new FileInputStream(store), password.toCharArray());

        Enumeration<String> en = keystore.aliases();
        while (en.hasMoreElements()) {
            log.info(en.nextElement());
        }

        if (!keystore.containsAlias(alias)) {
            ByteArrayInputStream bais = new ByteArrayInputStream(x509.getEncoded());
            Certificate cert = CertificateFactory.getInstance("x509").generateCertificate(bais);
            keystore.setCertificateEntry(alias, cert);

            storeNewPTM(alias, url, x509.getSubjectDN().toString().replace(", ", ","));

            en = keystore.aliases();
            while (en.hasMoreElements()) {
                log.info(en.nextElement());
            }
            keystore.store(new FileOutputStream(store), password.toCharArray());

            TrustManagerFactory.getInstance("PKIX").init(keystore);
        }

    } catch (Exception error) {
        log.error(error.getMessage());
    }
}

From source file:net.jmhertlein.mcanalytics.api.auth.SSLUtil.java

public static X509Certificate certFromBase64(String base64) {
    try {//from   w w  w .  j  av a  2s .co m
        return (X509Certificate) CertificateFactory.getInstance("X.509")
                .generateCertificate(new ByteArrayInputStream(Base64.decodeBase64(base64)));
    } catch (CertificateException ex) {
        Logger.getLogger(SSLUtil.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}

From source file:org.linagora.linshare.core.facade.webservice.user.impl.DocumentFacadeImpl.java

@Override
public DocumentDto createWithSignature(File tempFile, String fileName, String description,
        InputStream signatureFile, String signatureFileName, InputStream x509) throws BusinessException {
    Validate.notNull(tempFile, "Missing required file (check parameter named file)");
    User actor = checkAuthentication();/*  w  w  w .j  a va 2 s .  c o m*/
    if ((actor.isGuest() && !actor.getCanUpload()))
        throw new BusinessException(BusinessErrorCode.WEBSERVICE_FORBIDDEN,
                "You are not authorized to use this service");
    DocumentEntry res = documentEntryService.create(actor, actor, tempFile, fileName, description, false, null);
    if (signatureFile != null) {
        X509Certificate x509certificate = null;
        try {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            x509certificate = (X509Certificate) cf.generateCertificate(x509);
        } catch (CertificateException e) {
            throw new BusinessException(BusinessErrorCode.INVALID_INPUT_FOR_X509_CERTIFICATE,
                    "unable to generate a X509 certificate", e);
        }
        signatureService.createSignature(actor, res.getDocument(), signatureFile, signatureFileName,
                x509certificate);
    }

    documentEntryService.updateFileProperties(actor, actor, res.getUuid(), res.getName(), description, null);
    return new DocumentDto(res);
}

From source file:nl.nikhef.eduroam.WiFiEduroam.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
private void applyAndroid43EnterpriseSettings(WifiConfiguration currentConfig,
        HashMap<String, String> configMap) {
    try {/*  ww w.j  ava  2 s . co m*/
        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
        InputStream in = new ByteArrayInputStream(
                Base64.decode(certificate.replaceAll("-----(BEGIN|END) CERTIFICATE-----", "")));
        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in);
        in = new ByteArrayInputStream(Base64.decode(ca.replaceAll("-----(BEGIN|END) CERTIFICATE-----", "")));
        X509Certificate caCert = (X509Certificate) certFactory.generateCertificate(in);

        WifiEnterpriseConfig enterpriseConfig = new WifiEnterpriseConfig();
        enterpriseConfig.setPhase2Method(Phase2.NONE);
        enterpriseConfig.setAnonymousIdentity(configMap.get(INT_ANONYMOUS_IDENTITY));
        enterpriseConfig.setEapMethod(Eap.TLS);

        enterpriseConfig.setCaCertificate(caCert);
        enterpriseConfig.setClientKeyEntry(this.csr.getPrivate(), cert);
        enterpriseConfig.setIdentity(configMap.get(INT_ANONYMOUS_IDENTITY));
        enterpriseConfig.setSubjectMatch(configMap.get(INT_SUBJECT_MATCH));
        currentConfig.enterpriseConfig = enterpriseConfig;

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.indivica.olis.Driver.java

public static String signData2(String data) {
    X509Certificate cert = null;/*w ww .j  ava 2  s .  co m*/
    PrivateKey priv = null;
    KeyStore keystore = null;
    String pwd = OscarProperties.getInstance().getProperty("olis_ssl_keystore_password", "changeit");
    String result = null;
    try {
        Security.addProvider(new BouncyCastleProvider());

        keystore = KeyStore.getInstance("JKS");
        // Load the keystore
        keystore.load(new FileInputStream(OscarProperties.getInstance().getProperty("olis_keystore")),
                pwd.toCharArray());

        //Enumeration e = keystore.aliases();
        String name = "olis";

        // Get the private key and the certificate
        priv = (PrivateKey) keystore.getKey(name, pwd.toCharArray());

        FileInputStream is = new FileInputStream(
                OscarProperties.getInstance().getProperty("olis_returned_cert"));
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        cert = (X509Certificate) cf.generateCertificate(is);

        // I'm not sure if this is necessary

        ArrayList<Certificate> certList = new ArrayList<Certificate>();
        certList.add(cert);

        Store certs = new JcaCertStore(certList);

        // Encrypt data
        CMSSignedDataGenerator sgen = new CMSSignedDataGenerator();

        // What digest algorithm i must use? SHA1? MD5? RSA?...
        ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(priv);
        sgen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
                new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(sha1Signer, cert));

        // I'm not sure this is necessary
        sgen.addCertificates(certs);

        // I think that the 2nd parameter need to be false (detached form)
        CMSSignedData csd = sgen.generate(new CMSProcessableByteArray(data.getBytes()), true);

        byte[] signedData = csd.getEncoded();
        byte[] signedDataB64 = Base64.encode(signedData);

        result = new String(signedDataB64);

    } catch (Exception e) {
        MiscUtils.getLogger().error("Can't sign HL7 message for OLIS", e);
    }
    return result;
}