0

How can I get certificate sha256 hash of another application installed on android device? I am using solution mentioned in How to get APK signing signature?. But it is giving signature that does not seems to be certificate hash.

Community
  • 1
  • 1
Ammad
  • 21
  • 8

2 Answers2

3

Despite the name, that is the public portion of the certificate.

My CWAC-Security library has a SignatureUtils class with a getSignatureHash() method that calculates the SHA-256 hash of this information. The results are the same as if you used Java's keytool to dump the hash from the keystore.

The core code is fairly short:

public static String getSignatureHash(Context ctxt, String packageName)
  throws NameNotFoundException, NoSuchAlgorithmException {
    MessageDigest md=MessageDigest.getInstance("SHA-256");
    Signature sig=
        ctxt.getPackageManager()
            .getPackageInfo(packageName, PackageManager.GET_SIGNATURES).signatures[0];

    return(toHexStringWithColons(md.digest(sig.toByteArray())));
  }

  // based on https://stackoverflow.com/a/2197650/115145

  public static String toHexStringWithColons(byte[] bytes) {
    char[] hexArray=
        { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',
            'C', 'D', 'E', 'F' };
    char[] hexChars=new char[(bytes.length * 3) - 1];
    int v;

    for (int j=0; j < bytes.length; j++) {
      v=bytes[j] & 0xFF;
      hexChars[j * 3]=hexArray[v / 16];
      hexChars[j * 3 + 1]=hexArray[v % 16];

      if (j < bytes.length - 1) {
        hexChars[j * 3 + 2]=':';
      }
    }

    return new String(hexChars);
  }
CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
0

You can try something like this:

    PackageManager packageManager = getPackageManager();
    int flag = PackageManager.GET_SIGNATURES;

    PackageInfo packageInfo = null;
        try {
            packageInfo = packageManager.getPackageInfo(packageName, flag);

            byte[] certificates = packageInfo.signatures[0].toByteArray();
            InputStream input = new ByteArrayInputStream(certificates);
            CertificateFactory factory = CertificateFactory.getInstance("X509");
            X509Certificate certificate = (X509Certificate) factory.generateCertificate(input);

            MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
            byte[] publicKey = messageDigest.digest(certificate.getEncoded());

        } catch (PackageManager.NameNotFoundException exception) {
            exception.printStackTrace();
        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e2) {
            e2.printStackTrace();
        }
Aurelian Cotuna
  • 3,076
  • 3
  • 29
  • 49