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:at.asitplus.regkassen.core.base.util.CashBoxUtils.java

/**
 * extract certificates from DEP Export Format String representation
 *
 * @param base64EncodedCertificate BASE64 encoded DER-encoded-certificate
 * @return java object for X509Certificate
 * @throws CertificateException//from   ww  w. j  a v a 2 s . com
 */
public static X509Certificate parseCertificate(String base64EncodedCertificate) throws CertificateException {
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    ByteArrayInputStream bIn = new ByteArrayInputStream(
            CashBoxUtils.base64Decode(base64EncodedCertificate, false));
    return (X509Certificate) certificateFactory.generateCertificate(bIn);
}

From source file:com.jrummyapps.busybox.signing.ZipSigner.java

private static X509Certificate readPublicKey(InputStream file) throws IOException, GeneralSecurityException {
    try {/* w  w w  . j ava  2s.  c o  m*/
        return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(file);
    } finally {
        file.close();
    }
}

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

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
// Step 3 for android 4.0 - 4.2
private void installClientCertificate() {
    try {//from  ww w  .  j a v a 2 s  .  c om
        updateStatus("Inputting client certificate.");

        // Parse the certificate that we got from the server
        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
        InputStream in = new ByteArrayInputStream(
                Base64.decode(certificate.replaceAll("-----(BEGIN|END) CERTIFICATE-----", "")));
        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in);

        client_cert_name = ssid + " " + INT_CLIENT_CERT_NAME;

        // Create a pkcs12 certificate/private key combination
        Security.addProvider(new BouncyCastleProvider());
        KeyStore keystore = KeyStore.getInstance("PKCS12", "BC");
        keystore.load(null, null);
        Certificate chain[] = new Certificate[] { (Certificate) cert };
        keystore.setKeyEntry(client_cert_name, csr.getPrivate(), null, chain);

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        keystore.store(out, ssid.toCharArray());
        out.flush();
        byte[] buffer = out.toByteArray();
        out.close();

        // Install the private key/client certificate combination
        Intent intent = KeyChain.createInstallIntent();
        intent.putExtra(KeyChain.EXTRA_NAME, ssid + " " + INT_CLIENT_CERT_NAME);
        intent.putExtra(KeyChain.EXTRA_PKCS12, buffer);
        startActivityForResult(intent, 3);
    } catch (CertificateException e) {
        e.printStackTrace();
        throw new RuntimeException("Certificate error.");
    } catch (KeyStoreException e) {
        e.printStackTrace();
        System.out.println(e.getMessage());
        throw new RuntimeException("Certificate error: KeyStore");
    } catch (NoSuchProviderException e) {
        e.printStackTrace();
        throw new RuntimeException("Certificate error: Provider");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        throw new RuntimeException("Certificate error: Algorithm");
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException("Certificate error: IO");
    }
}

From source file:org.jenkins_ci.update_center.Main.java

/**
 * Loads a certificate chain and makes sure it's valid.
 *///from www.  ja va 2 s .  c  om
protected List<X509Certificate> getCertificateChain() throws IOException, GeneralSecurityException {
    CertificateFactory cf = CertificateFactory.getInstance("X509");
    List<X509Certificate> certs = new ArrayList<X509Certificate>();
    for (File f : certificates) {
        certs.add(loadCertificate(cf, f));
    }

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

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

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

private BasicX509Credential getKeyInfoCredential(KeyInfo keyInfo) throws CertificateException {
    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);
    return entityX509Cred;
}

From source file:hk.hku.cecid.ebms.admin.listener.PartnershipPageletAdaptor.java

private void getCertificateForPartnership(byte[] cert, PropertyTree dom, String prefix) {
    if (cert != null) {
        try {//www  .  ja  v a2s  . c  om
            ByteArrayInputStream bais = new ByteArrayInputStream(cert);
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509Certificate verifyCert = (X509Certificate) cf.generateCertificate(bais);
            bais.close();
            dom.setProperty(prefix + "issuer", verifyCert.getIssuerDN().getName());
            dom.setProperty(prefix + "subject", verifyCert.getSubjectDN().getName());
            dom.setProperty(prefix + "thumbprint", getCertFingerPrint(verifyCert));
            dom.setProperty(prefix + "valid-from", StringUtilities.toGMTString(verifyCert.getNotBefore()));
            dom.setProperty(prefix + "valid-to", StringUtilities.toGMTString(verifyCert.getNotAfter()));
        } catch (Exception e) {
            dom.setProperty(prefix + "Error", e.toString());
        }
    } else {
        dom.setProperty(prefix, "");
    }
}

From source file:com.owncloud.android.utils.EncryptionUtils.java

