Monday, 28 July 2014

Generating Facebook Key Hash

package com.ram.facebookkeyhash;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import com.ram.demo1.R;
import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;

public class MainActivity extends Activity
{
    // Declare your application package name
    String packageName = "your application package name";

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        try
        {
            // Overall information about the contents of a package. This
            // corresponds to all of the information collected from
            // AndroidManifest.xml.
            PackageInfo packageInfo = getPackageManager().getPackageInfo(packageName,
                    PackageManager.GET_SIGNATURES);

            // Array of all signatures read from the package file. This is only
            // filled in if the flag GET_SIGNATURES was set.
            for (Signature signature : packageInfo.signatures)
            {
                // The basic pattern to digest an InputStream
                MessageDigest md = MessageDigest.getInstance("SHA");
                // The basic pattern to digest an InputStream
                md.update(signature.toByteArray());
                // Prints key hash in logcat
                Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }

        } catch (NameNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}