How to create Android Facebook Key Hash?
Asked Answered
P

30

248

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?

Pregnancy answered 21/9, 2011 at 20:44 Comment(4)
if you are using latest facebook sdk and if you putted your facebook api perfectly then when login you click on login in facebook then in your logcat the hash key is printed..Isocline
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 base64Discovert
Why would anyone want to create a debug key?Toh
I have generated the key hash but don't know where to put that key, would you guide me? I'm running android studio on Ubuntu.Femoral
R
302

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

Rackley answered 21/9, 2011 at 20:48 Comment(18)
when it asks for a password can I put anything I want?Pregnancy
@Max, default password is android.Birnbaum
Note that this assumes Windows.Elvia
key hash doesn't match any stored key hashes android , not workingNaumann
Same problem as Paul. Tried a different version of OpenSSL too and still the same problem.Ferrante
I have generated the key hash but don't know where to put that key, would you guide me? I'm running android studio on Ubuntu.Femoral
First create a keystore by going to Build --> Build Apk from your studio. provide a name and password etc. Store it as a .jks file at a folder easily accessible. Now copy the path and generate the key by replacing that path in the above mentioned answer.Biodynamics
My key hash is weird: SK3E0KSlUYb85uiNNMTcHb2/gg4= not like the examples out thereOutreach
It is important not to use debug.keystore but use the keystore you generate when you sign the apk.Drinker
there is much efficient way to get the Hash Key in this answer by: @Mahendran SakkaraiSelfcontrol
It shows me an error: "... Expressions are only allowed as the first element of a pipeline. At line:1 char:184 ... Unexpected token 'sha1' in expression or statement. ... Expressions are only allowed as the first element of a pipeline. ... Unexpected token 'base64' in expression or statement. + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : ExpressionsMustBeFirstInPipeline "Midshipmite
@Outreach - that is your hash key.Defaulter
easiest way to copy keytool.exe and keytore cert when openssl isNeri
Just a tip if someone found the same problem, days ago I typed another custom password and now I was trying to use android, it did not work. After a while I figured out I needed to type the same custom password I typed before.Saretta
I generate Key Hashes but the password is not asking. Automatically generate the key.Anaximenes
I found this post helpfull https://mcmap.net/q/10287/-key-hash-for-android-facebook-appAnastigmat
I got the error "Expressions are only allowed as the first element of a pipeline" when using windows Powershell. When I changed my shell to Bash (in Visual Studio Code) it works fine.Stillman
My key hash was weird in powershell, but was alright in cmd. Do not use powershell for this I guess.Ripleigh
G
231

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.

