Android 讀取APK簽名資訊

來源:互聯網
上載者:User
某些時候需要擷取某個特定的apk(已安裝或者未安裝)的簽名資訊,如程式自檢測,可信賴的第三方檢測(應用市場),系統限定安裝對此,有兩種實現方法可以使用Java內建的API(主要用到的為JarFile,JarEntry,Certificate)進行擷取,還有一種方法是使用系統隱藏的API PackageParser,通過反射來使用對應的API.但是由於安卓系統的分裂版本過多,並且不同廠商進行的修改很多,依賴反射隱藏API的方法並不能保證相容性和通用性,因此推薦使用JAVA內建API進行擷取:    /**     * 從APK中讀取簽名     * @param file     * @return     * @throws IOException     */    private static List<String> getSignaturesFromApk(File file) throws IOException {        List<String> signatures=new ArrayList<String>();        JarFile jarFile=new JarFile(file);        try {            JarEntry je=jarFile.getJarEntry("AndroidManifest.xml");            byte[] readBuffer=new byte[8192];            Certificate[] certs=loadCertificates(jarFile, je, readBuffer);            if(certs != null) {                for(Certificate c: certs) {                    String sig=toCharsString(c.getEncoded());                    signatures.add(sig);                }            }        } catch(Exception ex) {        }        return signatures;    }

    /**     * 載入簽名     * @param jarFile     * @param je     * @param readBuffer     * @return     */    private static Certificate[] loadCertificates(JarFile jarFile, JarEntry je, byte[] readBuffer) {        try {            InputStream is=jarFile.getInputStream(je);            while(is.read(readBuffer, 0, readBuffer.length) != -1) {            }            is.close();            return je != null ? je.getCertificates() : null;        } catch(IOException e) {        }        return null;    }/**     * 將簽名轉成轉成可見字串     * @param sigBytes     * @return     */    private static String toCharsString(byte[] sigBytes) {        byte[] sig=sigBytes;        final int N=sig.length;        final int N2=N * 2;        char[] text=new char[N2];        for(int j=0; j < N; j++) {            byte v=sig[j];            int d=(v >> 4) & 0xf;            text[j * 2]=(char)(d >= 10 ? ('a' + d - 10) : ('0' + d));            d=v & 0xf;            text[j * 2 + 1]=(char)(d >= 10 ? ('a' + d - 10) : ('0' + d));        }        return new String(text);    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.