最近一个项目里需要得到Android已安装程序的签名文件(CERT.RSA)的SHA1值,所以就调研解压APK文件。
通过包名来得到已安装程序在系统的安装包路径。
private static String getApkPath(String pkgName) {
PackageManager pm = mContext.getPackageManager();
ApplicationInfo pi = null;
try {
pi = pm.getApplicationInfo(pkgName,PackageManager.GET_UNINSTALLED_PACKAGES);
if(pi != null)
return pi.sourceDir;
else
return null;
} catch (NameNotFoundException e) {
e.printStackTrace();
return null;
}
}
解压对应的APK包,得到需要的文件(.RSA)
public static void UnZip(String unzipfile){
try {
File zipFile = new File(unzipfile); //解压缩的文件路径(为了获取路径)
if(!zipFile.exists())
{
Log.i(TAG,"FILE !EXIST");
return ;
}
ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry entry;
while ( (entry = zin.getNextEntry()) != null){
if (!entry.isDirectory()) { //匹配文件,跳过文件夹
String filePath = entry.getName();
Pattern p = Pattern.compile(".*(RSA|DSA|rsa)$"); //匹配RSA后缀的文件
Matcher m = p.matcher(filePath);
if(m.matches())
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int count;
while ((count = zin.read(buffer)) != -1) {
baos.write(buffer, 0, count);
}
try {
String sha1 = Sha1.getSha1(baos);
Log.i(TAG, "Sha1:"+sha1+"");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}//while
zin.closeEntry();
}//try
catch (IOException e) {
e.printStackTrace();
}
}
主要就是通过ZipInputStream来读取对应文件,然后将该文件写到SD卡上,然后调用sha1方法读取该文件得到sha1值。
ZipInputStream类,比较重要,值得学习一下。
SDK里:
总结:ZipInputStream是InputStream的子类,通过此类可以方便地读取ZIP格式的压缩文件。
通过ZipInputStream类中的getNextEntry()方法可以依次取得每一个ZipEntry,那么将此类与ZipFile结合就可以对压缩的文件夹进行解压缩操作。但是需要注意的是,在mldndir.zip文件中本身是包含压缩的文件夹的,所以在进行解压缩前,应该先根据ZIP文件中的文件夹的名称在硬盘上创建好一个对应的文件夹,然后才能把文件解压缩进去,而且在操作时对于每一个解压缩的文件都必须先创建(File类的createNewFile()方法可以创建新文件)后再将内容输出。