Guddle answered 7/8, 2013 at 10:49 Comment(8)
To be clear, the password is empty. Just hit <enter> when prompted.Zymogen
I have generated the key hash but don't know where to put that key, would you guide me? I'm running android studio on Ubuntu.Femoral
This note: "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." was essential to solve the problemTrifolium
thank you for saving my life. im tyiping my mac password for the keystore password the whole time and i realized it was wrongVoronezh
Even asking for a password does not means that everything is ok (wrong password, wrong key alias). Run keytool -exportcert -alias <aliasName> -keystore <keystoreFilePath> alone at first, to see if everything is ok. Plus, when piped, keytool is in non-interactive mode and show the password in plain text when you input it. So you better write a small script that runs the commands separately.Waldheim
What is the purpose of copying the file to your desktop? The command will only work if your pwd happens to be the desktop directory. It worked fine for me to just write out the path: keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64 Also, I don't think @TomRedman 's comment is correct anymore. I had to actually type in "android" as the password. Leaving it blank did not work and displayed a warning message.Rhizo
Hi, when i input the code for release Build, it errors to: -bash: syntax error near unexpected token `|'Corcyra
I got a weird situation here, where both Debug and Release hash generated are the same hash. Using the generating code with androiddebugkey and my unique release alias, but both resulting hash are the same hash..... Anyone knows the fix?Burtonburty
M
129

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);
        }
    }
Myers answered 27/8, 2014 at 10:23 Comment(7)
I have generated the key hash but don't know where to put that key, would you guide me? I'm running android studio on Ubuntu.Femoral
this is the way to goSleigh
This works, if you call pContext.getPackageInfo. Or just remove it from a function and call it in onCreate of any activity.Ferrante
This now seems to be getPackageManager().getPackageInfo([your-package_name], PackageManager.GET_SIGNATURES)Zaidazailer
@Femoral You can put it in Android SharedPreferences in case of having any later use of that.Myers
It says GET_SIGNATURES is deprecated, but this still worked like a charm! Definitely the easiest way to go if you don't have keytool or openSSL installed.Septarium
perfectly worked for me!Bacteriophage
P
82

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:

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>
Peat answered 25/7, 2019 at 14:34 Comment(3)
SHA-1 was the one.Hatchery
This is very useful when google play store generates the certificate for me. I need this to convert to the generated certificate, instead of the keystore, to facebook hashColumbuscolumbyne
I believe this is the most up-to-date answer, since the Play Store now manages the final app signing, and the .jks file is now used only as the upload key instead of the final key. Thank you.Paleobiology
I
58

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.

Immortelle answered 21/9, 2011 at 20:59 Comment(4)
I ran this in cmd and it output a very long list of chars looking like a hash ending with an = sign then nothing $ keytool -exportcert -alias androiddebugkey -keystore "C:\Users\.android\debug.keystore" | "C:\OpenSSL\bin\openssl" sha1 -binary |"C:\OpenSSL\bin\openssl" base64Pregnancy
Sounds correct. Just tested it on my machine, was 28 chars long for me, just to give you an idea. Now just copy it over and you're fine. :)Immortelle
i wasnt prompted to use the pharse android though. Sorry am I being slow?Pregnancy
To be honest, I'm not sure why you didn't get prompted for that. But it sounds correct to me. I mean, if you would have done something wrong, there should be an error message instead. Just copy it over and see if it works. You can test some of the graph queries with the Graph API Explorer. Select your app on the top and see if you get valid results. It should spit an error if there is something wrong. Edit: And nothing wrong with beeing slow. We're not in a hurry. :)Immortelle
I
39

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.

Inquest answered 9/7, 2019 at 12:37 Comment(0)
S
35

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
Septum answered 15/9, 2017 at 13:58 Comment(7)
Thank you very much, this is a very detailed guide for beginners!Byington
@TamimProduction try same above procedure with k version of openssl and see code.google.com/archive/p/openssl-for-windows/downloadsSeptum
@TamimProduction if you enter wrong password it will return wrong keyhash . also did you build the apk again after deleting keystore ?Septum
@TamimProduction download and install Facebook application , login in facebook application . open your app and do facebook login . It will give you key hash in facebook application , check if it is same as yoursSeptum
Let us continue this discussion in chat.Pre
This is a complete answer. Thank you!Isahella
Nice job & good work done. You elaborated all things that every developer needs. :)Clarinda
D
25

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

Discovert answered 18/2, 2014 at 8:6 Comment(1)
I have generated the key hash but don't know where to put that key, would you guide me? I'm running android studio on Ubuntu.Femoral
M
18

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

Midshipmite answered 8/2, 2018 at 14:10 Comment(3)
I noticed that my key hash has a '_' in it which is not allowed by FB. In order to use the hash I had to change it to a '/'.Leveridge
Facebook function returned my key as -AAAAAAAA_AAAAAA-AAAAAAAAAA that is not allowed by Facebook, printHashKey returned the key in a valid format +AAAAAAAA/AAAAAA+AAAAAAAAAA=Acropolis
@GrafOrlov How odd. Maybe they have a bug on some new FB SDK version. You should report about it to them.Midshipmite
B
13

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

You got SHA1 value Hex to base64 converter, convert your SHA1 value to HASH KEY.

I am 100% sure this link will help You.

Bobinette answered 23/8, 2019 at 11:58 Comment(0)
Z
10

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.

Zicarelli answered 21/4, 2014 at 10:57 Comment(2)
I have generated the key hash but don't know where to put that key, would you guide me? I'm running android studio on Ubuntu.Femoral
Hi, I am able to generate hash key via code in my main activity but that generated hash key is only work on single device. When I install same apk in another device and run that it's showing invalid hash key error. Is there any thing I am missing.Oujda
S
9

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

Saloma answered 30/6, 2018 at 9:32 Comment(1)
You mean I place your code in class MainActivity: FlutterActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) GeneratedPluginRegistrant.registerWith(this) } }Auer
G
9

Easy way

By using the link hex_to_base64 you can get Hash Key by Converting SHA1 key to Hash Key for Facebook.

Gamin answered 23/4, 2020 at 1:15 Comment(0)
C
8

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.

Cense answered 25/6, 2019 at 20:32 Comment(1)
How to launch it? I see bash: keytool: command not found. A screenshot imgur.com/a/NHJrZRSEadwina
I
7

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.

Isothermal answered 4/1, 2013 at 13:35 Comment(1)
I have generated the key hash but don't know where to put that key, would you guide me? I'm running android studio on Ubuntu.Femoral
M
5

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
Midwest answered 14/12, 2020 at 8:10 Comment(0)
M
4

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 .

Midshipmite answered 8/2, 2018 at 14:4 Comment(0)
A
3

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.

Allsun answered 24/6, 2015 at 6:29 Comment(4)
I havent seen that the original answer already has the openssl link. But its still usefull for the system variable.Allsun
I have generated the key hash but don't know where to put that key, would you guide me? I'm running android studio on Ubuntu.Femoral
Ofcourse, are you sure you have generated the 28 length number? If so, now you have to go to facebook developer (search on google) site and create a new application, under settings, you can add a new Android app, there you paste your keyhash and your activity name (where the login code is located). Theres a tutorial about it on facebook tooAllsun
Thanks for the quick reply, I'll try it shortlyFemoral
S
3

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) }
}
Saltine answered 24/8, 2017 at 13:8 Comment(0)
G
3

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.

Gallery answered 13/7, 2019 at 13:33 Comment(0)
H
2

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";
}
Heptarchy answered 26/1, 2020 at 10:31 Comment(0)
J
1

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.

Jowl answered 23/11, 2012 at 13:55 Comment(1)
I have generated the key hash but don't know where to put that key, would you guide me? I'm running android studio on Ubuntu.Femoral
S
1

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
Sacculus answered 2/2, 2018 at 5:4 Comment(1)
@Elynad It's Chinese :DSacculus
W
1

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();
}
Welldisposed answered 17/9, 2018 at 11:56 Comment(0)
S
1

I think that documentation will helps to you finding SHA-1, SHA-256 and also Hash-key

[Debug and Release]

View full Documentation

Swinger answered 19/6, 2023 at 8:15 Comment(1)
You are correct. When I insert my SHA-1 key into the Facebook hash key field, it automatically converts it into a hash key. It's working as expected. Thank you!Eddington
J
0

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

Julian answered 2/6, 2020 at 13:29 Comment(0)
R
0

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>
Rendon answered 16/10, 2020 at 15:19 Comment(1)
this does not show hashes for facebook, instead, it shows SHA1Memberg
C
0
    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"
}
Chrysarobin answered 3/2, 2021 at 1:12 Comment(0)
J
0
    @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.

Jugular answered 1/6, 2021 at 20:31 Comment(0)
V
0

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

}
Vivi answered 14/9, 2021 at 12:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.