[java] How to create Android Facebook Key Hash?

I do not understand this process at all. I have been able to navigate to the folder containing the keytool in the Java SDK. Although I keep getting the error openssl not recognised as an internal or external command. The problem is even if I can get this to work, what would I do and with what afterwards?

This question is related to java android facebook

The answer is


Try this answer

https://stackoverflow.com/a/54513168/9236994

with minimal efforts helps to resolve the issue.


There is a short solution too. Just run this in your app:

FacebookSdk.sdkInitialize(getApplicationContext());
Log.d("AppLog", "key:" + FacebookSdk.getApplicationSignature(this));

A longer one that doesn't need FB SDK (based on a solution here) :

public static void printHashKey(Context context) {
    try {
        final PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
        for (android.content.pm.Signature signature : info.signatures) {
            final MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            final String hashKey = new String(Base64.encode(md.digest(), 0));
            Log.i("AppLog", "key:" + hashKey + "=");
        }
    } catch (Exception e) {
        Log.e("AppLog", "error:", e);
    }
}

The result should end with "=" .


Run either this in your app :

FacebookSdk.sdkInitialize(getApplicationContext());
Log.d("AppLog", "key:" + FacebookSdk.getApplicationSignature(this)+"=");

Or this:

public static void printHashKey(Context context) {
    try {
        final PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
        for (android.content.pm.Signature signature : info.signatures) {
            final MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            final String hashKey = new String(Base64.encode(md.digest(), 0));
            Log.i("AppLog", "key:" + hashKey + "=");
        }
    } catch (Exception e) {
        Log.e("AppLog", "error:", e);
    }
}

And then look at the logs.

The result should end with "=" .

Solution is based on here and here .


For Linux and Mac

Open Terminal :

For Debug Build

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

You will find debug.keystore in the ".android" folder. Copy it and paste onto the desktop and run the above command.

For release Build

keytool -exportcert -alias <aliasName> -keystore <keystoreFilePath> | openssl sha1 -binary | openssl base64

NOTE : Make sure that in both cases it asks for a password. If it does not ask for a password, it means that something is wrong in the command. Password for debug.keystore is "android" and for release you have to enter password that you set during create keystore.


You can get all your fingerprints from https://console.developers.google.com/projectselector/apis/credentials
And use this Kotlin code to convert it to keyhash:

fun main(args: Array<String>) {
    listOf("<your_production_sha1_fingerprint>",
            "<your_debug1_sha1_fingerprint>",
            "<your_debug2_sha1_fingerprint>")
            .map { it.split(":") }
            .map { it.map { it.toInt(16).toByte() }.toByteArray() }
            .map { String(Base64.getEncoder().encode(it)) }
            .forEach { println(it) }
}

If you have already uploaded the app to Play store you can generate Hash Key as follows:

  1. Go to Release Management here

  2. Select Release Management -> App Signing

  3. You can see SHA1 key in hex format App signing certificate.

  4. Copy the SHA1 in hex format and convert it in to base64 format, you can use this link do that without the SHA1: part of the hex.

  5. Go to Facebook developer console and add the key(after convert to base 64) in the settings —> basic –> key hashes.


Here is complete details (For Windows)

1. Download OpenSSl either 3rd or 4th (with e will work better) based on your system 32bit or 64bit .

2. Extract the downloaded zip inside C directory

3. Open the extracted folder up to bin and copy the path ,it should be some thing like C:\openssl-0.9.8k_X64\bin\openssl (add \openssl at end)

4. (Get the path to the bin folder of Jdk ,if you know how,ignore this ) .

Open android studio ~file~Project Structure(ctrl+alt+shift+s) , select SDK location in left side panel ,copy the JDK location and add /bin to it

So final JDK Location will be like C:\Program Files\Android\Android Studio\jre\bin

we are following this method to get Jdk location because you might use embedded jdk like me

enter image description here

now you have OpenSSl location & JDK location

5. now we need debug keystore location , for that open C~>Users~>YourUserName~>.android there should be a file name debug.keystore ,now copy the path location ,it should be some thing like

C:\Users\Redman\.android\debug.keystore

6. now open command prompt and type command

cd YourJDKLocationFromStep4  

in my case

 cd "C:\Program Files\Android\Android Studio\jre\bin"

7. now construct the following command

keytool -exportcert -alias androiddebugkey -keystore YOURKEYSTORELOCATION | YOUROPENSSLLOCATION sha1 -binary | YOUROPENSSLLOCATION base64

