.net 无法在Windows 10 1809中使用证书通过com互操作登录到网站

.net 无法在Windows 10 1809中使用证书通过com互操作登录到网站,.net,excel,vba,https,com-interop,.net,Excel,Vba,Https,Com Interop,下面的C代码登录到一个网站 通过com互操作从Excel 2010 VBA在计算机上调用时工作 从C#控制台应用程序在计算机B上调用时工作,但 通过com互操作从Excel 2010 VBA在计算机B上调用时失败 计算机A和计算机B之间的主要区别在于计算机A具有windows 10版本1803,而计算机B具有windows 10版本1809。这两台计算机都有Studio 2017,在所有情况下,目标.Net Framework都是4.6.2 using System; using Syste

下面的C代码登录到一个网站

  • 通过com互操作从Excel 2010 VBA在计算机上调用时工作
  • 从C#控制台应用程序在计算机B上调用时工作,但
  • 通过com互操作从Excel 2010 VBA在计算机B上调用时失败
计算机A和计算机B之间的主要区别在于计算机A具有windows 10版本1803,而计算机B具有windows 10版本1809。这两台计算机都有Studio 2017,在所有情况下,目标.Net Framework都是4.6.2

using System;
using System.Runtime.InteropServices;
using System.IO;

[Guid("97E1D9DB-8478-4E56-9D6D-26D8EF13B100")]
[ComVisible(true)]
public interface IToExcel {
    string Do();
}

[Guid("BBF87E31-77E2-46B6-8093-1689A144BFC6")]
[ClassInterface(ClassInterfaceType.None)]
[ComVisible(true)]
public class Main : IToExcel {
    private const string XAPP_ID = "...";
    private const string USERNAME = "...";
    private const string PASSWORD = "...";
    private const string CERT_FILE = @"...";
    private const string CERT_PASSWORD = "...";
    private const string WEBSITE = "https:// ...";

    public string Do() {
        System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(new Uri(WEBSITE));
        request.AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate;
        request.Method = "POST";
        request.Accept = "application/json";
        request.Timeout = request.ReadWriteTimeout = 20000;
        request.ContentType = "application/x-www-form-urlencoded";
        request.UseDefaultCredentials = true;
        request.Proxy = null;
        // setup headers
        System.Net.WebHeaderCollection whc = new System.Net.WebHeaderCollection {
            { "X-Application", XAPP_ID },
            { System.Net.HttpRequestHeader.AcceptCharset, "utf-8" },
            { System.Net.HttpRequestHeader.AcceptEncoding, "gzip,deflate" }
        };
        request.Headers.Add(whc);
        // setup certificate
        System.Security.Cryptography.X509Certificates.X509Certificate2 m_x509certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(CERT_FILE, CERT_PASSWORD);
        request.ClientCertificates.Add(m_x509certificate);
        // do call
        using (Stream stream = request.GetRequestStream()) {
            using (StreamWriter writer = new StreamWriter(stream, System.Text.Encoding.Default)) {
                writer.Write("username=" + USERNAME + "&password=" + PASSWORD);
            }
        }
        string responseData = string.Empty;
        using (System.Net.WebResponse response = request.GetResponse()) {
            using (Stream responseStream = response.GetResponseStream()) {
                using (StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8)) {
                    responseData = reader.ReadToEnd();
                }
            }
        }
        return responseData;
    }

}
在所有情况下,都会返回一个小JSON对象,其中JSON对象有一个名为“loginStatus”的字段。当它工作时,“loginStatus”=“SUCCESS”,但当它失败时,“loginStatus”=“CERT\u AUTH\u REQUIRED”

我尝试查看System.Net.ServicePointManager中的所有设置,但在所有情况下,设置都是相同的:

  • 重用端口:False
  • ServerCertificateValidationCallback:
  • DnsRefreshTimeout:120000
  • EnableDnsRoundRobin:False
  • 期望值:正确
  • UseNagleAlgorithm:正确
  • MaxServicePointIdleTime:100000
  • DefaultConnectionLimit:2
  • MaxServicePoints:0
  • 安全协议:Tls、Tls11、Tls12
  • CheckCertificateResortionList:False
  • 加密策略:要求重新加密
除此之外,我不知道还要检查什么。从.NET4.6.2升级到4.7.1没有效果,结果是一样的

我想知道这是否是Windows1809中的一个bug,但由于它在.Net控制台应用程序中直接调用时可以工作,所以我认为这是一个微妙的配置问题。有人能帮我在计算机B上使用Excel 2010吗

更新日期:2019年2月8日

正如评论中所建议的那样,我使用Fiddler来查看对该网站进行的https调用的结构。工作的两个看起来相同,失败的一个看起来略有不同:

