本文整理汇总了C#中System.Net.Security.SslStream.BeginAuthenticateAsServer方法的典型用法代码示例。如果您正苦于以下问题:C# SslStream.BeginAuthenticateAsServer方法的具体用法?C# SslStream.BeginAuthenticateAsServer怎么用?C# SslStream.BeginAuthenticateAsServer使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Security.SslStream
的用法示例。
在下文中一共展示了SslStream.BeginAuthenticateAsServer方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: assign_without_subscribing_on_MessageReceived_means_that_messages_can_get_lost
public void assign_without_subscribing_on_MessageReceived_means_that_messages_can_get_lost()
{
var slice = new BufferSlice(new byte[65535], 0, 65535);
var encoder = Substitute.For<IMessageEncoder>();
var decoder = Substitute.For<IMessageDecoder>();
var stream = new SslStream(new NetworkStream(_helper.Server));
stream.BeginAuthenticateAsServer(_certificate, OnAuthenticated, stream);
var sut = CreateClientChannel(slice, encoder, decoder);
Action actual = () => sut.Assign(_helper.Client);
actual.ShouldThrow<InvalidOperationException>();
}
示例2: Assign_should_work_after_subscription
public void Assign_should_work_after_subscription()
{
var slice = new BufferSlice(new byte[65535], 0, 65535);
var encoder = Substitute.For<IMessageEncoder>();
var decoder = Substitute.For<IMessageDecoder>();
object expected;
var stream = new SslStream(new NetworkStream(_helper.Server));
stream.BeginAuthenticateAsServer(_certificate, OnAuthenticated, stream);
var sut = CreateClientChannel(slice, encoder, decoder);
sut.MessageReceived += (channel, message) => expected = message;
sut.Assign(_helper.Client);
}
示例3: Authenticate
public Task Authenticate(X509Certificate2 certificate, SslProtocols enabledSslProtocols, Action callback, Action<Exception> error)
{
var ssl = new SslStream(_stream, false);
_stream = new QueuedStream(ssl);
Func<AsyncCallback, object, IAsyncResult> begin =
(cb, s) => ssl.BeginAuthenticateAsServer(certificate, false, enabledSslProtocols, false, cb, s);
Task task = Task.Factory.FromAsync(begin, ssl.EndAuthenticateAsServer, null);
task.ContinueWith(t => callback(), TaskContinuationOptions.NotOnFaulted)
.ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
task.ContinueWith(t => error(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
return task;
}
示例4: should_listen_on_the_decoder_event
public void should_listen_on_the_decoder_event()
{
var slice = new BufferSlice(new byte[65535], 0, 65535);
var encoder = Substitute.For<IMessageEncoder>();
var decoder = new FakeDecoder();
object expected = null;
var stream = new SslStream(new NetworkStream(_helper.Server));
stream.BeginAuthenticateAsServer(_certificate, OnAuthenticated, stream);
var sut = CreateClientChannel(slice, encoder, decoder);
sut.MessageReceived += (channel, message) => expected = message;
decoder.MessageReceived("Hello");
expected.Should().Be("Hello");
}
示例5: New
public void New(TcpClient c, bool isOutBound)
{
var stream = new SslStream(c.GetStream());
var remote = ((IPEndPoint)c.Client.RemoteEndPoint).Address.ToString();
var certs = new X509CertificateCollection();
var state = new State { Client = c, Stream = stream };
if (isOutBound)
{
certs.Add(clientCertificate);
stream.BeginAuthenticateAsClient(remote, certs, SslProtocols.Tls, false, EndAuthenticateAsClient, state);
}
else
{
certs.Add(serverCertificate);
stream.BeginAuthenticateAsServer(serverCertificate, true, SslProtocols.Tls, false, EndAuthenticateAsServer, state);
}
}
示例6: Client
internal Client(BaseServer server, TcpClient client, X509Certificate certificate)
: base(server)
{
this.client = client;
Nstream = client.GetStream();
cert = certificate;
Sstream = new SslStream(Nstream, false);
try
{
Sstream.BeginAuthenticateAsServer(certificate, false, SslProtocols.Default, true, FinishServerAuthentication, null);
}
catch (Exception x)
{
OnAuthFailed(new ClientAuthFailedEventArgs(x));
_CheckIfStopped(x, true);
}
}
示例7: InitServerSocket
private void InitServerSocket(Socket socket, X509Certificate certificate, bool verbose)
{
Ensure.NotNull(certificate, "certificate");
InitConnectionBase(socket);
if (verbose) Console.WriteLine("TcpConnectionSsl::InitClientSocket({0}, L{1})", RemoteEndPoint, LocalEndPoint);
using (_streamLock.Acquire())
{
try
{
socket.NoDelay = true;
}
catch (ObjectDisposedException)
{
CloseInternal(SocketError.Shutdown, "Socket is disposed.");
return;
}
_sslStream = new SslStream(new NetworkStream(socket, true), false);
try
{
_sslStream.BeginAuthenticateAsServer(certificate, false, SslProtocols.Default, true, OnEndAuthenticateAsServer, _sslStream);
}
catch (AuthenticationException exc)
{
Log.InfoException(exc, "[S{0}, L{1}]: Authentication exception on BeginAuthenticateAsServer.", RemoteEndPoint, LocalEndPoint);
CloseInternal(SocketError.SocketError, exc.Message);
}
catch (ObjectDisposedException)
{
CloseInternal(SocketError.SocketError, "SslStream disposed.");
}
catch (Exception exc)
{
Log.InfoException(exc, "[S{0}, L{1}]: Exception on BeginAuthenticateAsServer.", RemoteEndPoint, LocalEndPoint);
CloseInternal(SocketError.SocketError, exc.Message);
}
}
}
示例8: InitializeCryptService
//.........这里部分代码省略.........
SymmetricAlgorithm sa = CryptUtils.CreateSymmetricAlgoritm(connection.EncryptType);
sa.GenerateIV();
sa.GenerateKey();
//----- Adjust connection cryptors!
connection.Encryptor = sa.CreateEncryptor();
connection.Decryptor = sa.CreateDecryptor();
//----- Create authenticate structure!
AuthMessage am = new AuthMessage();
am.SessionIV = serverPublicKey.Encrypt(sa.IV, false);
am.SessionKey = serverPublicKey.Encrypt(sa.Key, false);
am.SourceKey = CryptUtils.EncryptDataForAuthenticate(sa, Encoding.UTF8.GetBytes(clientPrivateKey.ToXmlString(false)), PaddingMode.ISO10126);
//----- Sign message with am.SourceKey, am.SessionKey and signMessage!
//----- Need to use PaddingMode.PKCS7 in sign!
MemoryStream m = new MemoryStream();
m.Write(am.SourceKey, 0, am.SourceKey.Length);
m.Write(am.SessionKey, 0, am.SessionKey.Length);
m.Write(signMessage, 0, signMessage.Length);
am.Sign = clientPrivateKey.SignData(CryptUtils.EncryptDataForAuthenticate(sa, m.ToArray(), PaddingMode.PKCS7), new SHA1CryptoServiceProvider());
//----- Serialize authentication message!
XmlSerializer xml = new XmlSerializer(typeof(AuthMessage));
m.SetLength(0);
xml.Serialize(m, am);
//----- Send structure!
MessageBuffer mb = new MessageBuffer(0);
mb.PacketBuffer = Encoding.GetEncoding(1252).GetBytes(Convert.ToBase64String(m.ToArray()));
connection.Socket.BeginSend(mb.PacketBuffer, mb.PacketOffSet, mb.PacketRemaining, SocketFlags.None, new AsyncCallback(InitializeConnectionSendCallback), new CallbackData(connection, mb));
m.Close();
am.SessionIV.Initialize();
am.SessionKey.Initialize();
serverPublicKey.Clear();
clientPrivateKey.Clear();
}
else
{
//----- Create empty authenticate structure!
MessageBuffer mb = new MessageBuffer(8192);
//----- Start receive structure!
connection.Socket.BeginReceive(mb.PacketBuffer, mb.PacketOffSet, mb.PacketRemaining, SocketFlags.None, new AsyncCallback(InitializeConnectionReceiveCallback), new CallbackData(connection, mb));
}
}
//----- Asymmetric!
if (connection.EncryptType == EncryptType.etSSL)
{
if (FHost.HostType == HostType.htClient)
{
//----- Get SSL items!
X509Certificate2Collection certs = null;
string serverName = null;
bool checkRevocation = true;
FCryptoService.OnSSLClientAuthenticate(connection, out serverName, ref certs, ref checkRevocation);
//----- Authneticate SSL!
SslStream ssl = new SslStream(new NetworkStream(connection.Socket), true, new RemoteCertificateValidationCallback(ValidateServerCertificateCallback));
if (certs == null)
{
ssl.BeginAuthenticateAsClient(serverName, new AsyncCallback(SslAuthenticateCallback), new AuthenticateCallbackData(connection, ssl, HostType.htClient));
}
else
{
ssl.BeginAuthenticateAsClient(serverName, certs, System.Security.Authentication.SslProtocols.Default, checkRevocation, new AsyncCallback(SslAuthenticateCallback), new AuthenticateCallbackData(connection, ssl, HostType.htClient));
}
}
else
{
//----- Get SSL items!
X509Certificate2 cert = null;
bool clientAuthenticate = false;
bool checkRevocation = true;
FCryptoService.OnSSLServerAuthenticate(connection, out cert, out clientAuthenticate, ref checkRevocation);
//----- Authneticate SSL!
SslStream ssl = new SslStream(new NetworkStream(connection.Socket));
ssl.BeginAuthenticateAsServer(cert, clientAuthenticate, System.Security.Authentication.SslProtocols.Default, checkRevocation, new AsyncCallback(SslAuthenticateCallback), new AuthenticateCallbackData(connection, ssl, HostType.htServer));
}
}
}
示例9: BeginAuthenticationAsServer
public void BeginAuthenticationAsServer(X509Certificate2 certificate, SslProtocols protocols, AsyncCallback callback, object state)
{
SslStream sslStream = new SslStream(Stream, false);
Stream = sslStream;
sslStream.BeginAuthenticateAsServer(certificate, false, protocols, false, callback, state);
}
示例10: MaybeStartTLS
/// <summary>
/// Starts the TLS procedure ONLY if it's the correct time to do so.
/// This is dependent on several variables, such as the kPause flags, connected property, etc.
///
/// This method is NOT thread safe, and should only be invoked via thread safe methods.
/// </summary>
private void MaybeStartTLS()
{
Debug.Assert(socketStream != null, "Attempting to start tls without a connected socket");
Trace.Assert(secureSocketStream == null, "Attempting to start tls after tls has already completed");
// We can't start TLS until:
// - Any queued reads prior to the user calling StartTLS are complete
// - Any queued writes prior to the user calling StartTLS are complete
if (((flags & kPauseReads) > 0) && ((flags & kPauseWrites) > 0))
{
try
{
secureSocketStream = new SslStream(socketStream, true, tlsRemoteCallback, tlsLocalCallback);
if (isTLSClient)
{
secureSocketStream.BeginAuthenticateAsClient(tlsServerName,
new AsyncCallback(secureSocketStream_DidFinish), null);
}
else
{
secureSocketStream.BeginAuthenticateAsServer(localCertificate,
new AsyncCallback(secureSocketStream_DidFinish), null);
}
}
catch (Exception e)
{
// The most likely cause of this exception is a null tlsServerName.
CloseWithException(e);
}
}
}
示例11: send_message
public void send_message()
{
var slice = new BufferSlice(new byte[65535], 0, 65535);
var encoder = new StringEncoder();
var decoder = new StringDecoder();
object expected = null;
var sut = CreateClientChannel(slice, encoder, decoder);
sut.MessageReceived += (channel, message) => expected = message;
var stream = new SslStream(new NetworkStream(_helper.Server));
stream.BeginAuthenticateAsServer(_certificate, OnAuthenticated, stream);
sut.Assign(_helper.Client);
sut.Send("Hello world");
var buf = new byte[65535];
var tmp = stream.Read(buf, 0, 65535);
var actual = Encoding.ASCII.GetString(buf, 4, tmp-4); // string encoder have a length header.
actual.Should().Be("Hello world");
}
示例12: connectionHandler
public connectionHandler(Socket socket, HttpServer server, bool secure)
{
Socket = socket;
_requestId = Rnd.Next();
_requestStart = DateTime.UtcNow;
_server = server;
_secure = secure;
_server.Log.Info(4, "{0:X8} Incoming connection from {1}".Fmt(_requestId, socket.RemoteEndPoint));
_buffer = new byte[1024];
_bufferDataOffset = 0;
_bufferDataLength = 0;
_headersSoFar = "";
lock (server._activeConnectionHandlers)
server._activeConnectionHandlers.Add(this);
var stream = new NetworkStream(socket, ownsSocket: true);
if (_secure)
{
var secureStream = new SslStream(stream);
_stream = secureStream;
secureStream.BeginAuthenticateAsServer(new X509Certificate2(server.Options.CertificatePath, server.Options.CertificatePassword), false, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, true, ar =>
{
try
{
secureStream.EndAuthenticateAsServer(ar);
}
catch (Exception e)
{
Socket.Close();
cleanupIfDone();
if (_server.ResponseExceptionHandler != null)
_server.ResponseExceptionHandler(null, e, null);
return;
}
receiveMoreHeaderData();
}, null);
}
else
{
_stream = stream;
receiveMoreHeaderData();
}
}
示例13: AcceptConnections
private void AcceptConnections(string threadName)
{
try
{
Thread.CurrentThread.Name = threadName;
logger.Debug("SIPTLSChannel socket on " + m_localSIPEndPoint + " accept connections thread started.");
while (!Closed)
{
try
{
TcpClient tcpClient = m_tlsServerListener.AcceptTcpClient();
tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
IPEndPoint remoteEndPoint = (IPEndPoint)tcpClient.Client.RemoteEndPoint;
logger.Debug("SIP TLS Channel connection accepted from " + remoteEndPoint + ".");
SslStream sslStream = new SslStream(tcpClient.GetStream(), false);
SIPConnection sipTLSConnection = new SIPConnection(this, sslStream, remoteEndPoint, SIPProtocolsEnum.tls, SIPConnectionsEnum.Listener);
sslStream.BeginAuthenticateAsServer(m_serverCertificate, EndAuthenticateAsServer, sipTLSConnection);
//sslStream.AuthenticateAsServer(m_serverCertificate, false, SslProtocols.Tls, false);
//// Display the properties and settings for the authenticated stream.
////DisplaySecurityLevel(sslStream);
////DisplaySecurityServices(sslStream);
////DisplayCertificateInformation(sslStream);
////DisplayStreamProperties(sslStream);
//// Set timeouts for the read and write to 5 seconds.
//sslStream.ReadTimeout = 5000;
//sslStream.WriteTimeout = 5000;
////SIPConnection sipTLSConnection = new SIPConnection(this, sslStream, remoteEndPoint, SIPProtocolsEnum.tls, SIPConnectionsEnum.Listener);
//m_connectedSockets.Add(remoteEndPoint.ToString(), sipTLSConnection);
//sipTLSConnection.SIPSocketDisconnected += SIPTLSSocketDisconnected;
//sipTLSConnection.SIPMessageReceived += SIPTLSMessageReceived;
////byte[] receiveBuffer = new byte[MaxSIPTCPMessageSize];
//sipTLSConnection.SIPStream.BeginRead(sipTLSConnection.SocketBuffer, 0, MaxSIPTCPMessageSize, new AsyncCallback(ReceiveCallback), sipTLSConnection);
}
catch (Exception e)
{
logger.Error("SIPTLSChannel Accept Connection Exception. " + e);
//sslStream.Close();
//tcpClient.Close();
}
}
logger.Debug("SIPTLSChannel socket on " + m_localSIPEndPoint + " listening halted.");
}
catch (Exception excp)
{
logger.Error("Exception SIPTLSChannel Listen. " + excp);
//throw excp;
}
}
示例14: ProcessConnection
void ProcessConnection(Socket listener, IAsyncResult ar)
{
Socket ns = listener.EndAccept (ar);
ns.NoDelay = true;
SslStream ssl = new SslStream (new NetworkStream (ns, true));
ssl.BeginAuthenticateAsServer (cert, (IAsyncResult ar2) => {
try {
ssl.EndAuthenticateAsServer (ar2);
Protocol p = new Protocol ();
p.OnMessage += (incoming) => {
var hdr = incoming.Header;
// TODO timeout handling
if (hdr ["type"].AsString(null) != "request") {
Logger.LogError ("received non-request");
incoming.Discard ();
return;
}
if (!hdr.ContainsKey ("request_id")) {
Logger.LogError ("Received request with no request_id");
incoming.Discard ();
return;
}
var id = hdr ["request_id"];
reqh (incoming, (reply) => {
reply.Header ["type"] = "reply";
reply.Header ["request_id"] = id;
p.SendMessage (reply);
});
};
p.OnClose += (error) => {
Logger.LogInfo ("scamp connection closed: {0}", error);
};
p.Start (ssl);
} catch (Exception ex) {
Logger.LogError ("connection server authenticate: {0}", ex);
}
}, null);
}
示例15: NegotiateStream
private Stream NegotiateStream(Stream stream)
{
if (!_configuration.SslEnabled)
return stream;
var validateRemoteCertificate = new RemoteCertificateValidationCallback(
(object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
=>
{
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
if (_configuration.SslPolicyErrorsBypassed)
return true;
else
_log.ErrorFormat("Session [{0}] error occurred when validating remote certificate: [{1}], [{2}].",
this, this.RemoteEndPoint, sslPolicyErrors);
return false;
});
var sslStream = new SslStream(
stream,
false,
validateRemoteCertificate,
null,
_configuration.SslEncryptionPolicy);
var ar = sslStream.BeginAuthenticateAsServer(
_configuration.SslServerCertificate, // The X509Certificate used to authenticate the server.
_configuration.SslClientCertificateRequired, // A Boolean value that specifies whether the client must supply a certificate for authentication.
_configuration.SslEnabledProtocols, // The SslProtocols value that represents the protocol used for authentication.
_configuration.SslCheckCertificateRevocation, // A Boolean value that specifies whether the certificate revocation list is checked during authentication.
null, _tcpClient);
if (!ar.AsyncWaitHandle.WaitOne(ConnectTimeout))
{
Close();
throw new TimeoutException(string.Format(
"Negotiate SSL/TSL with remote [{0}] timeout [{1}].", this.RemoteEndPoint, ConnectTimeout));
}
// When authentication succeeds, you must check the IsEncrypted and IsSigned properties
// to determine what security services are used by the SslStream.
// Check the IsMutuallyAuthenticated property to determine whether mutual authentication occurred.
_log.DebugFormat(
"Ssl Stream: SslProtocol[{0}], IsServer[{1}], IsAuthenticated[{2}], IsEncrypted[{3}], IsSigned[{4}], IsMutuallyAuthenticated[{5}], "
+ "HashAlgorithm[{6}], HashStrength[{7}], KeyExchangeAlgorithm[{8}], KeyExchangeStrength[{9}], CipherAlgorithm[{10}], CipherStrength[{11}].",
sslStream.SslProtocol,
sslStream.IsServer,
sslStream.IsAuthenticated,
sslStream.IsEncrypted,
sslStream.IsSigned,
sslStream.IsMutuallyAuthenticated,
sslStream.HashAlgorithm,
sslStream.HashStrength,
sslStream.KeyExchangeAlgorithm,
sslStream.KeyExchangeStrength,
sslStream.CipherAlgorithm,
sslStream.CipherStrength);
return sslStream;
}