in my case the command will look like

keytool -exportcert -alias androiddebugkey -keystore "C:\Users\Redman\.android\debug.keystore" | "C:\openssl-0.9.8k_X64\bin\openssl" sha1 -binary | "C:\openssl-0.9.8k_X64\bin\openssl" base64

now enter this command in command prompt , if you did ever thing right you will be asked for password (password is android)

Enter keystore password:  android

thats it ,you will be given the Key Hash , just copy it and use it

For Signed KeyHash construct the following Command

keytool -exportcert -alias YOUR_ALIAS_FOR_JKS -keystore YOUR_JKS_LOCATION | YOUROPENSSLLOCATION sha1 -binary | YOUROPENSSLLOCATION base64

enter your keystore password , If you enter wrong password it will give wrong KeyHash

NOTE

If for some reason if it gives error at some path then wrap that path in double quotes .Also Windows power shell was not working well for me, I used git bash (or use command prompt) .

example

keytool -exportcert -alias androiddebugkey -keystore "C:\Users\Redman\.android\debug.keystore" | "C:\openssl-0.9.8k_X64\bin\openssl" sha1 -binary | "C:\openssl-0.9.8k_X64\bin\openssl" base64

if someone have problem with openssl , follow this instructions:

  1. download "openssl" for windows in zip
  2. extract zip in the path you want.
  3. get path for "bin" folder inside the zip

That's it

https://sourceforge.net/projects/openssl/files/latest/download


You can use this apk

1.first install the app from the Google play store
2.install the above apk
3.launch the apk and input the package name of your app
4.then you will get the hash code you want

That's how I obtained my:

private class SessionStatusCallback implements Session.StatusCallback {
        @Override
        public void call(Session session, SessionState state, Exception exception) {

            if (exception != null) {
                new AlertDialog.Builder(FriendActivity.this)
                        .setTitle(R.string.login_failed_dialog_title)
                        .setMessage(exception.getMessage())
                        .setPositiveButton(R.string.ok_button, null)
                        .show();
            }

So when you re trying to enter without the key, an exception will occur. Facebook put the RIGHT key into this exception. All you need to do is to copy it.


For Windows:

  1. open command prompt and paste below command

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

  1. Enter password : android --> Hit Enter

  2. Copy Generated Hash Key --> Login Facebook with your developer account

  3. Go to your Facebook App --> Settings--> Paste Hash key in "key hashes" option -->save changes.

  4. Now Test your android app with Facebook Log-in/Share etc.


    private fun generateKeyHash(): String? {try {
    val info =packageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES)
    for (signature in info.signatures) {
        val md: MessageDigest = MessageDigest.getInstance("SHA")
        md.update(signature.toByteArray())
        return String(Base64.encode(md.digest(), 0))
    }
} catch (e: Exception) {
    Log.e("exception", e.toString())
}
    return "key hash not found"
}

I ran into the same problem and here's how I was able to fix it

keytool -list -alias androiddebugkey -keystore <project_file\android\app\debug.keystore>

Just run this code in your OnCreateView Or OnStart Actvity and This Function Return you Development Key Hash.

private String generateKeyHash() {
    try {
        PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES);
        for (Signature signature : info.signatures) {
            MessageDigest md = (MessageDigest.getInstance("SHA"));
            md.update(signature.toByteArray());
            return new String(Base64.encode(md.digest(), 0));
        }
    }catch (Exception e) {
        Log.e("exception", e.toString());
    }
    return "key hash not found";
}

https://developers.facebook.com/docs/android/getting-started/

4.19.0 - January 25, 2017

Facebook SDK

Modified

Facebook SDK is now auto initialized when the application starts. In most cases a manual call to FacebookSDK.sdkInitialize() is no longer needed. See upgrade guide for more details.

For Debug

try {
    PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 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 (NoSuchAlgorithmException e) {
    e.printStackTrace();
} catch (Exception e) {
    e.printStackTrace();
}

keytool -exportcert -alias androiddebugkey -keystore "C:\Users**Deepak**.android\debug.keystore" | "C:\Users\Deepak\ssl\bin\openssl" sha1 -binary | "C:\Users\Deepak\ssl\bin\openssl" base64

2 Changes in this above command 1.Deepak===Replace by your System USERNAME 2.C:\Users\Deepak\ssl=== replce your Open SSL path

run this command and get output like this

C:\Users\Deepak>keytool -exportcert -alias androiddebugkey -keystore "C:\Users\D eepak.android\debug.keystore" | "C:\Users\Deepak\ssl\bin\openssl" sha1 -binary | "C:\Users\Deepak\ssl\bin\openssl" base64 Enter keystore password: ****** ga0RGNY******************=


to generate your key hash on your local computer, run Java's keytool utility (which should be on your console's path) against the Android debug keystore. This is, by default, in your home .android directory). On OS X, run:

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

