get Certificate By Name - Android java.security

Android examples for java.security:Certificate

Description

get Certificate By Name

Demo Code


//package com.java2s;
import android.util.Log;
import java.security.KeyStore;
import java.security.cert.X509Certificate;

import java.util.Enumeration;

public class Main {
    private static final String TAG = "Certificate";

    public static X509Certificate getCertificateByName(
            String certificateName) {
        X509Certificate certificate = null;

        try {//from   ww  w . j a  v  a2s  . c om

            KeyStore ks = KeyStore.getInstance("AndroidCAStore");
            ks.load(null, null);
            Enumeration aliases = ks.aliases();
            while (aliases.hasMoreElements()) {
                String alias = (String) aliases.nextElement();
                X509Certificate cert = (X509Certificate) ks
                        .getCertificate(alias);
                Log.d(TAG, "Subject DN: " + cert.getSubjectDN().getName());
                Log.d(TAG, "Subject SN: "
                        + cert.getSerialNumber().toString());
                Log.d(TAG, "Issuer DN: " + cert.getIssuerDN().getName());

                String name = parseName(cert.getIssuerDN().getName());

                if (name.equals(certificateName)) {
                    certificate = cert;
                    break;
                }
            }

        } catch (Exception s) {
            Log.e("Error", s.getMessage());
            return null;
        }

        finally {

            return certificate;
        }
    }

    private static String parseName(String certName) {
        String certificateName = "";
        try {

            String[] splitted = certName.split(",");

            if (splitted != null && splitted.length > 0) {
                for (String current : splitted) {
                    if (current.startsWith("CN")
                            || current.startsWith("OU")
                            || current.startsWith("O")) {
                        certificateName = (current.split("=")[1]);
                    }
                }
            }

        } catch (Exception s) {
            Log.e("Error", s.getMessage());

        }

        finally {

            return certificateName;
        }

    }
}

Related Tutorials