使用dotnet中的ssl进行双向身份验证

时间:2010-12-14 21:45:00

标签: vb.net authentication ssl-certificate two-way ssl-security

我有一个项目,我需要通过Web请求发送数据文件。我们需要设置双向身份验证,也称为相互身份验证。我们不确定是否需要特殊证书,但我们知道它需要达到3级。

我无法找到此案例的示例代码。我不知道在哪里添加我们的证书信息。使用此代码时,当我们尝试读取响应流并且永远不会调用Underlying connection is closed时,会引发ServicePointManager.ServerCertificateValidationCallback错误。这就是我所拥有的:

ServicePointManager.ServerCertificateValidationCallback = New Security.RemoteCertificateValidationCallback(AddressOf MyCertValidationCb)
            httpReq = CType(System.Net.HttpWebRequest.Create(url), HttpWebRequest)
            For Each cert As String In certs
                X509cert = X509Certificate2.CreateFromCertFile(cert)
                X509cert2 = New X509Certificate2(X509cert)
                httpReq.ClientCertificates.Add(X509cert2)
            Next
            httpReq.Method = "POST"        ' Post method
            httpReq.ContentType = "text/xml"               ' content type

            ' Wrap the request stream with a text-based writer
            writer = New StreamWriter(httpReq.GetRequestStream())
            ' Write the XML text into the stream
            reader = New StreamReader(filename.Name)
            ret = reader.ReadToEnd()
            reader.Close()
            ' Send the data to the webserver
            writer.WriteLine(ret)
            writer.Close()
            ' Wait for response
            Dim httpRsp As System.Net.HttpWebResponse = CType(httpReq.GetResponse(), HttpWebResponse)
            sr = New StreamReader(httpRsp.GetResponseStream)
            responseText = sr.ReadToEnd

            If httpReq IsNot Nothing Then
                httpReq.GetRequestStream().Close()
            End If
            If httpRsp IsNot Nothing Then
                httpRsp.GetResponseStream().Close()
            End If

带有示例代码的博客的任何提示或链接都会很棒。 感谢。

1 个答案:

答案 0 :(得分:1)

您不需要“特殊”证书。您的客户端需要自己的证书,并在连接中使用它来告诉服务器其身份。这称为客户证书。服务器应该正确处理。

以下MSDN文章讨论了如何设置ClientCertificate: http://msdn.microsoft.com/en-us/library/ms732391.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2