c# - 使用证书文件通过 SSL 连接到 Web 服务

标签 c# .net ssl windows-services ssl-certificate

我正在用 C# 开发调用 web 服务方法的 Windows 服务。我必须使用 SSL 连接到网络服务。我已经从发布者处收到带有证书的 p12 文件。该文件受密码保护。要使用 Import 方法来使用此证书。一切正常,但我不喜欢这种方法——我的应用程序中有硬编码密码。当发布者更改证书时,我必须重写代码(将密码更改为新密码)。有没有办法不将密码硬编码到 .p12 文件或使用其他选项(.cer 文件)?

最佳答案

你可以做的是这样的:

  1. 将 SSL 证书安装到本地计算机证书存储区(使用 Microsoft 管理控制台“MMC”)
  2. 提取证书指纹(例如“748681ca3646ccc7c4facb7360a0e3baa0894cb5”)
  3. 使用一个函数从本地证书存储中获取给定指纹的证书。
  4. 调用网络服务时提供 SSL 证书。
private static X509Certificate2 GetCertificateByThumbprint(string certificateThumbPrint, StoreLocation certificateStoreLocation) {
    X509Certificate2 certificate = null;

    X509Store certificateStore = new X509Store(certificateStoreLocation);
    certificateStore.Open(OpenFlags.ReadOnly);


    X509Certificate2Collection certCollection = certificateStore.Certificates;
    foreach (X509Certificate2 cert in certCollection)
    {
        if (cert.Thumbprint != null && cert.Thumbprint.Equals(certificateThumbPrint, StringComparison.OrdinalIgnoreCase))
        {
            certificate = cert;
            break;
        }
    }

    if (certificate == null)
    {
        Log.ErrorFormat(CultureInfo.InvariantCulture, "Certificate with thumbprint {0} not found", certificateThumbPrint);
    }

    return certificate;
}

public string GetServiceResponse() {
    string WebSvcEndpointConfigurationName = "WebServiceEndpoint";
    Uri webSvcEndpointAddress = new Uri("http://www.example.com/YourWebService.svc");
    string webSvcCertificateThumbPrint = "748681ca3646ccc7c4facb7360a0e3baa0894cb5";

    string webSvcResponse = null;
    SomeWebServiceClient webServiceClient = null;

    try
    {
        webServiceClient = new SomeWebServiceClient(WebSvcEndpointConfigurationName, new EndpointAddress(webSvcEndpointAddress));
        webServiceClient.ClientCredentials.ClientCertificate.Certificate = GetCertificateByThumbprint(webSvcCertificateThumbPrint, StoreLocation.LocalMachine);

        webSvcResponse = webServiceClient.GetServiceResponse();
    }
    catch (Exception ex)
    {
    }
    finally
    {
        if (webServiceClient != null)
        {
            webServiceClient.Close();
        }
    }
    return webSvcResponse;
} 

关于c# - 使用证书文件通过 SSL 连接到 Web 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8758442/

相关文章:

c# - 逐步将 WebForm VB Web 应用程序转换为 MVC C#

c# - 字符串操作

.net - 有什么办法可以在基本的T4模板中提供功能吗?

c# - .NET 类重构困境

.net - 知名 GUID 列表

web-services - java webservice客户端中的握手异常

ruby - 禁用 Ruby net/http 的 SNI 扩展 - 将 IP 地址与 SSL/TLS 结合使用

c# - 如何将一行gridview的客户端id发送到javascript

c# - 多维数组与字典性能

ruby-on-rails - 使用 Heroku 和 CloudFront 从 RapidSSL 获得的 SSL 证书