Skip to content
Advertisement

How to determine if an apk is signed in Java?

I’m building an Java Android App in Android Studio. In my onCreate function I wand to determine if the App has been build with or without a certificate.

But by now, I get no Certificate Information at all.

        Activity activity = this;

        Signature[] sigs;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            // New signature
            PackageInfo siginfo = activity.getPackageManager().getPackageArchiveInfo(activity.getPackageName(), activity.getPackageManager().GET_SIGNING_CERTIFICATES);
            if (siginfo == null){
                sigs = new Signature[0];
            }else{
                sigs = siginfo.signingInfo.getApkContentsSigners();
            }
            
        }else {
            sigs = activity.getPackageManager().getPackageArchiveInfo(activity.getPackageName(), activity.getPackageManager().GET_SIGNATURES).signatures;
        }
        
        String sigstring = "";
        for (Signature sig : sigs)
        {
            sigstring.concat(sig.toCharsString() + "; ");
        }
        Log.i("SigString: " + sigstring);
        Log.i("NumberOfSignatures: " + sigs.length);

output:

2021-04-19 14:44:52.156 I:SigString: 
2021-04-19 14:44:52.156 I:NumberOfSignatures: 0

Advertisement

Answer

You have to use getPackageInfo instead of getPackageArchiveInfo. When you do so, getPackageInfo has to be enclosed in a try-catch-block.

Thus, the line

PackageInfo siginfo = activity.getPackageManager().getPackageArchiveInfo(activity.getPackageName(), activity.getPackageManager().GET_SIGNING_CERTIFICATES);

needs to be replaced by

PackageInfo siginfo;
try {
  siginfo = activity.getPackageManager().getPackageInfo(activity.getPackageName(), activity.getPackageManager().GET_SIGNING_CERTIFICATES);
}catch (PackageManager.NameNotFoundException e){
  siginfo = null;
}

and the line in the else block has to be changed equivalently as well.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement