Java tutorial
//package com.java2s; /* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.File; import java.io.IOException; import java.io.InputStream; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarFile; public class Main { private static final String RSA = ".rsa"; private static final String DSA = ".dsa"; /** * Iterates over APK (jar entries) to populate * * @param projectFile * @return * @throws IOException * @throws CertificateException */ public static List<Certificate> populateCertificate(File projectFile) throws IOException, CertificateException { List<Certificate> certList = new ArrayList<Certificate>(); JarFile jar = new JarFile(projectFile); Enumeration<JarEntry> jarEntries = jar.entries(); while (jarEntries.hasMoreElements()) { JarEntry entry = jarEntries.nextElement(); if (entry.getName().toLowerCase().contains(DSA) || entry.getName().toLowerCase().contains(RSA)) { certList.addAll(extractCertificate(jar, entry)); } } return certList; } /** * Extracts certificate from APK * * @param jar * @param entry * rsa or dsa jar item * @return * @throws IOException * I/O problem to read jar * @throws CertificateException * certificate has problems */ private static List<Certificate> extractCertificate(JarFile jar, JarEntry entry) throws IOException, CertificateException { List<Certificate> certList = new ArrayList<Certificate>(); InputStream inStream = null; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); inStream = jar.getInputStream(entry); Collection<? extends Certificate> c = cf.generateCertificates(inStream); Iterator<? extends Certificate> i = c.iterator(); while (i.hasNext()) { Certificate cert = i.next(); certList.add(cert); } } finally { if (inStream != null) { inStream.close(); } } return certList; } }