在android中的ssl握手期间无法附加客户端证书

时间:2014-09-23 13:23:04

标签: android ssl

在我的应用程序中,我需要实现双向握手。 以下是我正在使用的以下代码:

 public static SSLContext getSSLContext() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, CertificateException, NotFoundException, IOException, UnrecoverableKeyException{
    KeyStore clientCertificateKeysKeyStore = getClientCertificateKeystore();    
    KeyStore trustStore = getServerCertificateKeystore();
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(X509);    

    if(clientCertificateKeysKeyStore != null)
        kmf.init(clientCertificateKeysKeyStore, "cleint".toCharArray());
    KeyManager[] keyManagers = kmf.getKeyManagers();


//  TrustManager[] trustManagers = {new CustomTrustManager(trustStore)};
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(X509);
    tmf.init(trustStore);

    TrustManager[] trustManagers = tmf.getTrustManagers();

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagers, trustManagers, null);
    return sslContext;

}

我有一个PEM文件,我必须从中生成密钥库。

private KeyStore loadPEMKeystoreStore(File certificateFile) throws Exception {
        InputStream caInput = new BufferedInputStream(new FileInputStream(certificateFile));
        byte[] der = loadPemCertificate(caInput);
        ByteArrayInputStream derInputStream = new ByteArrayInputStream(der);
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(derInputStream);
        String alias = cert.getSubjectX500Principal().getName();

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore .load(null);
        keyStore .setCertificateEntry(alias, cert);

        return keyStore ;
    }

服务器证书是本地存储的.pk12证书。

问题是握手过程中未附加客户端证书。 我使用wireshark来分析数据包,它显示客户端证书长度为0.

如果我使用.pk12文件作为客户端证书,则会正确附加。 但我必须使用PEM文件。 任何解决方案!!

1 个答案:

答案 0 :(得分:0)

PEM文件仅包含证书而非私钥。这是更新的代码,工作正常。

  private KeyStore loadPEMKeystoreStore(File certificateFile, String password) throws Exception {
        InputStream caInput = new BufferedInputStream(new FileInputStream(certificateFile));


        KeyStore keystore = KeyStore.getInstance(CLIENT_CERTIFICATE_KEYSTORE_TYPE);


        CertificateFactory certificateFactory = CertificateFactory
                .getInstance(X509);
        X509Certificate cert = (X509Certificate) certificateFactory
                .generateCertificate(caInput);


        keystore.load(null);
        keystore.setCertificateEntry("cert-alias", cert);
        keystore.setKeyEntry("key-alias", privateKey, password.toCharArray(),
                new Certificate[]{cert});
        FileOutputStream out = new FileOutputStream(file);
        keystore.store(out, password.toCharArray());

        return keyStore ;
    }