本文整理汇总了C#中System.Net.Security.SslStream.AuthenticateAsClientAsync方法的典型用法代码示例。如果您正苦于以下问题:C# SslStream.AuthenticateAsClientAsync方法的具体用法?C# SslStream.AuthenticateAsClientAsync怎么用?C# SslStream.AuthenticateAsClientAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Security.SslStream
的用法示例。
在下文中一共展示了SslStream.AuthenticateAsClientAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
public static void Main(string[] args)
{
Console.WriteLine("Starting...");
X509Certificate2 serverCertificate = new X509Certificate2("certificate.pfx"); // Any valid certificate with private key will work fine.
TcpListener listener = new TcpListener(IPAddress.Any, 4567);
TcpClient client = new TcpClient();
listener.Start();
Task clientConnectTask = client.ConnectAsync(IPAddress.Loopback, 4567);
Task<TcpClient> listenerAcceptTask = listener.AcceptTcpClientAsync();
Task.WaitAll(clientConnectTask, listenerAcceptTask);
TcpClient server = listenerAcceptTask.Result;
SslStream clientStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null, EncryptionPolicy.RequireEncryption);
SslStream serverStream = new SslStream(server.GetStream(), false, null, null, EncryptionPolicy.RequireEncryption);
Task clientAuthenticationTask = clientStream.AuthenticateAsClientAsync(serverCertificate.GetNameInfo(X509NameType.SimpleName, false), null, SslProtocols.Tls12, false);
Task serverAuthenticationTask = serverStream.AuthenticateAsServerAsync(serverCertificate, false, SslProtocols.Tls12, false);
Task.WaitAll(clientAuthenticationTask, serverAuthenticationTask);
byte[] readBuffer = new byte[256];
Task<int> readTask = clientStream.ReadAsync(readBuffer, 0, readBuffer.Length); // Create a pending ReadAsync, which will wait for data that will never come (for testing purposes).
byte[] writeBuffer = new byte[256];
Task writeTask = clientStream.WriteAsync(writeBuffer, 0, writeBuffer.Length); // The main thread actually blocks here (not asychronously waits) on .NET Core making this call.
bool result = Task.WaitAll(new Task[1] { writeTask }, 5000); // This code won't even be reached on .NET Core. Works fine on .NET Framework.
if (result)
{
Console.WriteLine("WriteAsync completed successfully while ReadAsync was pending... nothing locked up.");
}
else
{
Console.WriteLine("WriteAsync failed to complete after 5 seconds.");
}
}
示例2: DesktopNetworkStream
/// <summary>
/// Initializes a client instance of <see cref="DesktopNetworkStream"/>.
/// </summary>
/// <param name="host">Network host.</param>
/// <param name="port">Network port.</param>
/// <param name="useTls">Use TLS layer?</param>
/// <param name="noDelay">No delay?</param>
/// <param name="ignoreSslPolicyErrors">Ignore SSL policy errors?</param>
internal DesktopNetworkStream(string host, int port, bool useTls, bool noDelay, bool ignoreSslPolicyErrors)
{
this.Host = host;
this.Port = port;
#if NETSTANDARD
this.tcpClient = new TcpClient { NoDelay = noDelay };
this.tcpClient.ConnectAsync(host, port).Wait();
#else
this.tcpClient = new TcpClient(host, port) { NoDelay = noDelay };
#endif
Stream stream = this.tcpClient.GetStream();
if (useTls)
{
var ssl = new SslStream(
stream,
false,
(sender, certificate, chain, errors) => errors == SslPolicyErrors.None || ignoreSslPolicyErrors);
#if NETSTANDARD
ssl.AuthenticateAsClientAsync(host).Wait();
#else
ssl.AuthenticateAsClient(host);
#endif
stream = ssl;
}
this.networkStream = stream;
}
示例3: Discover
public ServiceEndPoint Discover(ServiceEndPoint serviceEndpoint)
{
try
{
using (var client = CreateConnectedTcpClient(serviceEndpoint))
{
using (var stream = client.GetStream())
{
using (var ssl = new SslStream(stream, false, ValidateCertificate))
{
ssl.AuthenticateAsClientAsync(serviceEndpoint.BaseUri.Host, new X509Certificate2Collection(), SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, false)
.GetAwaiter()
.GetResult();
ssl.Write(HelloLine, 0, HelloLine.Length);
ssl.Flush();
if (ssl.RemoteCertificate == null)
throw new Exception("The server did not provide an SSL certificate");
return new ServiceEndPoint(serviceEndpoint.BaseUri, new X509Certificate2(ssl.RemoteCertificate.Export(X509ContentType.Cert)).Thumbprint);
}
}
}
}
catch (Exception ex)
{
throw new HalibutClientException(ex.Message, ex);
}
}
示例4: PostEmailAsync
public override Task PostEmailAsync(string name, string[] to, string[] cc, string[] bcc, string subject, string message, params Attachment[] Attachments)
{
if (!ssl)
return Task.Factory.StartNew(async () =>
{
using (var client = new TcpClient())
{
await client.ConnectAsync(server, port);
using (var stream = client.GetStream())
using (var reader = new StreamReader(stream))
using (var writer = new StreamWriter(stream) { AutoFlush = true, NewLine = "\r\n" })
{
TcpWrite(writer, reader, name, to, cc, bcc, subject, message, Attachments);
}
}
});
else
return Task.Factory.StartNew(async () =>
{
using (var client = new TcpClient())
{
await client.ConnectAsync(server, port);
using (var stream = new SslStream(client.GetStream(), false))
{
await stream.AuthenticateAsClientAsync(server);
using (var reader = new StreamReader(stream))
using (var writer = new StreamWriter(stream) { AutoFlush = true, NewLine = "\r\n" })
{
TcpWrite(writer, reader, name, to, cc, bcc, subject, message, Attachments);
}
}
}
});
}
示例5: ConnectAsync
public async Task<Stream> ConnectAsync(string host, int port, X509Certificate clientCert, CancellationToken cancel)
{
Stream lowerStream = null;
SslStream sslStream = null;
X509CertificateCollection certCollection = null;;
if (clientCert != null)
{
certCollection = new X509CertificateCollection(new[] { clientCert });
}
try
{
lowerStream = await _connectionResolver.ConnectAsync(host, port, cancel);
sslStream = new SslStream(lowerStream);
await sslStream.AuthenticateAsClientAsync(host, certCollection, _protocols, checkCertificateRevocation: true);
return sslStream;
}
catch (Exception)
{
if (sslStream != null)
{
sslStream.Dispose();
}
if (lowerStream != null)
{
lowerStream.Dispose();
}
throw;
}
}
示例6: InitRemoteStream
async protected override Task InitRemoteStream()
{
await base.InitRemoteStream();
var secureRemoteStream = new SslStream(RemoteStream, true, RemoteCertificateValidator);
var targetHost = WrapperRequest.Prologue.Headers.First(x => x.Key == "Host").Value;
await secureRemoteStream.AuthenticateAsClientAsync(targetHost);
SecureRemoteStream = secureRemoteStream;
}
示例7: Connect
public async Task Connect ()
{
if (IsConnected ())
return;
tcp = new TcpClient ();
// Disable Nagle for HTTP/2
tcp.NoDelay = true;
await tcp.ConnectAsync (Host, (int)Port);
if (UseTls) {
sslStream = new SslStream (tcp.GetStream (), false,
(sender, certificate, chain, sslPolicyErrors) => true);
await sslStream.AuthenticateAsClientAsync (
Host,
Certificates ?? new X509CertificateCollection (),
System.Security.Authentication.SslProtocols.Tls12,
false);
clientStream = sslStream;
} else {
clientStream = tcp.GetStream ();
}
// Send out preface data
var prefaceData = System.Text.Encoding.ASCII.GetBytes (ConnectionPreface);
await clientStream.WriteAsync (prefaceData, 0, prefaceData.Length);
await clientStream.FlushAsync ();
// Start reading the stream on another thread
var readTask = Task.Factory.StartNew (() => {
try { read (); }
catch (Exception ex) {
Console.WriteLine ("Read error: " + ex);
Disconnect ();
}
}, TaskCreationOptions.LongRunning);
readTask.ContinueWith (t => {
// TODO: Handle the error
Console.WriteLine ("Error: " + t.Exception);
Disconnect ();
}, TaskContinuationOptions.OnlyOnFaulted);
// Send an un-ACK'd settings frame
await SendFrame(new SettingsFrame ());
// We need to wait for settings server preface to come back now
resetEventConnectionSettingsFrame = new ManualResetEventSlim ();
resetEventConnectionSettingsFrame.Reset ();
if (!resetEventConnectionSettingsFrame.Wait (ConnectionTimeout)) {
Disconnect ();
throw new Exception ("Connection timed out");
}
}
示例8: createClientStream
protected override Stream createClientStream(string host, int port)
{
var rval = new SslStream(base.createClientStream(host, port), false, (o, cert, chain, errors) => true);
//rval.AuthenticateAsClient(host);
Task task = rval.AuthenticateAsClientAsync(host);
task.Wait();
return rval;
}
示例9: ConnectAsync
/// <summary>
/// Establishes a TCP connection with the endpoint at the specified address/port pair.
/// </summary>
/// <param name="address">The address of the endpoint to connect to.</param>
/// <param name="port">The port of the endpoint to connect to.</param>
/// <param name="secure">True to enable TLS on the socket.</param>
public async Task ConnectAsync(string address, int port, bool secure = false)
{
await _backingTcpClient.ConnectAsync(address, port);
InitializeWriteStream();
if (secure)
{
var secureStream = new SslStream(_writeStream, true, (sender, cert, chain, sslPolicy) => ServerValidationCallback(sender, cert, chain, sslPolicy));
await secureStream.AuthenticateAsClientAsync(address, null, System.Security.Authentication.SslProtocols.Tls, false);
_secureStream = secureStream;
}
}
示例10: OnRunJobAsync
} // proc OnRunJob
private async Task OnRunJobAsync()
{
inConnectionPhase = true;
try
{
var timeoutSource = new CancellationTokenSource(30000);
// resolve end point
var serverTcp = this.GetService<IServerTcp>(true);
if (endPoint == null)
endPoint = await serverTcp.ResolveEndpointAsync(targetHost, targetPort, timeoutSource.Token);
// register the connection
if (endPoint != null)
{
var protocol = this.GetService<OdetteFileTransferProtocolItem>(true);
// check if the protocol is running
if (protocol.IsActiveProtocol(ChannelName))
Log.Info("Protocol is already active.");
else // create the connection
try
{
var stream = await serverTcp.CreateConnectionAsync(endPoint, timeoutSource.Token);
if (useSsl)
{
var ssl = new SslStream(stream, false, SslRemoteCertificateValidateCallback); // , SslLocalCertificateSelector
await ssl.AuthenticateAsClientAsync(targetHost);
var cert = ssl.RemoteCertificate;
Log.Info($"Ssl active: auth={ssl.IsAuthenticated}, encrypt={ssl.IsEncrypted}, signed={ssl.IsSigned}\nissuer={cert.Issuer}\nsubject={cert.Subject}");
stream = ssl;
}
await protocol.StartProtocolAsync(new OdetteNetworkStream(stream, channelName, Config), true);
}
catch (Exception e)
{
Log.Except("Connection failed.", e);
}
}
}
catch (Exception e)
{
Log.Except(e);
}
finally
{
inConnectionPhase = false;
}
} // proc OnRunJobAsync
示例11: CreateStream
private async Task<Stream> CreateStream(Uri uri, Socket socket)
{
Stream stream = new NetworkStream(socket);
if (uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
{
var sslStream = new SslStream(stream);
await sslStream.AuthenticateAsClientAsync(uri.Host, new X509CertificateCollection(), _sslProtocols, checkCertificateRevocation: false);
stream = sslStream;
}
return stream;
}
示例12: ConnectTls
public async Task<ConnectStatus> ConnectTls ()
{
try {
SslStream ssl = new SslStream(tcpc.GetStream(), false, CertificateValidationCallBack);
await ssl.AuthenticateAsClientAsync(host);
stream = ssl;
return ConnectStatus.Ok;
}
catch
{
return ConnectStatus.Failed;
}
}
示例13: TcpClient
async Task<Stream> IConnectionFactory.Connect(string hostname, int port, bool useSsl)
{
TcpClient client = new TcpClient();
client.NoDelay = true;
await client.ConnectAsync(hostname, port);
if (useSsl)
{
SslStream sslStream = new SslStream(client.GetStream());
await sslStream.AuthenticateAsClientAsync(hostname);
return sslStream;
}
return client.GetStream();
}
示例14: GetNetworkStream
protected override async Task<Stream> GetNetworkStream(TcpClient client)
{
var sslStream = new SslStream(
client.GetStream(),
false,
ValidateServerCertificate,
null
);
await sslStream.AuthenticateAsClientAsync(Hostname).ConfigureAwait(false);
return sslStream;
}
示例15: Connect
private async Task Connect()
{
try
{
// Could be a reconnect - get rid of the old stream if so
if (_stream != null)
{
_stream.Dispose();
_stream = null;
}
await _tcpClient.ConnectAsync(_host, _port);
_stream = _tcpClient.GetStream();
_stream.ReadTimeout = _configuration.WaitForDataTimeoutInMilliseconds;
if (_configuration.Ssl)
{
var sslStream = new SslStream(_stream, false, _configuration.CertificateValidationCallback);
await sslStream.AuthenticateAsClientAsync(_host);
_stream = sslStream;
}
if (_configuration.Password != null)
{
var response = await Command.From("AUTH", _configuration.Password).SendAsync(this);
if (response.Value.IsError || response.Value.ToString() != "OK")
throw ExceptionBecause.Connection.FailedToAuthenticate(response);
}
_configuration.Events.OnConnectionOpened(new ConnectionEventArgs
{
Host = _host,
Port = _port
});
}
catch (Exception e)
{
_configuration.Events.OnConnectionError(new ConnectionEventArgs
{
Host = _host,
Port = _port,
Exception = e
});
throw;
}
}