Mahmoud Gamal Mahmoud Gamal - 3 months ago 28
Android Question

Facebook api key hash

Why we use Key hash when developing Facebook Api (Login with facebook) in android ?
i need a lot of information about it and i have problem to get the key hash

1- from Android code i can't find key hash in logcat.

2- from CMD i get the key hash constant at every time.

Answer

//Generate Hash Key

public static String printKeyHash(Activity context) {
PackageInfo packageInfo;
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);

    Log.e("Package Name=", context.getApplicationContext().getPackageName());

    for (android.content.pm.Signature signature : packageInfo.signatures) {
        MessageDigest md = MessageDigest.getInstance("SHA");
        md.update(signature.toByteArray());
        key = new String(Base64.encode(md.digest(), 0));
Toast.makeText(context, key, Toast.LENGTH_SHORT).show();
        // String key = new String(Base64.encodeBytes(md.digest()));
        Log.e("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;
}