How to create Android Facebook Key Hash?

JavaAndroidFacebook

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

Here is what you need to do -

Download openSSl from Code Extract it. create a folder- OpenSSL in C:/ and copy the extracted code here.

detect debug.keystore file path. If u didn't find, then do a search in C:/ and use the Path in the command in next step.

detect your keytool.exe path and go to that dir/ in command prompt and run this command in 1 line-

$ keytool -exportcert -alias androiddebugkey -keystore "C:\Documents and Settings\Administrator.android\debug.keystore" | "C:\OpenSSL\bin\openssl" sha1 -binary |"C:\OpenSSL\bin\openssl" base64

it will ask for password, put android that's all. u will get a key-hash

Solution 2 - Java

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.

Solution 3 - Java

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);
		}
	}

Solution 4 - Java

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<user>.android\debug.keystore
  • Windows XP - C:\Documents and Settings<user>.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.

Solution 5 - Java

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 ReleaseSetupApp 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:

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('')
  );
});

<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>

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"

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(':')
});

<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>

Solution 6 - Java

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 fileProject 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

Solution 7 - Java

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

Solution 8 - Java

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.

Solution 9 - Java

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 "=" .

Solution 10 - Java

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.

Solution 11 - Java

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

Solution 12 - Java

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

Solution 13 - Java

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.

Solution 14 - Java

Easy way

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

Solution 15 - Java

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.

Solution 16 - Java

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 .

Solution 17 - Java

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.

Solution 18 - Java

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) }
}

Solution 19 - Java

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<br><br>
  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.

Solution 20 - Java

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";
}

Solution 21 - Java

so easy find sha1 of your android project

and paste on this website tomeko

for get sha1 just

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

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

Solution 22 - Java

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.

Solution 23 - Java

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

Solution 24 - Java

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

Solution 25 - Java

Try this answer

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

with minimal efforts helps to resolve the issue.

Solution 26 - Java

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******************=

Solution 27 - Java

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

Solution 28 - Java

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>

Solution 29 - Java

    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"
}

Solution 30 - Java

    @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    
    // Add code to print out the key hash
    try {
        PackageInfo info = getPackageManager().getPackageInfo(
                "com.facebook.samples.hellofacebook", 
                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) {
        
    }
    
    ...

Save your changes and re-run the sample. Check your logcat output for a message similar to this:

> 12-20 10:47:37.747: D/KeyHash:(936): 478uEnKQV+fMQT8Dy4AKvHkYibo=

Save the key hash in your developer profile. Re-run the samples and verify that you can log in successfully.

Solution 31 - Java

please try this , it works for me :

fun Context.generateSignKeyHash(): String {

    try {

        val info = packageManager.getPackageInfo(
            packageName,
            PackageManager.GET_SIGNATURES
        )

        for (signature in info.signatures) {
            val md = MessageDigest.getInstance("SHA")
            md.update(signature.toByteArray())
            return Base64.encodeToString(md.digest(), Base64.DEFAULT)
        }

    } catch (e: Exception) {
        Log.e("keyHash", e.message.toString())
    }

    return ""

}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSomkView Question on Stackoverflow
Solution 1 - Javacoder_For_Life22View Answer on Stackoverflow
Solution 2 - JavaBiraj ZalavadiaView Answer on Stackoverflow
Solution 3 - JavaMaddyView Answer on Stackoverflow
Solution 4 - Javauser658042View Answer on Stackoverflow
Solution 5 - JavaChristos LytrasView Answer on Stackoverflow
Solution 6 - JavaManoharView Answer on Stackoverflow
Solution 7 - JavaRakeshView Answer on Stackoverflow
Solution 8 - JavaMouzmiSadiqView Answer on Stackoverflow
Solution 9 - Javaandroid developerView Answer on Stackoverflow
Solution 10 - JavaswiftBoyView Answer on Stackoverflow
Solution 11 - JavaHannyView Answer on Stackoverflow
Solution 12 - Javanaveen pandiView Answer on Stackoverflow
Solution 13 - JavaValikponView Answer on Stackoverflow
Solution 14 - Javasaigopi.meView Answer on Stackoverflow
Solution 15 - JavaDmitri R117View Answer on Stackoverflow
Solution 16 - Javaandroid developerView Answer on Stackoverflow
Solution 17 - JavaRenato ProbstView Answer on Stackoverflow
Solution 18 - JavaAlexmelyonView Answer on Stackoverflow
Solution 19 - Javasifr_dot_inView Answer on Stackoverflow
Solution 20 - JavaSheikh HasibView Answer on Stackoverflow
Solution 21 - JavaRahman RezaeeView Answer on Stackoverflow
Solution 22 - JavaNick TsitlakidisView Answer on Stackoverflow
Solution 23 - JavaarmnotstrongView Answer on Stackoverflow
Solution 24 - JavaKetan RamaniView Answer on Stackoverflow
Solution 25 - JavaVicky SalunkheView Answer on Stackoverflow
Solution 26 - JavaDeepak parmarView Answer on Stackoverflow
Solution 27 - JavaMalek TubaisahtView Answer on Stackoverflow
Solution 28 - JavaDomtryView Answer on Stackoverflow
Solution 29 - JavaPeterView Answer on Stackoverflow
Solution 30 - JavaBholendra SinghView Answer on Stackoverflow
Solution 31 - Javafarshad rezaeiView Answer on Stackoverflow