同事,
当我尝试在.cer文件中使用带有公钥的X509证书时,我遇到以下异常:
{“证书'CN = name'必须有私钥。进程必须具有私钥的访问权限。”}
以下是我用来设置证书的客户端代码。请注意,它是基于文件的。
var cert = new X509Certificate2(@"C:\mycert.cer");
credentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;
credentials.ClientCertificate.Certificate = cert;
主机代码:
namespace Host
{
class Program
{
static void Main(string[] args)
{
using (ServiceHost host = new ServiceHost(typeof(HelloIndigo.HelloIndigoService),
new Uri("http://localhost:8000/HelloIndigo")))
{
host.Open();
Console.WriteLine("Service is listening...");
Console.WriteLine();
Console.WriteLine("Number of base addresses: {0}", host.BaseAddresses.Count);
foreach (Uri uri in host.BaseAddresses)
{
Console.WriteLine("\t{0}", uri.ToString());
}
Console.WriteLine();
Console.WriteLine("Number of dispatchers (listeners): {0}", host.ChannelDispatchers.Count);
foreach (ChannelDispatcher dispatcher in host.ChannelDispatchers)
{
Console.WriteLine("\t{0}, {1}", dispatcher.Listener.Uri.ToString(), dispatcher.BindingName);
}
Console.WriteLine();
Console.WriteLine("Press <ENTER> to terminate the host application");
Console.ReadLine();
}
}
}
}
主机App.config:
<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<services>
<service name="HelloIndigo.HelloIndigoService" behaviorConfiguration="serviceBehavior">
<endpoint contract="HelloIndigo.IHelloIndigoService" binding="wsHttpBinding" bindingConfiguration="wsHttpBinding"/>
<endpoint contract="IMetadataExchange" binding="wsHttpBinding" bindingConfiguration="mexBinding" address="mex"/> <!-- -->
</service>
</services>
<bindings>
<wsHttpBinding>
<binding name="mexBinding">
<security mode="Message">
<message clientCredentialType="Certificate"/>
</security>
</binding>
<binding name="wsHttpBinding">
<security mode="Message">
<message clientCredentialType="Certificate"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="serviceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceCredentials>
<clientCertificate>
<authentication certificateValidationMode="PeerOrChainTrust" trustedStoreLocation="LocalMachine"/>
</clientCertificate>
<serviceCertificate findValue="name" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName"/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<diagnostics performanceCounters="ServiceOnly" wmiProviderEnabled="true">
<messageLogging logEntireMessage="true" logMalformedMessages="true" logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true" maxMessagesToLog="100000"/>
</diagnostics>
</system.serviceModel>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>
我使用它的唯一方法是使用公钥/私钥和密码在pfx中生成证书,但我认为在客户端上始终有密码是不安全的。有没有办法只使用公钥来对服务进行客户端身份验证?
答案 0 :(得分:0)
回答我的问题是,为了保证私钥的安全性,这显然是使用基于文件的客户端证书的最重要问题,需要先将其导入到商店,然后再从商店使用它通过API找到。