Print signing key SHA in code

Print signing key SHA in code

If you ever want to get the SHA, MD5 or the signing key used to sign your app for example you can use the following snippet:

private void printSHA() {
    try {
        // get the package info that contains the key you want to print
        PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES);

        for (Signature signature : info.signatures) {
            // you can use other algorithms like MD5, SHA-1 or SHA-256
            MessageDigest sha = MessageDigest.getInstance("SHA-256");

            // print the signing key SHA hash
            byte[] output = sha.digest();
            Log.e("MY KEY HASH:", Base64.encodeToString(output, Base64.DEFAULT));
            Log.e("MY KEY HASH Hex:", bytesToHex(output));
    } catch (PackageManager.NameNotFoundException notFoundException) {
        Log.e("My tag", notFoundException.getMessage());
    } catch (NoSuchAlgorithmException noSuchAlgorithmException) {
        Log.e("My tag", noSuchAlgorithmException.getMessage());

And the converter method that outputs a hexa string from an array of bytes:

public static String bytesToHex(byte[] bytes) {
    final StringBuilder builder = new StringBuilder();
    for(byte aByte : bytes) {
        builder.append(String.format("%02x", aByte));
    return builder.toString();

Using this you can implement validation systems between your app and backend. This way the backend knows if the app that does a request has this extra security layer or not :).


, , , , , , , ,
Previous Post
Make Genymotion point to localhost
Next Post
How to unzip Gzipped InputStream

Related Posts