Skip to content

Instantly share code, notes, and snippets.

@tuzenvn
Forked from scottyab/SignatureCheck.java
Last active March 7, 2020 12:13
Show Gist options
  • Save tuzenvn/64fb662817f9698231ff33d5b35e8093 to your computer and use it in GitHub Desktop.
Save tuzenvn/64fb662817f9698231ff33d5b35e8093 to your computer and use it in GitHub Desktop.
Simple Android signature check. It's not bullet proof but does increase the difficulty of backdooring the app
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Build;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import timber.log.Timber;
public class SignatureCheck {
//we store the hash of the signture for a little more protection
private static final String APP_SIGNATURE = "48ADE4692E8BC66455766F41D2CC3A17D005E55F";
/**
* Query the signature for this application to detect whether it matches the
* signature of the real developer. If it doesn't the app must have been
* resigned, which indicates it may been tampered with.
*
* @param context
* @return true if the app's signature matches the expected signature.
* @throws PackageManager.NameNotFoundException
*/
public boolean signaturesAreNotValid(Context context) throws PackageManager.NameNotFoundException {
final Signature[] signatures;
if(Build.VERSION.SDK_INT >= 28) {
signatures = context.getPackageManager().getPackageInfo(
context.getPackageName(), PackageManager.GET_SIGNING_CERTIFICATES).signingInfo.getApkContentsSigners();
} else {
signatures = context.getPackageManager().getPackageInfo(
context.getPackageName(), PackageManager.GET_SIGNATURES).signatures;
}
//note sample just checks the first signature
if (signatures!= null) {
for (Signature signature : signatures) {
// SHA1 the signature
String sha1 = "";
try {
sha1 = getSHA1(signature.toByteArray());
Timber.d("SHA: " + sha1);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
// check is matches hardcoded value
if (!APP_SIGNATURE.equals(sha1)) {
return false;
}
}
}
return true;
}
//computed the sha1 hash of the signature
public static String getSHA1(byte[] sig) throws NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance("SHA1");
digest.update(sig);
byte[] hashtext = digest.digest();
return bytesToHex(hashtext);
}
//util method to convert byte array to hex string
public static String bytesToHex(byte[] bytes) {
final char[] hexArray = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'A', 'B', 'C', 'D', 'E', 'F' };
char[] hexChars = new char[bytes.length * 2];
int v;
for (int j = 0; j < bytes.length; j++) {
v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment