在VB.Net中使用pfx(客户端证书)从HTTPS连接下载文件

时间:2018-08-01 21:34:47

标签: c# vb.net ssl pfx

我尝试了许多不同的方法来完成此任务,但没有发现任何运气。我有一个pfx证书(客户端身份验证),可以访问我们受客户端保护的网站并下载每日报告(zip文件)。

当我尝试在Visual Studio 2013的脚本任务中使用C#/ VB.NET代码自动执行此操作时,出现错误消息

  

请求已中止:无法创建SSL / TLS安全通道。

我确定客户端证书包含私钥,公钥和其他必需的证书,因为当我尝试在IE中访问其网站时,它询问是否信任证书和繁荣,如果我说“确定”,我可以得到任何东西我想要。

感谢您的时间。非常感谢(请让我知道正确的方法是什么)

Public Sub Main()

    ServicePointManager.Expect100Continue = True
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3

    Dim mycert As New X509Certificate2("certificate.pfx", "password", X509KeyStorageFlags.MachineKeySet)


    Dim wr As HttpWebRequest = CType(WebRequest.Create("sourceurl.zip"), HttpWebRequest)
    wr.ClientCertificates.Add(mycert)


    Dim ws As HttpWebResponse = CType(wr.GetResponse(), HttpWebResponse)
    Dim str As Stream = ws.GetResponseStream()
    Dim inBuf(100000000) As Byte
    Dim bytesToRead As Integer = CInt(inBuf.Length)
    Dim bytesRead As Integer = 0
    While bytesToRead > 0
        Dim n As Integer = str.Read(inBuf, bytesRead, bytesToRead)
        If n = 0 Then
            Exit While
        End If
        bytesRead += n
        bytesToRead -= n
    End While
    Dim fstr As New FileStream("destination.zip", FileMode.OpenOrCreate, FileAccess.Write)
    fstr.Write(inBuf, 0, bytesRead)
    str.Close()
    fstr.Close()
    'Dts.TaskResult = ScriptResults.Success'

End Sub

0 个答案:

没有答案