get X.509 Certificate From APK - Android java.security

Android examples for java.security:Certificate

Description

get X.509 Certificate From APK

Demo Code


//package com.java2s;

import java.io.ByteArrayInputStream;

import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

import java.util.Iterator;
import java.util.List;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

public class Main {
    public static X509Certificate getCertificateFromAPK(PackageManager pm,
            String pkgName) {/*w w w.  ja v a2  s .  co  m*/
        byte[] signature = null;
        List<PackageInfo> apps = pm
                .getInstalledPackages(PackageManager.GET_SIGNATURES);
        Iterator<PackageInfo> iter = apps.iterator();
        while (iter.hasNext()) {
            PackageInfo info = iter.next();
            String packageName = info.packageName;
            if (packageName.equals(pkgName)) {
                signature = info.signatures[0].toByteArray();
                break;
            }
        }
        if (signature != null) {
            try {
                CertificateFactory certFactory = CertificateFactory
                        .getInstance("X.509");
                X509Certificate cert = (X509Certificate) certFactory
                        .generateCertificate(new ByteArrayInputStream(
                                signature));
                return cert;
            } catch (CertificateException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

Related Tutorials