在C#中加载自签名的P12证书文件

时间:2012-10-29 19:39:11

标签: c# x509certificate

使用证书对我来说仍然是新手。

我正在尝试加载一个p12证书文件(我认为它被称为自签名证书),用于渠道工厂。这是VS2010中的C#程序和WFC服务引用。以下是我尝试的方法和我收到的错误。最后一段代码是VB.net代码,运行没有错误。我认为这表明p12文件的路径和密码是正确的。

//Create the binding and channel
WSHttpBinding binding = new WSHttpBinding();
binding.Security.Mode = SecurityMode.Message;
binding.Security.Message.ClientCredentialType = MessageCredentialType.Certificate;
binding.Security.Message.NegotiateServiceCredential = false;
binding.Security.Message.EstablishSecurityContext = false;

EndpointAddress serviceAddress = new EndpointAddress("http://myendpoint");
ChannelFactory<ServiceName> channelFactory = null;

channelFactory = new ChannelFactory<ServiceName>(binding, serviceAddress);


//try to add the cert - Error: Object reference not set to an instance of the object. I've tried all available X509KeyStorageFlags
channelFactory.Credentials.ClientCertificate.Certificate.Import(@c:\path\to\file\fw.mycert.com.p12", "password", X509KeyStorageFlags.PersistKeySet);

//try to add the cert - Error: The specified network password is not correct. I've tried all available X509KeyStorageFlags
//rawCertificateData does contain 2000+ bytes
X509Certificate2 certificate = new X509Certificate2();
byte[] rawCertificateData = File.ReadAllBytes(@"c:\path\to\file\fw.mycert.com.p12");                
channelFactory.Credentials.ClientCertificate.Certificate.Import(rawCertificateData, "password", X509KeyStorageFlags.DefaultKeySet);

//This works in vb.net with the same path and password
Dim cert As New X509Certificate2("c:\path\to\file\fw.mycert.com.p12", "password")
request.ClientCertificates.Add(cert)

0 个答案:

没有答案