使用Signature.verify验证android应用程序签名失败

时间:2014-06-12 14:15:37

标签: java android security digital-signature

我一直在努力验证自己的应用程序签名已有一段时间但无法实现。我有以下代码

public static X509Certificate createCert (byte [] bytes) {
    X509Certificate certret = null;
    CertificateFactory cf = null;
    try {
        cf = CertificateFactory.getInstance("X.509");
        InputStream certStream = new ByteArrayInputStream(bytes);
        certret = (X509Certificate) cf.generateCertificate(certStream);
    } catch (CertificateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return certret;
}
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    android.content.pm.Signature[] sigs;
    try {
        sigs = this.getPackageManager().getPackageInfo(this.getPackageName(),PackageManager.GET_SIGNATURES).signatures;
        for (android.content.pm.Signature sig : sigs)
        {
            Log.i("App", "Signature String : " + sig.toString()); 
            Log.i("App", "Signature : " + sig.hashCode());
            X509Certificate cert = createCert(sig.toByteArray());
            java.security.Signature signat;
            try {
                signat = java.security.Signature.getInstance("SHA1withRSA");
                signat.initVerify(cert.getPublicKey());
                boolean ret;
                ret = signat.verify(sig.toByteArray());
                Log.e(TAG, "verify result = " + ret);
            } catch (NoSuchAlgorithmException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SignatureException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvalidKeyException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    } catch (NameNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

我引用了一些stackoverflow技巧,例如 android verify signature of file with .der public key How to get APK signing signature?

但我的验证总是返回false。

我不想在我的应用程序中使用openssl。如何通过编程方式验证我自己的应用程序证书。

0 个答案:

没有答案