在以下Android应用程序代码中,服务器正在为连接Android客户端提供自签名证书。也就是说,我已经用我自己的CA签署了服务器证书。该证书将使用CA的公钥进行验证,该公钥是从位于 / raw 中的名为 trust_store_ca 的文件中获取的。问题是如果我使用不同的证书(用不同的CA签名,即),验证步骤不会抛出相应的SignatureException。我已经在NetBeans中测试了代码,它确实抛出了上述异常。但是,在AndroidStudio中 IT不会。问题可能是什么?
KeyStore ts = KeyStore.getInstance("BKS");
InputStream trustin = v.getResources().openRawResource(R.raw.trust_store_ca);
ts.load(trustin, "MyKey".toCharArray());
// Create own trustmanager with self-signed cert.
final TrustManagerFactory tmf = TrustManagerFactory.
getInstance(KeyManagerFactory.getDefaultAlgorithm());
//tmf.init((KeyStore) null);
tmf.init(ts);
trustManagers = tmf.getTrustManagers();
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream cA_certificate = v.getResources().openRawResource(R.raw.ca_certif);
final X509Certificate caCertificate = (X509Certificate)cf
.generateCertificate(cA_certificate);
// Check server certificate is valid
final X509TrustManager origTrustmanager = (X509TrustManager)trustManagers[0];
wrappedTrustManagers = new TrustManager[]{
new X509TrustManager() {
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return origTrustmanager.getAcceptedIssuers();
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {//Not used}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType)
throws CertificateException{
if (certs == null || certs.length == 0) {
throw new IllegalArgumentException(
"checkServerTrusted: null or zero-length certificate chain");
}
if (authType == null || authType.length() == 0) {
throw new IllegalArgumentException(
"checkServerTrusted: null or zero-length authentication type");
}
// This does not work in Android, at least from me in JB...
//
// try {
// certs[0].verify(caCertificate.getPublicKey(), "BC");
// Log.i(TAG,"Pubkey for caCertificate: "+ caCertificate.getPublicKey());
// } catch (CertificateException | NoSuchAlgorithmException |
// NoSuchProviderException | InvalidKeyException | SignatureException e)
// {Log.i(TAG,"Certificate verification exception" + e);}
//
// Do signature verification by decrypting it and comparing to expected
// value (01FFFFFFFFFFFFFFF.....FFFFFF003021300906052B0E03021A05 000414... etc)
byte[] signature = certs[0].getSignature(); // signature in server's certif.
BigInteger exp = new BigInteger("010001",16); // 65537 as usual
BigInteger decrypt_sign = new BigInteger(1, signature).modPow(exp, ca_pubkey.getModulus());
System.out.println("Signature after decryption: " +decrypt_sign);
编辑:我正在覆盖验证过程,因为它没有检测到假证书。请参阅我的代码版,现在只需检查已解密的值。
见:
http://www.moserware.com/2009/06/first-few-milliseconds-of-https.html
获得出色的解释。
此外,向所有帮助过的人致意。 :)
答案 0 :(得分:1)
这可能与您正在进食(捕捉而非重新投掷){... 1}}
引发的一系列例外事实有关。