[android] Android Facebook integration with invalid key hash

In one of my apps I need to get data from Facebook... I am doing this:

I have created app ID. It logs in successfully, but after logging out, I log in, and then it gives me:

Screenshot of invalid key hash error Facebook

What is wrong I am doing? I am using the Facebook SDK... I have installed Facebook on my phone... It is running well within an emulator, but that does not have the inbuilt Facebook application installed.

This is my code:

if (FB_APP_ID == null) {
    Builder alertBuilder = new Builder(this);
    alertBuilder.setTitle("Warning");
    alertBuilder.setMessage("A Facebook Applicaton ID must be " +
                            "specified before running this example: see App.java");
    alertBuilder.create().show();
}

// Initialize the dispatcher
Dispatcher dispatcher = new Dispatcher(this);
dispatcher.addHandler("login", LoginHandler.class);
dispatcher.addHandler("stream", StreamHandler.class);
dispatcher.addHandler("logout", LogoutHandler.class);

// If a session already exists, render the stream page
// immediately. Otherwise, render the login page.
Session session = Session.restore(this);
if (session != null) {
    dispatcher.runHandler("stream");
}
else {
    dispatcher.runHandler("login");
}

This question is related to android facebook

The answer is


Use the below code in the onCreate() method of your activity:

try {
    PackageInfo info = getPackageManager().getPackageInfo(
                           "your application package name",
                           PackageManager.GET_SIGNATURES);
    for (Signature signature : info.signatures) {
        MessageDigest md = MessageDigest.getInstance("SHA");
        md.update(signature.toByteArray());
        Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
    }
}
catch (NameNotFoundException e) {
}
catch (NoSuchAlgorithmException e) {
}

Run this code. This will generate the hash key. Copy this KeyHash in the Facebook application setting, and save changes. Then log into your application. This will work perfectly in the future too.


I experienced the same problem. I made a short research on the possible reasons for this strange behavior and I found the following:

  • During the first execution of a new Facebook app, it will allow connection/login even if you don't specify any key hashes.

  • For me, the tutorial which Facebook provided didn't generate the correct key hash, because it was giving the wrong configuration. When executing:

    keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore | openssl sha1 -binary | openssl
    base64
    

make sure you check all properties - the HOMEPATH, the existence of the keystore, etc. Maybe you also have to provide password.

  • What generated the proper configuration was the solution suggested by @Mahendran.

  • Also, if you see the error originally posted (http://i.stack.imgur.com/58q3v.png), most probably the key hash you see on the screen is your real one. If nothing else works, try inputting it in Facebook.

I got all those results with: Windows 7 64-bit edition, Android Studio 1.2.2, JDK 7.


If you are using Google Play App signing:

Open the App signing section in Google Play Console, and get the SHA-1 hash under App signing certificate. Then convert it to Base64, for example with this tool: Hexadecimal -> base64 string decoder

Console screenshot

Convert to Base64 screenshot


If you are typing the keyhash manually (for example from mobile to the Facebook Dashboard), make sure to differentiate between small L and capital I.


After so many trials I stumbled on a solution to this. I generated and added both debug and release keys to the Facebook developer console and still got the error.

The only solution that worked for me was is to uninstall the OpenSSL program from Google and download from Win32/Win64 OpenSSL Installer for Windows

It really works like magic.


The generated hash key is wrong. You may get the hash key using two steps.

One is through a command prompt. Another one is through coding. The hash key through a command prompt is working on the first time only. I don't know the reason. I have also got the same problem. So I tried it through programmatically.

Follow these steps:

Paste the following code in oncreate().

try {
    PackageInfo info = getPackageManager().getPackageInfo(
                           "com.example.packagename",
                           PackageManager.GET_SIGNATURES);
    for (Signature signature : info.signatures) {
        MessageDigest md = MessageDigest.getInstance("SHA");
        md.update(signature.toByteArray());
        Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
    }
}
catch (NameNotFoundException e) {
}
catch (NoSuchAlgorithmException e) {
}

Modify "com.example.packagename" with your package name in the above coding without fail (you may find your package name in the Android manifest file).

Run your application. Go to the activity where you pasted the above code. In the LogCat file, search for "KeyHash". You may find a key hash. Copy the key hash and go to Facebook application dashboard page. Go to settings and enter the details like in the below image.

Enter image description here

Once you finished the above step, relaunch the app again. You may now log into Facebook. For more details about key hash, check the link.

If you add wrong information in the settings page, it means it will give some error. So use the correct information there. And also if the public (other than you) need to use your application means you need to enable the permission (change "yes" in the "Status & Review" next to the setting).


According Facebook Login for Android, you must provide the key hash value. In order to obtain it, you will need the key used to sign your application.

keytool \
    -exportcert \
    -alias YourKeyAlias \
    -storepass YourStoreKeyPassword \
    -keystore PathToYourKeyStoreFile | openssl sha1 -binary | openssl base64

I got the same problem. I was sure that it was due to very small fault and yes it was!

I found the solution:

When generating the debug hash key in my computer, I entered the password of my system. But the password should be the following -

Enter keystore password: "android". This was the only problem in my case.

----- For generating Debug key hash, use this command -

keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64

Enter keystore password: 'android'

----- To Generate Release key hash, use this command -

keytool -exportcert -alias "alias of keystore" -keystore "Your path to the keystore when signing app" | openssl sha1 -binary | openssl base64

Provide your keystore password after executing this command.


I was having the same problem. First log in, just fine, but then, an invalid key hash.

The Facebook SDK for Unity gets the wrong key hash. It gets the key from "C:\Users\"your user".android\debug.keystore" and, in a perfect world, it should get it from the keystore you created in your project. That's why it is telling you that the key hash is not registered.

As suggested by Madi, you can follow the steps on this link to find the right key. Just make sure to point them to the keystore inside your project. Otherwise you won't get the right key.


This is how I solved this problem:

First you have to get the SHA-1 value. For that there are two ways.

To get the SHA-1 value in Android Studio.

  1. Click Gradle
  2. Click Signing Report
  3. Copy the SHA-1 value

OR

To get the SHA-1 value from the keystore file.

keytool -list -v -keystore keystore_file_name.jks -alias key0

Copy the SHA-1 value to your clipboard like this:

CD:A1:EA:A3:5C:5C:68:FB:FA:0A:6B:E5:5A:72:64:DD:26:8D:44:84

And open Hexadecimal -> Base64 string decoder to convert your SHA-1 value to Base64.

This is what Facebook requires.

Get the generated hash " ********************= " and copy the key hash to the Facebook app.


I had the same problem.

Make sure that you build the APK file with the same device that generated the hashkey which is stored on in the Facebook developers section.


If you're generating release key hashes, make sure you enter the actual password of your keystore and not "android".

This was my issue. Debug release was working, but the release APK was not.


After a long research, we found a solution.

We had set permissions as:

loginButton.setReadPermissions(public_profile email);

This worked for the first time, but when we re-logged in to Facebook, it gave the Invalid Hash Error.

The simple solution was to change the above line to:

loginButton.setReadPermissions(Arrays.asList("public_profile", "email"));

And it worked like a bliss!

Facebook should return the correct exception instead of the misleading invalid hash key error.


Here are a lot of right answers. Just one thing:

Paste the received hash into ApplicationSettingsMain, not via the fast start tutorial.


I had the same problem when I was debugging my app. I've rewrote the hash that you have crossed out in the attached image (the one that Facebook says is invalid) and added it in the Facebook's developers console to key hashes. Just be careful of typos.

This solution is more like an easy workaround than a proper solution.


I fixed this by adding the following into MainApplication.onCreate:

try {
    PackageInfo info = getPackageManager().getPackageInfo(
                           "com.genolingo.genolingo",
                           PackageManager.GET_SIGNATURES);

    for (Signature signature : info.signatures) {
        MessageDigest md = MessageDigest.getInstance("SHA");
        md.update(signature.toByteArray());
        String hash = Base64.encodeToString(md.digest(), Base64.DEFAULT);
        KeyHash.addKeyHash(hash);
    }
}
catch (PackageManager.NameNotFoundException e) {
    Log.e("PackageInfoError:", "NameNotFoundException");
}
catch (NoSuchAlgorithmException e) {
    Log.e("PackageInfoError:", "NoSuchAlgorithmException");
}

I then uploaded this to the Google developer console and then downloaded the derived APK which, for whatever reason, has a totally different key hash.

I then used LogCat to determine the new key hash and added it Facebook as other users have outlined.


I tried all of the previous answers and nothing helped my case with my clients!

Then my client remembered he had the Facebook App installed on his device. After he removed it. the login worked perfectly.

The hashkey had been changed, and I've replaced the old hash keys at Facebook Developers Console with the key from the error (as suggested above), and it works!

The Facebook App itself might be the issue, so you better figure this out on a device with the Facebook app installed and on a device with the Facebook app not installed and handle both cases...


If you are facing this problem then put this key into your developer.facebook.com:

Enter image description here

Then make sure your app is live on developer.facebook.com.

This green circle is indicating the app is live:

Enter image description here

If it is not then follow these two steps for make your app live:

Step 1 Go to your application→settingadd Contact Email and apply Save Changes.

Step 2 Go to the App Review option and make sure this toggle is Yes. I added a screenshot:

Enter image description here

Note: If you want to copy the hashkey, check the BlueServiceQueue in LogCat.


The following code will give you your hash for Facebook, but you have to follow these steps in order to get the release candidate hash.

  1. Copy and paste this code in your main activity

    try {
        PackageInfo info = getPackageManager().getPackageInfo(
                               "com.example.packagename",
                               PackageManager.GET_SIGNATURES);
        for (Signature signature : info.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
        }
    }
    catch (NameNotFoundException e) {
    }
    catch (NoSuchAlgorithmException e) {
    }
    
  2. Generate a signed APK file.

  3. Connect your phone to a laptop and make sure it stays connected.
  4. Install and run the APK file in your phone by manually moving the release APK to your phone.
  5. Now look at Android LogCat (use filter KeyHash:). You should see your release hash key for Facebook. Simply copy and paste it in your https://developers.facebook.com/apps. It's under settings.
  6. Now you can test the app it should work perfectly well.

You must create two key hashes, one for Debug and one for Release.

For the Debug key hash:

On OS X, run:

keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64

On Windows, run:

keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore | openssl sha1 -binary | openssl
base64

Debug key hashes source

For the Release key hash:

On OS X, run (replace what is between <> with your values):

keytool -exportcert -alias <RELEASE_KEY_ALIAS> -keystore <RELEASE_KEY_PATH> | openssl sha1 -binary | openssl base64

On Windows, use (replace what is between <> with your values):

keytool -exportcert -alias <RELEASE_KEY_ALIAS> -keystore <RELEASE_KEY_PATH> | openssl sha1 -binary | openssl base64

Release key hashes source


try {
    PackageInfo info = getPackageManager().getPackageInfo(
                           "www.icognix.infomedia",
                           PackageManager.GET_SIGNATURES);
    for (Signature signature : info.signatures) {
        MessageDigest md = MessageDigest.getInstance("SHA");
        md.update(signature.toByteArray());
        Log.d("YourKeyHash: ", Base64.encodeToString(md.digest(), Base64.DEFAULT));
        Log.d("YourKeyHash: ", Base64.encodeToString(md.digest(), Base64.DEFAULT));
    }
}
catch (PackageManager.NameNotFoundException e) {
}
catch (NoSuchAlgorithmException e) {
}

What Facebook used is not the default password and alias for debug. You need to change it following and it will work.

/usr/lib/jvm/jdk1.8.0_66/bin/keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64

If you have not changed anything with the default password it should be "android".

You can also configure it in the build.gradle file. But the same alias password should be used for generating the hash:

android {
    signingConfigs {
        release {
            storeFile file("~/.android/debug.keystore")
            storePassword "android"
            keyAlias "androiddebugkey"
            keyPassword "android"
        }
    }
}

Even though this question has been answered in alot of helpful ways I just wanted to add that when I followed Rafal Maleks answer (using the hash keys on Google Play Console) I was NOT able to use the App Signing SHA1 key, still got the generic error from Facebook. Instead I needed to use the SHA-1 certificate fingerprint from the Upload Certificate part (just below the App Signing part on Google Play Console). Same process otherwise;

  1. Copy the SHA-1 certificate fingerprint from Upload Certificate section in Google Play Console

  2. Convert the SHA-1 using: http://tomeko.net/online_tools/hex_to_base64.php and copy the output (base64)

  3. Paste it into the Key Hashes input on developer.facebook.com and save changes.

Hopefully this answer isn't to redundant and will help someone that can't get it to work with the App Signing certificate.

Now Facebook login works in my app both in debug and release mode.


Paste the following code into your OnCreate method:

try {
    PackageInfo info = getPackageManager().getPackageInfo(
                           "com.example.packagename",
                           PackageManager.GET_SIGNATURES);
    for (Signature signature : info.signatures) {
        MessageDigest md = MessageDigest.getInstance("SHA");
        md.update(signature.toByteArray());
        Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
    }
}
catch (NameNotFoundException e) {
    e.printStackTrace();
}
catch (NoSuchAlgorithmException e) {
    e.printStackTrace();
}

Just modify the package name. Then go to your LogCat file and select Debug search here. Then you will find the hash key. Now copy this hash key and then go to the developer.facebook.app_id site, edit your hash key, and press Save. Now run your Android project again. I think issue will be resolved.


This may help someone with the same problem.

  1. Generate the key hash using the below code

    keytool -exportcert -alias <your_keystore> alias -keystore <your_keystore_file> | openssl sha1 -binary | openssl base64
    

    How to use keytool

  2. Paste it in required field in Facebook developer

  3. In Android Studio, menu FileProject Structure

    Enter image description here

    Add signing parameters.

  4. Select flavors

    Enter image description here

    Select the signing configuration we created.

  5. Select build type

    Enter image description here

  6. Select build variant and build it

    Enter image description here