Android的APK应用签名机制以及读取签名的方法

2019-12-10 19:02:02王旭

3)证书的发行机构名称,命名规则一般采用X.500格式;
4)证书的有效期,通用的证书一般采用UTC时间格式,它的计时范围为1950-2049;
5)证书所有人的名称,命名规则一般采用X.500格式;
6)证书所有人的公开密钥;
7)证书发行者对证书的签名。
CERT.RSA包含了数字签名以及开发者的数字证书。CERT.RSA里的数字签名是指对CERT.SF的摘要采用私钥加密后的数据,Android系统安装apk时会对CERT.SF计算摘要,然后使用CERT.RSA里的公钥对CERT.RSA里的数字签名解密得到一个摘要,比较这两个摘要便可知道该apk是否有正确的签名,也就说如果其他人修改了apk并没有重新签名是会被检查出来的。
需注意Android平台的证书是自签名的,也就说不需要权威机构签发,数字证书的发行机构和所有人是相同的,都是开发者自己,开发者生成公私钥对后不需要提交到权威机构进行校验。

读取签名
某些时候需要获取某个特定的apk(已安装或者未安装)的签名信息,如程序自检测,可信赖的第三方检测(应用市场),系统限定安装  
对此,有两种实现方法  
可以使用Java自带的API(主要用到的为JarFile,JarEntry,Certificate)进行获取,还有一种方法是使用系统隐藏的API PackageParser,通过反射来使用对应的API.  
但是由于安卓系统的分裂版本过多,并且不同厂商进行的修改很多,依赖反射隐藏API的方法并不能保证兼容性和通用性,因此推荐使用JAVA自带API进行获取:  
  

 
  /** 
   * 从APK中读取签名 
   * @param file 
   * @return 
   * @throws IOException 
   */ 
  private static List<String> getSignaturesFromApk(File file) throws IOException { 
    List<String> signatures=new ArrayList<String>(); 
    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) { 
          String sig=toCharsString(c.getEncoded()); 
          signatures.add(sig); 
        } 
      } 
    } catch(Exception ex) { 
    } 
    return signatures; 
  } 

 /** 
   * 加载签名 
   * @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; 
  } 
 
/** 
   * 将签名转成转成可见字符串 
   * @param sigBytes 
   * @return 
   */ 
  private static String toCharsString(byte[] sigBytes) { 
    byte[] sig=sigBytes; 
    final int N=sig.length; 
    final int N2=N * 2; 
    char[] text=new char[N2]; 
    for(int j=0; j < N; j++) { 
      byte v=sig[j]; 
      int d=(v >> 4) & 0xf; 
      text[j * 2]=(char)(d >= 10 ? ('a' + d - 10) : ('0' + d)); 
      d=v & 0xf; 
      text[j * 2 + 1]=(char)(d >= 10 ? ('a' + d - 10) : ('0' + d)); 
    } 
    return new String(text); 
  }