On Windows, use:-

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

hope this will help you

Ref - developer facebook site


EASY WAY -> Don't install openssl -> USE GIT BASH!

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

The default password is "android"

Most of us have Git Bash installed so this is my favorite way.


For easy vedio tutorial link for the generate KeyHash Here

Download openssl from HERE


so easy find sha1 of your android project

and paste on this website fbkeyhash

for get sha1 just

// vscode and my cmd
project-name/cd android && ./gradlew signingReport

// other 
project-name/cd android && ./gradlew signingReport

I was having the same exact problem, I wasnt being asked for a password, and it seems that I had the wrong path for the keystore file.

In fact, if the keytool doesn't find the keystore you have set, it will create one and give you the wrong key since it isn't using the correct one.

The general rule is that if you aren't being asked for a password then you have the wrong key being generated.


step 1->open cmd in your system

step 2->C:\Program Files\Java\jdk1.6.0_43\bin>

Step 3->keytool -list -v -keystore C:\Users\leon\.android\debug.keystore -alias androiddebugkey -storepass android -keypass android

u got SHA1 value click this link u convert ur SHA1 value to HASH KEY

im 100% sure this link will help u


this will help newbees also.

just adding more details to @coder_For_Life22's answer.

if this answer helps you don't forget to upvote. it motivates us.

for this you must already know the path of the app's keystore file and password

for this example consider the key is stored at "c:\keystorekey\new.jks"

1. open this page https://code.google.com/archive/p/openssl-for-windows/downloads

2. download 32 or 64 bit zip file as per your windows OS.

3. extract the downloaded file where ever you want and remember the path.

4. for this example we consider that you have extracted the folder in download folder.

so the file address will be "C:\Users\0\Downloads\openssl-0.9.8e_X64\bin\openssl.exe";

5. now on keyboard press windows+r button.

6. this will open run box.

7. type cmd and press Ctrl+Shift+Enter.

8. this will open command prompt as administrator.

9. here navigate to java's bin folder:

if you use jre provided by Android Studio you will find the path as follows:
a. open android studio.
b. file->project structure
c. in the left pane, click 'SDK location'
d. in the right pane, below 'JDK location' is your jre path.
e. add "\bin" at the end of this path as the file "keytool.exe", we need, is inside this folder.
for this example i consider, you have installed java separately and following is the path
"C:\Program Files\Java\jre-10.0.2\bin"
if you have installed 32bit java it will be in
"C:\Program Files (x86)\Java\jre-10.0.2\bin"
10. now with above paths execute command as following:

keytool -exportcert -alias androiddebugkey -keystore "c:\keystorekey\new.jks" | "C:\Users\0\Downloads\openssl-0.9.8e_X64\bin\openssl.exe" sha1 -binary |"C:\Users\0\Downloads\openssl-0.9.8e_X64\bin\openssl.exe" base64
  1. You will be asked for password, give the password you have given when creating keystore key.

    !!!!!! this will give you the key

errors: if you get:
---
'keytool' is not recognized as an internal or external command
---
this means that java is installed somewhere else.


Since API 26, you can generate your HASH KEYS using the following code in KOTLIN without any need of Facebook SDK.

fun generateSSHKey(context: Context){
    try {
        val info = context.packageManager.getPackageInfo(context.packageName, PackageManager.GET_SIGNATURES)
        for (signature in info.signatures) {
            val md = MessageDigest.getInstance("SHA")
            md.update(signature.toByteArray())
            val hashKey = String(Base64.getEncoder().encode(md.digest()))
            Log.i("AppLog", "key:$hashKey=")
        }
    } catch (e: Exception) {
        Log.e("AppLog", "error:", e)
    }

}

enter image description here


Please try this:

public static void printHashKey(Context pContext) {
        try {
            PackageInfo info = pContext.getPackageManager().getPackageInfo(pContext.getPackageName(), PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                String hashKey = new String(Base64.encode(md.digest(), 0));
                Log.i(TAG, "printHashKey() Hash Key: " + hashKey);
            }
        } catch (NoSuchAlgorithmException e) {
            Log.e(TAG, "printHashKey()", e);
        } catch (Exception e) {
            Log.e(TAG, "printHashKey()", e);
        }
    }

