Categories
Android Coding Guides

How to generate key certificate hash programmatically: Android Java

We have to generate the hash for both debug and release build types. Which we can use for verification of requests from our android app to our server. Upon verification, the server will pass the requested data.

In app: build.gradle

signingConfigs {
        release {
            Properties keystoreProps = new Properties()
            keystoreProps.load(new FileInputStream(file("YOUR_PATH\\keystore.config")))
            keyAlias keystoreProps['keyAlias']
            keyPassword keystoreProps['keyPassword']
            storePassword keystoreProps['storePassword']
            storeFile file('YOUR_PATH\\keystore.jks')
        }
    }
buildTypes {
        debug {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        release {
            minifyEnabled false
            signingConfig signingConfigs.release
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

keystore.config
Prepared to keep the keystore passwords and alias hidden when the code is public or compromised.

keyAlias=MyAlias
keyPassword=MyPassword
storePassword=StorePassword

Inside java code:

// Add code to print out the key hash
        try {
            PackageInfo info = getPackageManager().getPackageInfo(getApplication().getPackageName(), PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.e("key_hash", Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

The hash key will be generated based on the current build type of the apk.