2012-01-06 106 views
3

我正在開發調用webservice方法的C#中的Windows服務。我必須使用SSL連接到webservice。我已從發佈者p12文件中獲得證書。該文件受密碼保護。使用導入方法來使用此證書。一切工作正常,但我不喜歡這種方法 - 我的密碼在我的應用程序編碼。當發佈者更改證書時,我必須重寫代碼(將密碼更改爲新密碼)。有什麼辦法不把密碼合併到.p12文件或使用其他選項(.cer文件)?使用證書文件通過SSL連接到webservice

回答

1

提供PKCS#12文件給您,因爲它是將證書與私鑰一起傳輸的自然方式。您可以使用下列之一:

  • 將其轉換成格式化你喜歡和存儲你喜歡
  • 的方式將其轉換爲無密碼的PFX
  • 導入以計算機的證書存儲和使用這種方式

但是,所有這些方法(連同保留硬編碼密碼一起)都不提供對私鑰的實際保護,因此如果將應用程序分發到組織外部,則不可用。

5

你可以做的是這樣的:

  1. 安裝SSL證書導入到本地計算機證書存儲(使用Microsoft管理控制檯「MMC」)
  2. 提取證書指紋(如「748681ca3646ccc7c4facb7360a0e3baa0894cb5 「)
  3. 使用從給定指紋的本地證書存儲中獲取證書的函數。
  4. 調用Web服務時提供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; 
}