我觉得这工作还可以

  • TLS扩展ec_点_格式=未压缩[0x0]
  • 未指定TLS扩展加密\u then\u mac(RFC7366)
  • TLS扩展重新协商_info=0
  • 密码TLS\u空\u重新协商\u信息\u未指定SCSV
失败的呼叫

  • TLS扩展ec_point_formats=未压缩[0x0],ansiX962_压缩_prime[0x1],ansiX962_压缩_char2[0x2]
  • TLS扩展加密\u然后\u mac(RFC7366)=空
  • 未指定TLS扩展重新协商\u信息
  • 指定密码TLS\u空\u重新协商\u信息\u SCSV
但现在我有了这些信息,我不确定它是否有用。可能工作的调用都是由相同的低级代码生成的(尽管它们在不同版本的Windows 10上),而失败的调用是由不同的低级代码生成的

更新日期:2019年2月10日

通过com互操作从Excel调用时,我让代码在新的AppDomain中执行EXE,而不是直接调用登录代码。当我这样做时,EXE无法工作,并且产生了与我直接调用登录代码相同的输出

下面是一些VisualStudio输出窗口,其中显示了在登录代码执行之前,EXE文件运行时加载DLL的顺序。成功的方案和失败的方案之间最大的区别在于,失败的方案从不加载C:\Windows\System32\ncryptprov.dll。有人知道是什么导致加载该DLL吗

(Win32):已加载“C:\Windows\System32\msisip.dll”

(Win32):加载了“C:\Windows\System32\coml2.dll”-以前从EXCEL加载

(Win32):加载了“C:\Windows\System32\wshext.dll”

(Win32):已加载“C:\Windows\System32\AppxSip.dll”

(Win32):已加载“C:\Windows\System32\tdh.dll”

(Win32):已加载“C:\Windows\System32\xmllite.dll”

(Win32):已加载“C:\Windows\System32\OpcServices.dll”

(Win32):已加载“C:\Windows\System32\mintdh.dll”

(Win32):加载了“C:\Windows\System32\urlmon.dll”-以前从EXCEL加载

(Win32):已加载“C:\Windows\System32\mintdh.dll”

(Win32):已卸载“C:\Windows\System32\mintdh.dll”

(Win32):加载了“C:\Windows\System32\iertutil.dll”-以前从EXCEL加载

(Win32):已加载“C:\Windows\System32\WindowsPowerShell\v1.0\pwrshsip.dll”

(Win32):加载了“C:\Windows\System32\EsdSip.dll”

(Win32):加载了“C:\Windows\System32\userenv.dll”-以前从EXCEL加载

(Win32):已加载“C:\Windows\System32\dpapi.dll”

(Win32):已加载“C:\Windows\System32\dnsapi.dll”

(Win32):已加载“C:\Windows\System32\rasadhlp.dll”

(Win32):已加载“C:\Windows\System32\FWPUCLNT.DLL”

(Win32):已加载“C:\Windows\System32\secur32.dll”

(Win32):加载了“C:\Windows\System32\sspicli.dll”-以前从EXCEL加载

(Win32):已加载“C:\Windows\System32\schannel.dll”

(Win32):已加载“C:\Windows\System32\mskeyprotect.dll”

(Win32):已加载“C:\Windows\System32\ncrypt.dll”

(Win32):已加载“C:\Windows\System32\ntasn1.dll”

(Win32):已加载“C:\Windows\System32\ncryptprov.dll”-从未从EXCEL加载

(Win32):已加载“C:\Windows\System32\ncryptsslp.dll”

此时,C#代码将执行

更新日期:2019年2月12日

非常感谢您告诉我如何设置System.Net diagnostics。在计算机B上运行诊断时,两种情况下获得输出的“System.Net information”行开始时相同,但最终会有所不同。这是计算机B上控制台EXE文件的输出(即有效的案例):

