如何使用在.NET WebRequest的一个PKCS#12证书文件?
-
21-08-2019 - |
题
我已经发出用于访问一个简单的基于XML的web服务一个PKCS#12的证书。当我加载PKCS#12文件到Windows(Vista)的,我可以用我的浏览器访问该服务。
试图通过应用程序来访问该服务,而无需加载PKCS#12到OS证书集合,我已经写以下代码:
// The certificate i'm using can not be authenticated as it is a development one.
// For now, just ignore it.
static bool myRemoteCertificateValidationCallback(
Object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors
)
{ return true; }
static void Main(string[] args)
{
ServicePointManager.ServerCertificateValidationCallback = myRemoteCertificateValidationCallback;
X509Certificate Cert = new X509Certificate(@"certificatefile.p12","medialab");
HttpWebRequest Req = (HttpWebRequest)WebRequest.Create("https://ServiceURL");
Req.ClientCertificates.Add(Cert);
Stream S = Req.GetResponse().GetResponseStream();
TextReader TR = new StreamReader(S);
string Ret = TR.ReadToEnd();
Console.Write(Ret);
}
不幸的是此代码失败,我得到一个System.Net.WebException:请求被中止:无法创建SSL / TLS安全通道。我注意到,当我加载PKCS#12文件到Windows,代码突然工作。
什么我需要做的,凑合着用单独的文件,并避免使用Windows证书存储区?
谢谢, 波阿斯
更多信息:刚刚申请SP1到我的Visual Studio和现在我得到一个不同的异常:“到SSPI调用失败,请参见内部异常”与内部异常 - >“收到的消息是意外或格式错误。”
解决方案
您必须已经安装在证书存储证书。最简单的方法是使用IE和导入证书。
不隶属于 StackOverflow