本文整理汇总了C#中System.Net.Security.SslStream.AuthenticateAsServerAsync方法的典型用法代码示例。如果您正苦于以下问题:C# SslStream.AuthenticateAsServerAsync方法的具体用法?C# SslStream.AuthenticateAsServerAsync怎么用?C# SslStream.AuthenticateAsServerAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Security.SslStream
的用法示例。
在下文中一共展示了SslStream.AuthenticateAsServerAsync方法的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: FinishAccept
public void FinishAccept(byte[] buffer, int offset, int length, IPEndPoint remoteEndPoint, IPEndPoint localEndPoint)
{
_remoteEndPoint = remoteEndPoint;
_localEndPoint = localEndPoint;
Debug.Assert(length == 0);
try
{
_ssl = new SslStream(_inputStream, true);
_authenticateTask = _ssl.AuthenticateAsServerAsync(_serverCertificate, false, _protocols, false).ContinueWith((t, selfObject) =>
{
var self = (SslTransportHandler)selfObject;
if (t.IsFaulted || t.IsCanceled)
self._next.FinishAccept(null, 0, 0, null, null);
else
self._ssl.ReadAsync(self._recvBuffer, self._recvOffset, self._recvLength).ContinueWith((t2, selfObject2) =>
{
var self2 = (SslTransportHandler)selfObject2;
if (t2.IsFaulted || t2.IsCanceled)
self2._next.FinishAccept(null, 0, 0, null, null);
else
self2._next.FinishAccept(self2._recvBuffer, self2._recvOffset, t2.Result, self2._remoteEndPoint, self2._localEndPoint);
}, self);
}, this);
}
catch (Exception)
{
Callback.StartDisconnect();
}
}
示例3: For
async public static Task<ProxySslRequest> For(ProxyRequest wrapperRequest, IRequestInspector wrapperRequestInspector)
{
if (_certProvider == null)
{
_certProvider = new CertificateProvider(MakeCertPath);
_certProvider.EnsureRootCertificate();
}
var sslRequest = new ProxySslRequest
{
WrapperRequest = wrapperRequest,
ClientPid = wrapperRequest.ClientPid,
ClientSocket = wrapperRequest.ClientSocket,
ClientStream = wrapperRequest.ClientStream
};
if (wrapperRequestInspector != null)
wrapperRequestInspector.OnTransferredToSecureRequest(sslRequest);
var hostName = sslRequest.GetHostName();
sslRequest._hostCert = _certProvider.GetCertificateForHost(hostName);
var clientSsslStream = new SslStream(wrapperRequest.ClientStream, true, RemoteCertificateValidator, sslRequest.LocalCertificateSelector);
await clientSsslStream.AuthenticateAsServerAsync(sslRequest._hostCert);
sslRequest.SecureClientStream = clientSsslStream;
sslRequest.ReadPrologue();
return sslRequest;
}
示例4: CreateSession
internal override async Task<HttpSession> CreateSession(long sessionId, TcpClient client)
{
var sslStream = new SslStream(client.GetStream());
await sslStream.AuthenticateAsServerAsync(serverCertificate, false, sslProtocols, false).ConfigureAwait(false);
return new HttpSession(sessionId, client, sslStream, true, maxKeepAlives, sessionReadBufferSize, (int)sessionReadTimeout.TotalMilliseconds, (int)sessionWriteTimeout.TotalMilliseconds);
}
示例5: ProcessAsync
public async Task ProcessAsync(IConnection connection, SmtpCommand command)
{
X509Certificate certificate = connection.Server.Behaviour.GetSSLCertificate(connection);
if (certificate == null)
{
await connection.WriteResponseAsync(new SmtpResponse(StandardSmtpResponseCode.CommandNotImplemented, "TLS configuration error - no certificate"));
return;
}
await connection.WriteResponseAsync(new SmtpResponse(StandardSmtpResponseCode.ServiceReady,
"Ready to start TLS"));
#pragma warning disable 0618
var sslProtos = SslProtocols.Ssl2 | SslProtocols.Ssl3 | SslProtocols.Tls;
#pragma warning restore 0618
await connection.ApplyStreamFilterAsync(async stream =>
{
SslStream sslStream = new SslStream(stream);
await sslStream.AuthenticateAsServerAsync(certificate
, false,
sslProtos,
false);
return sslStream;
});
connection.Session.SecureConnection = true;
}
示例6: AuthenticateAsync
public async Task AuthenticateAsync(X509Certificate2 certificate)
{
if (certificate == null)
return;
SslStream sslStream = new SslStream(Stream, false);
Stream = sslStream;
await sslStream.AuthenticateAsServerAsync(certificate);
}
示例7: Invoke
public async Task Invoke(TcpContext context)
{
var sslStream = new SslStream(context.Body);
await sslStream.AuthenticateAsServerAsync(_cert);
context.Body = sslStream;
await _next(context);
}
示例8: ExecuteAsync
/// <summary>
/// Execute the command.
/// </summary>
/// <param name="context">The execution context to operate on.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>A task which asynchronously performs the execution.</returns>
public override async Task ExecuteAsync(ISmtpSessionContext context, CancellationToken cancellationToken)
{
await context.Text.ReplyAsync(SmtpResponse.ServiceReady, cancellationToken);
var stream = new SslStream(context.Text.GetInnerStream(), true);
await stream.AuthenticateAsServerAsync(_certificate, false, SslProtocols.Default, true);
context.Text = new NetworkTextStream(stream);
}
示例9: ExtendConnection
public Stream ExtendConnection(Stream stream)
{
var ssl = new SslStream(stream, false, _validation);
#if (UAP10_0 || DOTNET5_4 || NETSTANDARD || NETSTANDARDAPP1_5)
ssl.AuthenticateAsServerAsync(_certificate, _validation != null, SslProtocols.Tls12, false).Wait();
#else
ssl.AuthenticateAsServer(_certificate, _validation != null, SslProtocols.Tls12, false);
#endif
return ssl;
}
示例10: OnConnection
public async Task OnConnection(ConnectionFilterContext context)
{
await _previous.OnConnection(context);
if (string.Equals(context.Address.Scheme, "https", StringComparison.OrdinalIgnoreCase))
{
var sslStream = new SslStream(context.Connection);
await sslStream.AuthenticateAsServerAsync(_cert);
context.Connection = sslStream;
}
}
示例11: CreateSession
internal override async Task<HttpSession> CreateSession(long sessionId,
TcpClient client,
int _maxKeepAlives,
int _sessionReadBufferSize,
TimeSpan _sessionReadTimeout,
TimeSpan _sessionWriteTimeout)
{
var sslStream = new SslStream(client.GetStream());
await sslStream.AuthenticateAsServerAsync(serverCertificate, false, sslProtocols, false);
return new HttpSession(sessionId, client, sslStream, true, _maxKeepAlives, _sessionReadBufferSize, _sessionReadTimeout, _sessionWriteTimeout);
}
示例12: Accept
public override async void Accept()
{
try
{
if (Sockets[0].AcceptSocket != null)
{
networkStream = new NetworkStream(Sockets[0].AcceptSocket);
tlsStream = new SslStream(networkStream, false);
tlsSemaphore = new SemaphoreSlim(1, 1);
await tlsStream.AuthenticateAsServerAsync(Manager.Session.Certificate, false, SslProtocols.Tls12, false);
if (tlsStream.IsAuthenticated && Manager.Session.Add(this))
{
var buffer = Sockets[0].Buffer;
int numReadBytes;
do
{
numReadBytes = await tlsStream.ReadAsync(buffer, 0, buffer.Length);
if (numReadBytes == 0)
break;
var headerLength = (buffer[0] << 8) | buffer[1];
var header = Header.Parser.ParseFrom(new CodedInputStream(buffer, 2, headerLength));
var data = new byte[header.Size];
if (header.Size > 0)
Buffer.BlockCopy(buffer, 2 + headerLength, data, 0, data.Length);
await Manager.BnetPacket.CallHandler(header, data, this);
} while (numReadBytes != 0);
}
}
}
catch (Exception ex)
{
Log.Message(LogTypes.Error, ex.Message);
}
finally
{
if (Manager.Session.Remove(this))
Dispose();
}
}
示例13: FinishAccept
public void FinishAccept(byte[] buffer, int offset, int length, IPEndPoint remoteEndPoint, IPEndPoint localEndPoint)
{
Debug.Assert(length == 0);
try
{
_ssl = new SslStream(_inputStream, true);
_authenticateTask = _ssl.AuthenticateAsServerAsync(_serverParameters.Certificate, _serverParameters.ClientCertificateRequired, _serverParameters.Protocols, false).ContinueWith((t, selfObject) =>
{
var self = (SslTransportHandler)selfObject;
self._next.SetRemoteCertificate(_ssl.RemoteCertificate);
}, this, TaskContinuationOptions.OnlyOnRanToCompletion);
_next.FinishAccept(_recvBuffer, _recvOffset, 0, remoteEndPoint, localEndPoint);
}
catch (Exception)
{
Callback.StartDisconnect();
}
}
示例14: DesktopNetworkStream
/// <summary>
/// Initializes a server instance of <see cref="DesktopNetworkStream"/>.
/// </summary>
/// <param name="tcpClient">TCP client.</param>
/// <param name="certificate">Certificate for authenticated connection.</param>
/// <remarks>Ownership of <paramref name="tcpClient"/> remains with the caller, including responsibility for
/// disposal. Therefore, a handle to <paramref name="tcpClient"/> is <em>not</em> stored when <see cref="DesktopNetworkStream"/>
/// is initialized with this server-side constructor.</remarks>
internal DesktopNetworkStream(TcpClient tcpClient, X509Certificate certificate)
{
this.Host = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address.ToString();
this.Port = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Port;
Stream stream = tcpClient.GetStream();
if (certificate != null)
{
var ssl = new SslStream(stream, false);
#if NETSTANDARD
ssl.AuthenticateAsServerAsync(certificate, false, SslProtocols.Tls, false).Wait();
#else
ssl.AuthenticateAsServer(certificate, false, SslProtocols.Tls, false);
#endif
stream = ssl;
}
this.networkStream = stream;
}
示例15: InitializeConnectionAsync
async protected override Task InitializeConnectionAsync(TcpSocket Client)
{
var Stream = new SslStream(
innerStream: Client.Stream,
leaveInnerStreamOpen: false,
userCertificateValidationCallback: (Sender, Certificate, Chain, SslPolicyErrors) =>
{
//Console.WriteLine("userCertificateValidationCallback");
return true;
},
userCertificateSelectionCallback: (Sender, TargetHost, LocalCertificates, RemoteCertificate, AcceptableIssuers) =>
{
//Console.WriteLine("Host: '{0}'", targetHost);
//Console.WriteLine(String.Join(",", acceptableIssuers));
if (HostCertificates.ContainsKey(TargetHost))
{
return HostCertificates[TargetHost];
}
else
{
return DefaultX509Certificate;
}
}
);
await Stream.AuthenticateAsServerAsync(DefaultX509Certificate);
//await Stream.AuthenticateAsServerAsync(X509Certificate, true, SslProtocols.Tls, true);
Client.UnsafeSetStream(Stream);
}