System.Net信息:0:[35268]当前操作系统安装类型为“客户端”。
系统.Net信息:0:[35268]支持的RAS:True
系统.Net信息:0:
System.Net Information: 0 : [35268] Current OS installation type is 'Client'.
System.Net Information: 0 : [35268] RAS supported: True
System.Net Information: 0 : [35268] Associating HttpWebRequest#21454193 with ServicePoint#34640832
System.Net Information: 0 : [35268] Associating Connection#43332040 with HttpWebRequest#21454193
System.Net Information: 0 : [35268] Connection#43332040 - Created connection from XXX.XXX.XXX.XXX:53002 to YYY.YYY.YYY.YYY:443.
System.Net Information: 0 : [35268] TlsStream#54444047::.ctor(host=<TargetWebSite>, #certs=1, checkCertificateRevocationList=False, sslProtocols=Tls12)
System.Net Information: 0 : [35268] Associating HttpWebRequest#21454193 with ConnectStream#20234383
System.Net Information: 0 : [35268] HttpWebRequest#21454193 - Request: POST /api/certlogin HTTP/1.1
System.Net Information: 0 : [35268] ConnectStream#20234383 - Sending headers
System.Net Information: 0 : [35268] SecureChannel#47891719::.ctor(hostname=<TargetWebSite>, #clientCertificates=1, encryptionPolicy=RequireEncryption)
System.Net Information: 0 : [35268] Enumerating security packages:
System.Net Information: 0 : [35268]     Negotiate
System.Net Information: 0 : [35268]     NegoExtender
System.Net Information: 0 : [35268]     Kerberos
System.Net Information: 0 : [35268]     NTLM
System.Net Information: 0 : [35268]     TSSSP
System.Net Information: 0 : [35268]     pku2u
System.Net Information: 0 : [35268]     CloudAP
System.Net Information: 0 : [35268]     WDigest
System.Net Information: 0 : [35268]     Schannel
System.Net Information: 0 : [35268]     Microsoft Unified Security Protocol Provider
System.Net Information: 0 : [35268]     Default TLS SSP
System.Net Information: 0 : [35268]     CREDSSP
System.Net Information: 0 : [35268] SecureChannel#47891719 - Attempting to restart the session using the user-provided certificate: [Version]
System.Net Information: 0 : [35268] SecureChannel#47891719 - Left with 1 client certificates to choose from.
System.Net Information: 0 : [35268] SecureChannel#47891719 - Trying to find a matching certificate in the certificate store.
System.Net Information: 0 : [35268] SecureChannel#47891719 - Locating the private key for the certificate: [Version]
System.Net Information: 0 : [35268] SecureChannel#47891719 - Certificate is of type X509Certificate2 and contains the private key.
System.Net Information: 0 : [35268] SecureChannel#47891719::.AcquireClientCredentials, new SecureCredential() (flags=(ValidateManual, NoDefaultCred, SendAuxRecord, UseStrongCrypto), m_ProtocolFlags=(Tls12Client), m_EncryptionPolicy=RequireEncryption)
System.Net Information: 0 : [35268] AcquireCredentialsHandle(package = Microsoft Unified Security Protocol Provider, intent  = Outbound, scc     = System.Net.SecureCredential)
System.Net Information: 0 : [35268] InitializeSecurityContext(credential = System.Net.SafeFreeCredential_SECURITY, context = (null), targetName = <TargetWebSite>, inFlags = ReplayDetect, SequenceDetect, Confidentiality, AllocateMemory, InitManualCredValidation)
System.Net Information: 0 : [35268] InitializeSecurityContext(In-Buffer length=0, Out-Buffer length=184, returned code=ContinueNeeded).
System.Net Information: 0 : [35268] InitializeSecurityContext(credential = System.Net.SafeFreeCredential_SECURITY, context = 227c85a89b0:2449d0deff0, targetName = <TargetWebSite>, inFlags = ReplayDetect, SequenceDetect, Confidentiality, AllocateMemory, InitManualCredValidation)
System.Net Information: 0 : [35268] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=CredentialsNeeded).
System.Net Information: 0 : [39988] InitializeSecurityContext(credential = System.Net.SafeFreeCredential_SECURITY, context = (null), targetName = <TargetWebSite>, inFlags = ReplayDetect, SequenceDetect, Confidentiality, AllocateMemory, InitManualCredValidation)
System.Net Information: 0 : [39988] InitializeSecurityContext(In-Buffer length=0, Out-Buffer length=184, returned code=ContinueNeeded).
System.Net Information: 0 : [39988] InitializeSecurityContext(credential = System.Net.SafeFreeCredential_SECURITY, context = 8a8e2f0:2449d0def90, targetName = <TargetWebSite>, inFlags = ReplayDetect, SequenceDetect, Confidentiality, AllocateMemory, InitManualCredValidation)
System.Net Information: 0 : [39988] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=ContinueNeeded).
System.Net Information: 0 : [39988] InitializeSecurityContext(credential = System.Net.SafeFreeCredential_SECURITY, context = 8a8e2f0:2449d0def90, targetName = <TargetWebSite>, inFlags = ReplayDetect, SequenceDetect, Confidentiality, AllocateMemory, InitManualCredValidation)
System.Net Information: 0 : [39988] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=ContinueNeeded).
System.Net Information: 0 : [35268] Remote certificate: [Version] V3
[ Lots of lines describing a certificate with [Subject]=<TargetWebSite>, [Issuer]=HydrantID SSL ICA G2, etc]
System.Net Information: 0 : [35268] SecureChannel#47891719 - Remote certificate was verified as valid by the user.    
System.Net Information: 0 : [39988] Remote certificate: [Version] V3
[ Lots of lines describing a certificate with [Subject]=<TargetWebSite>, [Issuer]=Kaspersky, etc]
System.Net Information: 0 : [39988] SecureChannel#2383799 - Remote certificate was verified as valid by the user.