私の C# アプリケーションでは、https 経由で Web サービスを呼び出し、既に持っている .crt ファイルを使用して検証する必要がありました。そのようなニーズに対する正しいソリューションがここにあります。私のような他の人に役立つかもしれないと考えて、実用的な解決策を得たら、この投稿を更新しました。
解決策 : 以下のコードは、アプリケーションの実行全体で 1 回だけ実行する必要があります。これにより、リクエストが呼び出されるたびに使用される ServerCertification および SSL プロパティを設定します。
public static void setSSLCertificate()
{
clientCert = new X509Certificate2(AUTHEN_CERT_FILE); // Pointing to the .crt file that will be used for server certificate verification by the client
System.Net.ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(customXertificateValidation);
}
public static bool customXertificateValidation(Object sender, X509Certificate certificate, X509Chain chain, System.Net.Security.SslPolicyErrors sslPoicyErrors)
{
switch (sslPoicyErrors)
{
case System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors:
case System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch:
case System.Net.Security.SslPolicyErrors.RemoteCertificateNotAvailable:
break;
}
return clientCert.Verify(); // Perform the Verification and sends the result
}
リクエストは、SSL を実装しない場合と同様に通常どおり行われます。投稿リクエストコードは次のとおりです。
private static String SendPost(String uri, String post_data)
{
String resData = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
// turn request string into byte[]
byte[] postBytes = Encoding.ASCII.GetBytes(post_data);
Stream requestStream = null;
try
{
// Send it
request.ContentLength = postBytes.Length;
requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
}
catch (WebException we)
{ // If SSL throws exception that will be handled here
if (we.Status == WebExceptionStatus.TrustFailure)
throw new Exception("Exception Sending Data POST : Fail to verify server " + we.Message);
}
catch (Exception e)
{
throw new Exception("Exception Sending Data POST : " + e.Message, e.InnerException);
}
finally
{
if (requestStream != null)
requestStream.Close();
}
// Get the response
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.GetResponse();
if (response == null)
return "";
StreamReader sr = new StreamReader(response.GetResponseStream());
resData = sr.ReadToEnd().Trim();
sr.Close();
}
catch (Exception e)
{
throw new Exception("Error receiving response from POST : " + e.Message, e.InnerException);
}
finally
{
if (response != null)
response.Close();
}
return resData;
}
サーバー証明書を受け入れることで、目標を大幅に達成するのに役立つ説明をしてくれた Dipti Mehta に感謝します。彼女は私の混乱を解決するのを手伝ってくれました。クライアントが .crt ファイルを使用してサーバー証明書を検証する方法をついに見つけました。
これが誰かに役立つことを願っています。
ありがとう