Get the SHA1 fingerprint for the certificate - Android java.security

Android examples for java.security:Certificate

Description

Get the SHA1 fingerprint for the certificate

Demo Code


//package com.java2s;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

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

public class Main {
    /**//from  w w  w  .  ja v a 2  s  . com
     * Get the SHA1 fingerprint for the cetificate
     * 
     * @param pm
     *            {@link PackageManager} package Manager
     * @param pn
     *            {@link String} package name
     * @return
     */
    public static String getSHA1Fingerprint(PackageManager pm, String pn) {
        String fingerprintSHA1 = null;
        byte[] cert = getCert(pm, pn);

        try {
            MessageDigest md = MessageDigest.getInstance("SHA1");

            byte[] sha1digest = new byte[0];
            if (md != null) {
                sha1digest = md.digest(cert);
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < sha1digest.length; ++i) {
                    sb.append((Integer
                            .toHexString((sha1digest[i] & 0xFF) | 0x100))
                            .substring(1, 3));
                }
                fingerprintSHA1 = sb.toString();
            }

        } catch (NoSuchAlgorithmException e1) {
            e1.printStackTrace();
        }

        return fingerprintSHA1;
    }

    /**
     * Get certificate in bytes
     * 
     * @param pm
     * @param pn
     * @return
     */
    private static byte[] getCert(PackageManager pm, String pn) {

        int flags = PackageManager.GET_SIGNATURES;

        PackageInfo packageInfo = null;
        byte[] cert = null;
        try {
            packageInfo = pm.getPackageInfo(pn, flags);
            Signature[] signatures = packageInfo.signatures;
            cert = signatures[0].toByteArray();

        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }

        return cert;
    }
}

Related Tutorials