java gets the signature summary of APK installed on the phone

  • 2020-05-05 11:12:50
  • OfStack

When publishing APK to the app store or accessing SDK of a third party, it is sometimes necessary to provide the signature summary information of APK. You can obtain the signature summary by the digest algorithm MD5 or SHA-1. Besides obtaining your own APK signature, you can also obtain other installed APK signatures on the phone.


private static final char[] HEX_CHAR = {
 
  '0', '1', '2', '3', '4', '5', '6', '7',
 
  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
 
};
 
/**  signed-in MD5 Abstract  */
 
public String[] signatureDigest() {
 
  pkgInfo = mContext.getPackageManager().getPackageInfo(
 
        mContext.getPackageName(), PackageManager.GET_SIGNATURES);
 
  int length = pkgInfo.signatures.length;
 
  String[] digests = new String[length];
 
  for (int i = 0; i < length; ++i) {
 
    Signature sign = mPkgInfo.signatures[i];
 
    try {
 
      MessageDigest md5 = MessageDigest.getInstance("MD5");
 
      byte[] digest = md5.digest(sign.toByteArray()); // get digest with md5 algorithm
 
      digests[i] = toHexString(digest);
 
    } catch (NoSuchAlgorithmException e) {
 
      e.printStackTrace();
 
      digests[i] = null;
 
    }
 
  }
 
  return digests;
 
}
 
/**  Converts a byte array to a corresponding hexadecimal string  */
 
private String toHexString(byte[] rawByteArray) {
 
  char[] chars = new char[rawByteArray.length * 2];
 
  for (int i = 0; i < rawByteArray.length; ++i) {
 
    byte b = rawByteArray[i];
 
    chars[i*2] = HEX_CHAR[(b >>> 4 & 0x0F)];
 
    chars[i*2+1] = HEX_CHAR[(b & 0x0F)];
 
  }
 
  return new String(chars);
 
}

The above is the entire content of this article, I hope to help you with your study.


Related articles: