我在C#中开发Windows服务,它调用webservice方法。我必须使用SSL连接到webservice。我已经从发布者p12文件中获得了证书。该文件受密码保护。使用Import方法使用此证书。一切都很好,但我不喜欢这种方法 - 我的应用程序中有密码编码。当发布者更改证书时,我必须重写代码(将密码更改为新密码)。有没有办法不将密码编码为.p12文件或使用其他选项(.cer文件)?
答案 0 :(得分:5)
你能做的是这样的事情:
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;
}
答案 1 :(得分:1)
提供PKCS#12文件,因为它是将证书与私钥一起传输的自然方式。您可以使用以下其中一项:
但是所有这些方法(连同保留硬编码密码)都没有为私钥提供真正的保护,因此如果您将应用程序分发到组织外部,则无法使用。