Captain Blammo
Captain Blammo

Reputation: 1897

How can I verify whether another app on the system is genuine?

I'd like to send intents containing sensitive information to another app on the system, which I have also written. Before doing so, I need to verify that the app I am sending them to is signed by me, and not just a rogue version with the same packagename and classes. How can I do this programmatically?

I want to do this using explicit intents dispatched through startService() and startActivity(), so there are no concerns around broadcast intents. That said, I don't want to send anything until I have verified that the package name I specify is installed and signed by the author (myself in this specific case).

Upvotes: 5

Views: 370

Answers (1)

Yojimbo
Yojimbo

Reputation: 24256

The package manager will give you the signing certificate for any installed package.

final PackageManager packageManager = context.getPackageManager();
final List<PackageInfo> packageList = packageManager.getInstalledPackages(PackageManager.GET_SIGNATURES);
CertificateFactory certFactory = null;
try {
    certFactory = CertificateFactory.getInstance("X509");
}
catch (CertificateException e) {
    // e.printStackTrace();
}

for (PackageInfo p : packageList) {
    String strName = p.applicationInfo.loadLabel(packageManager).toString();
    String strVendor = p.packageName;

    sb.append("<br>" + strName + " / " + strVendor + "<br>");

    Signature[] arrSignatures = p.signatures;
    for (Signature sig : arrSignatures) {
        /*
        * Get the X.509 certificate.
        */
        byte[] rawCert = sig.toByteArray();
        InputStream certStream = new ByteArrayInputStream(rawCert);

        X509Certificate x509Cert = null;
        try {
            x509Cert = (X509Certificate) certFactory.generateCertificate(certStream);
        }
        catch (CertificateException e) {
            // e.printStackTrace();
        }

        sb.append("Certificate subject: " + x509Cert.getSubjectDN() + "<br>");
        sb.append("Certificate issuer: " + x509Cert.getIssuerDN() + "<br>");
        sb.append("Certificate serial number: " + x509Cert.getSerialNumber() + "<br>");
        sb.append("<br>");
    }
}

Upvotes: 2

Related Questions