You can simply use one line javascript in browser console to convert a hex map key to base64. Open console in latest browser (F12 on Windows, ? Option+? Command+I on macOS, Ctrl+? Shift+I on Linux) and paste the code and replace the SHA-1, SHA-256 hex map that Google Play provides under Release Setup App signing:

Hex map key to Base64 key hash

> btoa('a7:77:d9:20:c8:01:dd:fa:2c:3b:db:b2:ef:c5:5a:1d:ae:f7:28:6f'.split(':').map(hc => String.fromCharCode(parseInt(hc, 16))).join(''))
< "p3fZIMgB3fosO9uy78VaHa73KG8="

You can also convert it here; run the below code snippet and paste hex map key and hit convert button:

_x000D_
_x000D_
document.getElementById('convert').addEventListener('click', function() {
  document.getElementById('result').textContent = btoa(
    document.getElementById('hex-map').value
      .split(':')
      .map(hc => String.fromCharCode(parseInt(hc, 16)))
      .join('')
  );
});
_x000D_
<textarea id="hex-map" placeholder="paste hex key map here" style="width: 100%"></textarea>
<button id="convert">Convert</button>
<p><code id="result"></code></p>
_x000D_
_x000D_
_x000D_

And if you want to reverse a key hash to check and validate it:

Reverse Base64 key hash to hex map key

> atob('p3fZIMgB3fosO9uy78VaHa73KG8=').split('').map(c => c.charCodeAt(0).toString(16)).join(':')
< "a7:77:d9:20:c8:1:dd:fa:2c:3b:db:b2:ef:c5:5a:1d:ae:f7:28:6f"

_x000D_
_x000D_
document.getElementById('convert').addEventListener('click', function() {
  document.getElementById('result').textContent = atob(document.getElementById('base64-hash').value)
    .split('')
    .map(c => c.charCodeAt(0).toString(16))
    .join(':')
});
_x000D_
<textarea id="base64-hash" placeholder="paste base64 key hash here" style="width: 100%"></textarea>
<button id="convert">Convert</button>
<p><code id="result"></code></p>
_x000D_
_x000D_
_x000D_


Easy way

By using this website you can get Hash Key by Converting SHA1 key to Hash Key for Facebook.


Download open ssl:

Then add openssl\bin to the path system variables:

My computer -> properties -> Advanced configurations -> Advanced -> System variables -> under system variables find path, and add this to its endings: ;yourFullOpenSSLDir\bin

Now open a command line on your jdk\bin folder C:\Program Files\Java\jdk1.8.0_40\bin (on windows hold shift and right click -> open command line here) and use:

keytool -exportcert -alias keystorealias -keystore C:\yourkeystore\folder\keystore.jks | openssl sha1 -binary | openssl base64

And copy the 28 lenght number it generates after giving the password.


OpenSSL: You have to install that if it doesn't come preinstalled with your operating system (e.g. Windows does not have it preinstalled). How to install that depends on your OS (for Windows check the link provided by coder_For_Life22).

The easiest way without fiddling around is copying that openssl.exe binary to your keytool path if you are on Windows. If you don't want to do that, you have to add it to your PATH environment variable. Then execute the command provided in the docs.

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

Note that the argument after -keystore points to your debug keystore. This location also depends on your operating system. Should be in one of the following locations:

  • Windows Vista or 7 - C:\Users\.android\debug.keystore
  • Windows XP - C:\Documents and Settings\.android\debug.keystore
  • OS X and Linux - ~/.android/debug.keystore

If you did everything right, you should be prompted for a password. That is android for the debug certificate. If the password is correct the console prints a hash (somewhat random chars and numbers).

Take that and copy it into the android key hash field inside the preferences of your app on facebook. To get there, go to developers.facebook.com/apps, select your app, go to Edit settings and scroll down. After that, wait a few minutes until the changes take effect.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to facebook

I am receiving warning in Facebook Application using PHP SDK React-Native: Application has not been registered error Can't Load URL: The domain of this URL isn't included in the app's domains Facebook OAuth "The domain of this URL isn't included in the app's domain" Facebook login message: "URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings." Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView` Open Facebook Page in Facebook App (if installed) on Android App not setup: This app is still in development mode IOS - How to segue programmatically using swift Get ALL User Friends Using Facebook Graph API - Android