如何使用 makecert 创建 WCF 接受的 X509 证书
Posted
技术标签:
【中文标题】如何使用 makecert 创建 WCF 接受的 X509 证书【英文标题】:How to use makecert to create a X509 certificate accepted by WCF 【发布时间】:2012-03-04 07:50:40 【问题描述】:谁能给我提供一个如何创建自签名证书的示例,以下代码将接受该证书:
ServiceHost svh = new ServiceHost(typeof(MyClass));
var tcpbinding = new NetTcpBinding(SecurityMode.TransportWithMessageCredential, true);
//security
tcpbinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
svh.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = new BWUserNamePasswordValidator();
svh.Credentials.UserNameAuthentication.UserNamePasswordValidationMode =UserNamePasswordValidationMode.Custom;
svh.Credentials.ServiceCertificate.Certificate = BookmarkWizSettings.TcpBindingCertificate;
....
svh.Open();
我用过
makecert -pe myCertificate
和
makecert -sv SignRoot.pvk -cy authority -r signroot.cer -a sha1 -n "CN=Dev Certification Authority" -ss my -sr localmachine
和
makecert -r -pe -n "CN=Client" -ss MyApp -sky Exchange
我尝试使用 BouncyCastle 生成证书,但每次我收到以下异常:
It is likely that certificate 'CN=Dev Certification Authority' may not have a
private key that is capable of key exchange or the process may not have access
rights for the private key. Please see inner exception for detail.
内部异常为空。
这可能有一个技巧,但我不明白。
如何为我的 WCF 服务生成正确的证书??
【问题讨论】:
看看这个如何链接。 msdn.microsoft.com/en-us/library/ff648498.aspx 这个链接对我设置我的最有帮助。它走过所有的步骤。 codeproject.com/Articles/96028/… 【参考方案1】:以下代码适用于框架 4.0: 首先在您的 LocalMachine 中手动安装您的证书作为可信证书很重要 为此,您只需从 Internet Explorer 中打开服务器位置即可安装它。
第二个 响应服务器错误,因为自签名证书
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.Net;
using System.Net.Security;
namespace WCFSelfSignCert
class Program
static void Main(string[] args)
//You have to install your certificate as trusted certificate in your LocalMachine
//create your service client/ procy
using (MyProxy.ServiceClient client = new MyProxy.ServiceClient())
//server certification respond with an error, because doesnt recognize the autority
ServicePointManager.ServerCertificateValidationCallback += OnServerValError;
//Assign to self sign certificate
client.ClientCredentials.ClientCertificate.SetCertificate(StoreLocation.LocalMachine,
StoreName.Root,
X509FindType.FindBySubjectName,
"MY custom subject name"); //SubjectName(CN) from certificate
//make a test call to ensure that service responds
var res = client.echo("test");
Console.WriteLine(res);
Console.ReadKey();
public static bool OnServerValError(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
//mute the error, or provide some custom validation code
return true;
//or more restrictive
// if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateNameMismatch)
//
// return true;
//
// else
//
// return false;
//
【讨论】:
以上是关于如何使用 makecert 创建 WCF 接受的 X509 证书的主要内容,如果未能解决你的问题,请参考以下文章