Android gets the apk md5 Value
Android gets the apk md5 Value
1. Obtain Signature
2. Calculate md5 and sha1 Information Based on Signature and obtain the Signature public key information
TextView text = null;
StringBuffer sb = new StringBuffer ();
@ Override
Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. activity_main );
Text = (TextView) findViewById (R. id. text );
Try {
PackageInfo pi = getPackageManager (). getPackageInfo (getPackageName (), PackageManager. GET_SIGNATURES );
Signature signatures = pi. signatures [0];
MessageDigest md = MessageDigest. getInstance ("MD5 ");
Md. update (signatures. toByteArray ());
Byte [] digest = md. digest ();
String res = toHexString (digest );
Log. e (TAG, "apk md5 =" + res );
Sb. append ("apk md5 =" + res );
MessageDigest md2 = MessageDigest. getInstance ("SHA1 ");
Md2.update (signatures. toByteArray ());
Byte [] digest2 = md. digest ();
String res2 = toHexString (digest2 );
Log. e (TAG, "apk SHA1 =" + res2 );
Sb. append ("\ napk SHA1 =" + res2 );
ByteArrayInputStream bais = new ByteArrayInputStream (signatures. toByteArray ());
CertificateFactory cf = CertificateFactory. getInstance ("X.509 ");
X509Certificate cert = (X509Certificate) cf. generateCertificate (bais );
String sigAlgName = cert. getSigAlgName ();
String subjectDN = cert. getSubjectDN (). toString ();
Log. e (TAG, "sigAlgName =" + sigAlgName );
Log. e (TAG, "subjectDN =" + subjectDN );
Sb. append ("\ n sigAlgName =" + sigAlgName );
Sb. append ("\ n subjectDN =" + subjectDN );
Bais. close ();
} Catch (NameNotFoundException e ){
E. printStackTrace ();
} Catch (NoSuchAlgorithmException e ){
E. printStackTrace ();
} Catch (CertificateException e ){
E. printStackTrace ();
} Catch (IOException e ){
E. printStackTrace ();
}
Text. setText (sb. toString ());
}
Private void byte2hex (byte B, StringBuffer buf ){
Char [] hexChars = {'0', '1', '2', '3', '4', '5', '6', '7 ', '8 ',
'9', 'A', 'B', 'C', 'D', 'E', 'F '};
Int high = (B & 0xf0)> 4 );
Int low = (B & 0x0f );
Buf. append (hexChars [high]);
Buf. append (hexChars [low]);
}
/*
* Converts a byte array to hex string
*/
Private String toHexString (byte [] block ){
StringBuffer buf = new StringBuffer ();
Int len = block. length;
For (int I = 0; I <len; I ++ ){
Byte2hex (block [I], buf );
If (I <len-1 ){
Buf. append (":");
}
}
Return buf. toString ();
}