java層獲取apk簽名MD5
阿新 • • 發佈:2019-09-14
public class getApkSign {
public static void main(String[] args) throws IOException, Exception {
String path = "E:\\android\\workspace\\trunk\\ccplay_2016\\CCPlay_Market\\build\\outputs\\apk\\CCPlay_Market-debug.apk";// apk的路徑
byte[] bytes = getSignaturesFromApk(path);
System.out.println(hexDigest(bytes));
}
public static String hexDigest(byte[] bytes) {
MessageDigest md5;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (Exception e) {
e.printStackTrace();
return "";
}
byte[] md5Bytes = md5.digest(bytes);
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++) {
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16)
hexValue.append("0");
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
}
/**
* 從APK中讀取簽名
*
* @param file
* @return
* @throws IOException
*/
private static byte[] getSignaturesFromApk(String strFile) throws IOException {
File file = new File(strFile);
JarFile jarFile = new JarFile(file);
try {
JarEntry je = jarFile.getJarEntry("AndroidManifest.xml");
byte[] readBuffer = new byte[8192];
Certificate[] certs = loadCertificates(jarFile, je, readBuffer);
if (certs != null) {
for (Certificate c : certs) {
return c.getEncoded();
}
}
} catch (Exception ex) {
}
return null;
}
/**
* 載入簽名
*
* @param jarFile
* @param je
* @param readBuffer
* @return
*/
private static Certificate[] loadCertificates(JarFile jarFile, JarEntry je, byte[] readBuffer) {
try {
InputStream is = jarFile.getInputStream(je);
while (is.read(readBuffer, 0, readBuffer.length) != -1) {
}
is.close();
return je != null ? je.getCertificates() : null;
} catch (IOException e) {
}
return null;