c# - 如何从 C# 调用带有客户端证书的 Web 服务?

标签 c# ssl-certificate

我已经从我的客户端安装了一个证书到我的电脑中,这是访问他们的网络服务所需要的。但是当我尝试从我的 C# Windows 服务访问 Web 服务时,我无法从代码中找到证书。 这是我的代码:

private X509Certificate findCertificate()
{
        X509Store store = new X509Store(StoreName.Root, StoreLocation.CurrentUser);
        store.Open(OpenFlags.ReadOnly);
        string certThumbprint = string.Empty;

        X509Certificate cert = new X509Certificate();
        for (int i = 0; i < store.Certificates.Count; i++)
        {
            certThumbprint = store.Certificates[i].Thumbprint.ToString().ToUpper();
            if (certThumbprint == "‎176455DB76886FF2BA3C122F8B36322F647CB2FD")//when debugging then debugger is not coming into this line even if it finds the thumbprint
            {
                cert = store.Certificates[i];
            }
        }
        return cert;
 }

此外,我正在尝试对 App.config 做同样的事情,但我遇到了错误:

invalid hexadecimal string format. inner exception null

这是我的 App.config

<?xml version="1.0" encoding="utf-8"?>
 <configuration>
 <system.serviceModel>
  <bindings>
   <customBinding>
     <binding name="PrivatmoneyPortBinding" >
        <security defaultAlgorithmSuite="Basic128" authenticationMode="MutualCertificate"
          requireDerivedKeys="false" includeTimestamp="true" messageProtectionOrder="SignBeforeEncrypt"  messageSecurityVersion="WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10"
          requireSignatureConfirmation="false">

            <localClientSettings cacheCookies="true" detectReplays="true"
                        replayCacheSize="900000" maxClockSkew="00:05:00" maxCookieCachingTime="00:05:00"
                        replayWindow="00:05:00" sessionKeyRenewalInterval="10:00:00"
                        sessionKeyRolloverInterval="00:05:00" reconnectTransportOnFailure="true"
                        timestampValidityDuration="00:05:00" cookieRenewalThresholdPercentage="60" />
                    <localServiceSettings detectReplays="true" issuedCookieLifetime="10:00:00"
                        maxStatefulNegotiations="128" replayCacheSize="900000" maxClockSkew="00:05:00"
                        negotiationTimeout="00:01:00" replayWindow="00:05:00" inactivityTimeout="00:02:00"
                        sessionKeyRenewalInterval="15:00:00" sessionKeyRolloverInterval="00:05:00"
                        reconnectTransportOnFailure="true" maxPendingSessions="128"
                        maxCachedCookies="1000" timestampValidityDuration="00:05:00" />
      </security>
                <textMessageEncoding maxReadPoolSize="64" maxWritePoolSize="16"
                    messageVersion="Default" writeEncoding="utf-8">
                    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                </textMessageEncoding>
                <httpsTransport manualAddressing="false" maxBufferPoolSize="524288"
                    maxReceivedMessageSize="65536" allowCookies="false" authenticationScheme="Anonymous"
                    bypassProxyOnLocal="false" decompressionEnabled="true"
                    keepAliveEnabled="true" maxBufferSize="65536" proxyAuthenticationScheme="Anonymous"
                    realm="" transferMode="Buffered" unsafeConnectionNtlmAuthentication="true"
                    useDefaultWebProxy="true" requireClientCertificate="true" />
    </binding>
  </customBinding>
</bindings>
<client>
    <endpoint address="https://pmtest.xxxx.xx:xxxx/xxxxx/xxxxx?wsdl" behaviorConfiguration="NewClientEPBehavior"
      binding="customBinding" bindingConfiguration="PrivatmoneyPortBinding"
      contract="PrivatMoney.PrivatmoneyPort" name="PrivatmoneyPort">
  </endpoint>
</client>
    <behaviors>
        <endpointBehaviors>
            <behavior name="NewClientEPBehavior">
                <clientCredentials>
                    <serviceCertificate>
          <authentication certificateValidationMode="PeerTrust" trustedStoreLocation="CurrentUser" />
                    </serviceCertificate>
                    <clientCertificate storeLocation="CurrentUser" storeName="Root" findValue="‎176455DB76886FF2BA3C122F8B36322F647CB2FD"  x509FindType="FindByThumbprint" />

      </clientCredentials>
            </behavior>
         </endpointBehaviors>
    </behaviors>
 </system.serviceModel>
</configuration>

最佳答案

我不知道你是怎么得到指纹的。在我的例子中,我从证书详细信息(来自 mmc 的 GUI)中选择了它。问题是我选择了更多。 开头有一些不可见的字符,当您将其粘贴到配置时不会显示。

选择除第一个字符以外的指纹并将其复制到剪贴板。在配置中输入第一个字符,然后从剪贴板粘贴其余字符。

关于c# - 如何从 C# 调用带有客户端证书的 Web 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46641357/

相关文章:

c# - 如何使用单页保护 Web API

c# - 为 C# 自动属性赋予初始值的最佳方法是什么?

c# - SplashScreen.Close(Timespan.FromMilliseconds(int)) : Is there an Event dispatched at Timespan Complete?

python - python中的这个ssl错误是什么意思?

security - bower 安装 self_signed_cert_in_chain

php - 测试不安全的结帐页面

c# - 通过 LINQ 创建匿名对象

ruby - ssl_verify_mode + bundler + geminabox

ssl - Certbot 自动配置后站点未启用 ssl

c# - 如何使用 LINQ 区分列表?