获取Android应用程序的证书指纹

时间:2014-04-07 15:00:49

标签: android security x509certificate

我是安卓Android的新手.. 我想获取Android应用程序的签名证书指纹的sha1, 我想得到相同的cmd结果:  keytool -v -list -keystore " PATH of key " -alias "alias of the key" -storpass " password" 我试过这段代码,但它给了我不同的结果

    android.content.pm.Signature[] sigs;
        try {
            sigs = this.getPackageManager().getPackageInfo(this.getPackageName(),
                    PackageManager.GET_SIGNATURES).signatures;

            byte[] cert = sigs[0].toByteArray();
                 InputStream input

 = new ByteArrayInputStream(cert);
             CertificateFactory cf = null;
        try {
                cf = CertificateFactory.getInstance("X509");


            } catch (CertificateException e) {
                    e.printStackTrace();
            }
            X509Certificate c = null;

            try {

                    c = (X509Certificate) cf.generateCertificate(input);
                    Signature signature=null;
    signature = Signature.getInstance("SHA1withRSA");
                         signature.initVerify(c.getPublicKey());
                            signature.update(cert);
                           System.out.println("signature"+ signature.sign());

1 个答案:

答案 0 :(得分:3)

My SignatureUtils class使用SHA-256(可通过Java 7 keytool 获得),并且值排成一行。因此,此方法应该为您提供SHA-1签名哈希:

  public static String getSignatureHash(Context ctxt, String packageName)
                                                                         throws NameNotFoundException,
                                                                         NoSuchAlgorithmException {
    MessageDigest md=MessageDigest.getInstance("SHA-1");
    Signature sig=
        ctxt.getPackageManager()
            .getPackageInfo(packageName, PackageManager.GET_SIGNATURES).signatures[0];

    return(toHexStringWithColons(md.digest(sig.toByteArray())));
  }

其中toHexStringWithColons()基于this StackOverflow answer

  public static String toHexStringWithColons(byte[] bytes) {
    char[] hexArray=
        { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',
            'C', 'D', 'E', 'F' };
    char[] hexChars=new char[(bytes.length * 3) - 1];
    int v;

    for (int j=0; j < bytes.length; j++) {
      v=bytes[j] & 0xFF;
      hexChars[j * 3]=hexArray[v / 16];
      hexChars[j * 3 + 1]=hexArray[v % 16];

      if (j < bytes.length - 1) {
        hexChars[j * 3 + 2]=':';
      }
    }

    return new String(hexChars);
  }

自SHA-1 is not a great hash algorithm anymore以来,由于您可以从 keytool 获取SHA-256,因此您可以考虑使用我的CWAC-Security库和{{1}直接。