How to Generate Key Hash for Facebook in Android | Android Breakdown

All Android app makers who is going to implement Facebook login to their app is searching for this blog. Yes, absolutely without any doubt your need will end here. When you register on Facebook developer and follow steps to implement android facebook sdk into your app than there is an field named "Key Hash" which is quite confusing for so many developers to find out that how to generate it ? So Let's start.


Just paste this Code

Yes, just paste this code in your activity or fragment and run your app than you can debug your app to get keyhash. Or you can also search in logs "Key Hash=" by this. That's it !!!

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 (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.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;
}

Comments