如何信任自签名证书并将其添加到httpclient

时间:2019-04-03 23:29:15

标签: c# ssl certificate x509

我有一个Windows窗体应用程序(客户端),我需要它来信任服务器的证书并将其自己的证书添加到请求中。 我已经在Android(Java)中做到了,但是尝试在C#上实现时遇到了困难。

在Android Studio(Java)上,我使用了以下方法:

private OkHttpClient initClient() throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, UnrecoverableKeyException, KeyManagementException {

    // Trust self signed certificate
    InputStream certificateFileCRT = mContext.getResources().openRawResource(R.raw.server);
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(certificateFileCRT);
    String alias = cert.getSubjectX500Principal().getName();
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null);
    trustStore.setCertificateEntry(alias, cert);

    // KeyStore containing client certificate
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    InputStream fis = mContext.getResources().openRawResource(R.raw.client);
    keyStore.load(fis, "password".toCharArray());

    // Build an SSL context
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
    kmf.init(keyStore, "password".toCharArray());
    KeyManager[] keyManagers = kmf.getKeyManagers();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
    tmf.init(trustStore);
    TrustManager[] trustManagers = tmf.getTrustManagers();

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

    return new OkHttpClient.Builder()
            .readTimeout(60, TimeUnit.SECONDS)
            .sslSocketFactory(sslContext.getSocketFactory())
            .hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            })
            .build();

}

现在,我有此代码。我想我只需要将客户端的证书添加到HttpClient中即可。

X509Certificate x509Certificate = new X509Certificate2("server.pfx", "password");

WebRequestHandler clientHandler = new WebRequestHandler();
clientHandler.ClientCertificates.Add(x509Certificate);

HttpClient client = new HttpClient(clientHandler);

try
{
    HttpContent content = loginJSON;
    HttpResponseMessage responseMessage = await client.PostAsync(SERVER_ADMIN_URL + LOGIN_PATH, content);
    Console.WriteLine("\n" + responseMessage.StatusCode);
    responseMessage.EnsureSuccessStatusCode();
    responseBody = await responseMessage.Content.ReadAsStringAsync();
}
catch (HttpRequestException e)
{
    Console.WriteLine(e.StackTrace);
    responseBody = "An error occured while sending the request to the server";
}

我认为我可以允许服务器的证书(自签名)。我的问题是我想将客户的证书发送到服务器。

0 个答案:

没有答案