/**
 * Encrypt string with RSA algorithm, ECB mode, OAEPWithSHA-256AndMGF1 padding
 * Asymmetric encryption, with private and public key
 *
 * @param string String to encrypt/*from w w  w .  j  a  v  a 2 s  . co m*/
 * @param cert   contains public key in it
 * @return encrypted string
 */
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public static String encryptStringAsymmetric(String string, String cert)
        throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException,
        IllegalBlockSizeException, IOException, CertificateException {

    Cipher cipher = Cipher.getInstance(RSA_CIPHER);

    String trimmedCert = cert.replace("-----BEGIN CERTIFICATE-----\n", "")
            .replace("-----END CERTIFICATE-----\n", "");
    byte[] encodedCert = trimmedCert.getBytes("UTF-8");
    byte[] decodedCert = org.apache.commons.codec.binary.Base64.decodeBase64(encodedCert);

    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    InputStream in = new ByteArrayInputStream(decodedCert);
    X509Certificate certificate = (X509Certificate) certFactory.generateCertificate(in);
    PublicKey realPublicKey = certificate.getPublicKey();

    cipher.init(Cipher.ENCRYPT_MODE, realPublicKey);

    byte[] bytes = encodeStringToBase64Bytes(string);
    byte[] cryptedBytes = cipher.doFinal(bytes);

    return encodeBytesToBase64String(cryptedBytes);
}

From source file:io.fabric8.kubernetes.api.KubernetesFactory.java

private void configureClientCert(WebClient webClient) {
    try (InputStream certInputStream = getInputStreamFromDataOrFile(clientCertData, clientCertFile)) {
        CertificateFactory certFactory = CertificateFactory.getInstance("X509");
        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(certInputStream);

        InputStream keyInputStream = getInputStreamFromDataOrFile(clientKeyData, clientKeyFile);
        PEMReader reader = new PEMReader(keyInputStream);
        RSAPrivateCrtKeySpec keySpec = new PKCS1EncodedKeySpec(reader.getDerBytes()).getKeySpec();
        KeyFactory kf = KeyFactory.getInstance(clientKeyAlgo);
        RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(keySpec);

        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(null);//from  w w  w. j a  va 2 s  .c o  m

        String alias = cert.getSubjectX500Principal().getName();
        keyStore.setKeyEntry(alias, privKey, clientKeyPassword, new Certificate[] { cert });

        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, clientKeyPassword);

        HTTPConduit conduit = WebClient.getConfig(webClient).getHttpConduit();

        TLSClientParameters params = conduit.getTlsClientParameters();

        if (params == null) {
            params = new TLSClientParameters();
            conduit.setTlsClientParameters(params);
        }

        KeyManager[] existingKeyManagers = params.getKeyManagers();
        KeyManager[] keyManagers;

        if (existingKeyManagers == null || ArrayUtils.isEmpty(existingKeyManagers)) {
            keyManagers = keyManagerFactory.getKeyManagers();
        } else {
            keyManagers = (KeyManager[]) ArrayUtils.addAll(existingKeyManagers,
                    keyManagerFactory.getKeyManagers());
        }

        params.setKeyManagers(keyManagers);

    } catch (Exception e) {
        log.error("Could not create key manager for " + clientCertFile + " (" + clientKeyFile + ")", e);
    }
}

From source file:com.corebase.android.framework.http.client.AsyncHttpClient.java

/**
 * ?SSLSocketFactory?https?/*from   w w  w.ja  va2  s. c o m*/
 * 
 * @return
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws UnrecoverableKeyException
 * @throws KeyManagementException
 */
private CustomSSLSocketFactory initCustomSSLSocketFactory()
        throws KeyStoreException, KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException {

    KeyStore keyStore = null;
    try {
        InputStream ins = context.getAssets().open("app_pay.cer"); // ?assets
        if (ins != null) {
            CertificateFactory cerFactory = CertificateFactory.getInstance("X.509");
            Certificate cer = cerFactory.generateCertificate(ins);
            keyStore = KeyStore.getInstance("PKCS12", "BC");
            keyStore.load(null, null);
            keyStore.setCertificateEntry("trust", cer);
        } else {
            keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null, null);
        }
        CustomSSLSocketFactory customSSLSocketFactory = new CustomSSLSocketFactory(keyStore);
        customSSLSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        return customSSLSocketFactory;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.cloudbees.jenkins.plugins.enterpriseplugins.CloudBeesUpdateSite.java

static X509Certificate loadLicenseCaCertificate() throws CertificateException {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    InputStream stream = CloudBeesUpdateSite.class.getResourceAsStream("/cloudbees-root-cacert.pem");
    try {/*from   ww w. j av a 2s . c  om*/
        return stream != null ? (X509Certificate) cf.generateCertificate(stream) : null;
    } finally {
        IOUtils.closeQuietly(stream);
    }
}