print Key Hash by SHA - Android java.security

Android examples for java.security:Sha

Description

print Key Hash by SHA

Demo Code


//package com.java2s;
import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.util.Base64;
import android.util.Log;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    public static String printKeyHash(Activity context) {
        PackageInfo packageInfo;/*from   w  w w.jav a 2 s. c om*/
        String key = null;
        try {
            //getting application package name, as defined in manifest
            String packageName = context.getApplicationContext()
                    .getPackageName();

            //Retriving package info
            packageInfo = context.getPackageManager().getPackageInfo(
                    packageName, PackageManager.GET_SIGNATURES);


            for (Signature signature : packageInfo.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                key = new String(Base64.encode(md.digest(), 0));

                // String key = new String(Base64.encodeBytes(md.digest()));
                Log.d("evan", "Key Hash=" + key);
            }
        } catch (PackageManager.NameNotFoundException e1) {
            Log.e("Name not found", e1.toString());
        } catch (NoSuchAlgorithmException e) {
            Log.e("No such an algorithm", e.toString());
        } catch (Exception e) {
            Log.e("Exception", e.toString());
        }

        return key;
    }
}

Related Tutorials