我正在尝试使用SSL加密设置net.tcp连接 我有以下课程
Wcf界面:
[ServiceContract()]
public interface IServer
{
[OperationContract]
void Send(string message);
}
服务器:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple, UseSynchronizationContext = false)]
class Server : IServer
{
readonly ServiceHost host;
public Server()
{
host = new ServiceHost(this);
host.AddServiceEndpoint(typeof(IServer), Program.GetBinding(), string.Format("net.tcp://localhost:{0}/", 1010));
host.Credentials.ServiceCertificate.Certificate = Program.LoadCert();
host.Open();
}
public void Send(string message)
{
Console.WriteLine(message);
}
}
程序(客户端/服务器):
class Program
{
static ChannelFactory<IServer> channelFactory;
static IServer server;
static RemoteCertificateValidationCallback callback = null;
public const int MaxMessageSize = 1024 * 1024 * 2;
public static Binding GetBinding()
{
NetTcpBinding binding = new NetTcpBinding();
binding.Security.Mode = SecurityMode.Transport;
binding.Security.Message.ClientCredentialType = MessageCredentialType.None;
binding.ReaderQuotas.MaxArrayLength = MaxMessageSize;
binding.ReaderQuotas.MaxBytesPerRead = MaxMessageSize;
binding.MaxBufferSize = MaxMessageSize;
binding.MaxReceivedMessageSize = MaxMessageSize;
binding.MaxBufferPoolSize = binding.MaxBufferSize * 10;
binding.TransactionFlow = false;
binding.ReliableSession.Enabled = false;
binding.Security.Transport.ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign;
return binding;
}
public static X509Certificate2 LoadCert()
{
X509Certificate2 cert = new X509Certificate2();
cert.Import(@"Test2.pfx", "Test", X509KeyStorageFlags.DefaultKeySet);
return cert;
}
static void Main(string[] args)
{
try
{
callback = new RemoteCertificateValidationCallback(ValidateCertificate);
ServicePointManager.ServerCertificateValidationCallback += callback;
Console.WriteLine("[C]lient or [S]erver?");
ConsoleKeyInfo key = Console.ReadKey(true);
if (key.Key == ConsoleKey.S)
{
StartServer();
}
else if (key.Key == ConsoleKey.C)
{
StartClient();
}
}
finally
{
if (callback != null)
ServicePointManager.ServerCertificateValidationCallback -= callback;
}
}
private static void StartClient()
{
Console.WriteLine("Starting client mode!");
Console.Write("Host:");
string host = Console.ReadLine();
channelFactory = new ChannelFactory<IServer>(GetBinding());
server = channelFactory.CreateChannel(new EndpointAddress(string.Format("net.tcp://{0}:{1}/", host, 1010)));
while (true)
{
Console.Write("Message:");
server.Send(Console.ReadLine());
}
}
private static void StartServer()
{
Console.WriteLine("Starting server mode!");
Server server = new Server();
Console.ReadKey();
GC.KeepAlive(server);
}
public static bool ValidateCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
Console.WriteLine("ValidateCertificate");
return true;
}
}
当服务器和客户端都在同一台计算机上运行时,这种方法很好(但是从不像它应该那样调用ValidateCertificate)。
但如果我在不同的计算机上运行它们,我会在客户端上遇到以下异常:
描述:由于未处理的异常,进程终止。 例外信息: System.ServiceModel.Security.SecurityNegotiationException Stack:
服务器堆栈跟踪:at System.ServiceModel.Channels.WindowsStreamSecurityUpgradeProvider.WindowsStreamSecurityUpgradeInitiator.OnInitiateUpgrade(流 stream,SecurityMessageProperty&amp; remoteSecurity)at System.ServiceModel.Channels.StreamSecurityUpgradeInitiatorBase.InitiateUpgrade(流 流) System.ServiceModel.Channels.ConnectionUpgradeHelper.InitiateUpgrade(StreamUpgradeInitiator upgradeInitiator,IConnection&amp;连接,ClientFramingDecoder 解码器,IDefaultCommunicationTimeouts defaultTimeouts,TimeoutHelper&amp; timeoutHelper)at System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.SendPreamble(IConnection 连接,ArraySegment`1前导码,TimeoutHelper&amp; timeoutHelper)
在 System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.DuplexConnectionPoolHelper.AcceptPooledConnection(IConnection 连接,TimeoutHelper&amp; timeoutHelper)at System.ServiceModel.Channels.ConnectionPoolHelper.EstablishConnection(时间跨度 超时)at System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.OnOpen(时间跨度 超时)at System.ServiceModel.Channels.CommunicationObject.Open(时间跨度 超时)at System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout)
在System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan 超时)at System.ServiceModel.Channels.ServiceChannel.CallOpenOnce.System.ServiceModel.Channels.ServiceChannel.ICallOnce.Call(ServiceChannel 频道,TimeSpan超时)at System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(时间跨度 超时,CallOnceManager级联)at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway,ProxyOperationRuntime操作,Object [] ins, 对象[]出局,TimeSpan超时)at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall,ProxyOperationRuntime operation)at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(即时聊天 消息) System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(System.Runtime.Remoting.Messaging.IMessage, System.Runtime.Remoting.Messaging.IMessage)at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(System.Runtime.Remoting.Proxies.MessageData ByRef,Int32)at WcfChatTest.Client.Program + IServer.Send(System.String)at WcfChatTest.Client.Program.StartClient()at WcfChatTest.Client.Program.Main(System.String [])
我配置错误,为什么在我提供证书时会调用“WindowsStreamSecurityUpgradeProvider”?
或者,如果其他人有一个很好的例子,如何在net.tcp上获得传输加密,而客户端和服务器不在同一个域中?
答案 0 :(得分:0)
我在线上解决了问题
server = channelFactory.CreateChannel(new EndpointAddress(string.Format("net.tcp://{0}:{1}/", host, 1010)));
我必须添加一个我用以下代码创建的附加参数
EndpointIdentity.CreateX509CertificateIdentity(certificate)