本文整理汇总了C#中System.Net.Security.SslStream.BeginAuthenticateAsClient方法的典型用法代码示例。如果您正苦于以下问题:C# SslStream.BeginAuthenticateAsClient方法的具体用法?C# SslStream.BeginAuthenticateAsClient怎么用?C# SslStream.BeginAuthenticateAsClient使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Security.SslStream
的用法示例。
在下文中一共展示了SslStream.BeginAuthenticateAsClient方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ReconTest
public void ReconTest()
{
MonoCatConfig config = new MonoCatConfig()
{
Name = "monocat",
Nick = "monocat",//"monocat" + DateTime.Now.Second,
Server = "kornbluth.freenode.net",
Port = 6697,
Cipher = "blowfish",
ChannelList = new String[] { "#shrew-dev", "#screenage" }
};
TcpClient tcpClient = new TcpClient(config.Server, config.Port);
SslStream stream = new SslStream(tcpClient.GetStream(), false, new RemoteCertificateValidationCallback((a, b, c, d) => { return true; }));
Boolean visited = false;
var async = stream.BeginAuthenticateAsClient(config.Server, (result) =>
{
var s = (SslStream)result.AsyncState;
s.EndAuthenticateAsClient(result);
visited = true;
Trace.TraceInformation("Auth req finished.");
}, stream);
Trace.TraceInformation("Sent auth req.");
Thread.Sleep(1000);
Assert.IsTrue(stream.IsAuthenticated);
Assert.IsTrue(stream.IsEncrypted);
Assert.IsTrue(visited);
}
示例2: OnGetSocket
protected override void OnGetSocket(SocketAsyncEventArgs e)
{
try
{
#if SILVERLIGHT
var sslStream = new SslStream(new NetworkStream(Client));
sslStream.BeginAuthenticateAsClient(HostName, OnAuthenticated, sslStream);
#else
var securityOption = Security;
if (securityOption == null)
{
throw new Exception("securityOption was not configured");
}
#if NETSTANDARD
AuthenticateAsClientAsync(new SslStream(new NetworkStream(Client), false, ValidateRemoteCertificate), Security);
#else
var sslStream = new SslStream(new NetworkStream(Client), false, ValidateRemoteCertificate);
sslStream.BeginAuthenticateAsClient(HostName, securityOption.Certificates, securityOption.EnabledSslProtocols, false, OnAuthenticated, sslStream);
#endif
#endif
}
catch (Exception exc)
{
if (!IsIgnorableException(exc))
OnError(exc);
}
}
示例3: AuthenticateAsClient
public Task AuthenticateAsClient(X509Certificate2 certificate)
{
var ssl = new SslStream(Stream, false, (sender, x509Certificate, chain, errors) =>
{
if (errors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch))
{
return true;
}
// if (errors == SslPolicyErrors.None)
//return true;
return true;
}, null);
var tempStream = new SslStreamWrapper(ssl);
Stream = tempStream;
Func<AsyncCallback, object, IAsyncResult> begin =
(cb, s) => ssl.BeginAuthenticateAsClient(this.RemoteIpAddress,
new X509Certificate2Collection(certificate),SslProtocols.Tls, false, cb, s);
var task = Task.Factory.FromAsync(begin, ssl.EndAuthenticateAsClient, null);
return task;
}
示例4: OnGetSocket
protected override void OnGetSocket(SocketAsyncEventArgs e)
{
try
{
var sslStream = new SslStream(new NetworkStream(Client), false, ValidateRemoteCertificate);
sslStream.BeginAuthenticateAsClient(HostName, OnAuthenticated, sslStream);
}
catch (Exception exc)
{
if (!IsIgnorableException(exc))
OnError(exc);
}
}
示例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: AuthenticateAsClient
public Task AuthenticateAsClient()
{
var ssl = new SslStream(Stream, false, (sender, x509Certificate, chain, errors) =>
{
if (errors == SslPolicyErrors.None)
return true;
return false;
}, null);
var tempStream = new SslStreamWrapper(ssl);
Stream = tempStream;
Func<AsyncCallback, object, IAsyncResult> begin =
(cb, s) => ssl.BeginAuthenticateAsClient(this._uri.Host, cb, s);
var task = Task.Factory.FromAsync(begin, ssl.EndAuthenticateAsClient, null);
return task;
}
示例7: OnGetSocket
protected override void OnGetSocket(SocketAsyncEventArgs e)
{
try
{
#if !SILVERLIGHT
var sslStream = new SslStream(new NetworkStream(Client), false, ValidateRemoteCertificate);
sslStream.BeginAuthenticateAsClient(HostName, new X509CertificateCollection(), m_EnabledSslProtocols, false, OnAuthenticated, sslStream);
#else
var sslStream = new SslStream(new NetworkStream(Client));
sslStream.BeginAuthenticateAsClient(HostName, OnAuthenticated, sslStream);
#endif
}
catch (Exception exc)
{
if (!IsIgnorableException(exc))
OnError(exc);
}
}
示例8: ConnectCallback
private void ConnectCallback(IAsyncResult ar)
{
try
{
this.client.EndConnect(ar);
}
catch (Exception ex)
{
this.ConnectionError(ex);
return;
}
if (this.tls)
{
this.State = MqttState.StartingEncryption;
SslStream SslStream = new SslStream(this.client.GetStream(), false, this.RemoteCertificateValidationCallback);
this.stream = SslStream;
SslStream.BeginAuthenticateAsClient(this.host, null, SslProtocols.Tls, true, this.AuthenticateAsClientCallback, null);
}
else
{
this.stream = this.client.GetStream();
this.CONNECT(KeepAliveTimeSeconds);
}
}
示例9: InitializeCryptService
protected void InitializeCryptService(BaseSocketConnection connection)
{
//----- None!
if (connection.EncryptType == EncryptType.etNone || connection.EncryptType == EncryptType.etBase64)
{
FHost.FireOnConnected(connection);
}
//----- Symmetric!
if (connection.EncryptType == EncryptType.etRijndael || connection.EncryptType == EncryptType.etTripleDES)
{
if (FHost.HostType == HostType.htClient)
{
//----- Get RSA provider!
RSACryptoServiceProvider serverPublicKey;
RSACryptoServiceProvider clientPrivateKey = new RSACryptoServiceProvider();
byte[] signMessage;
FCryptoService.OnSymmetricAuthenticate(connection, out serverPublicKey, out signMessage);
//----- Generates symmetric algoritm!
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
{
//.........这里部分代码省略.........
示例10: onConnect
private void onConnect(IAsyncResult res)
{
try
{
socket.EndConnect(res);
stream = new NetworkStream(socket);
if (usesSSL)
{
sslStream = new SslStream(stream, false, onCertificateValidate);
sslStream.BeginAuthenticateAsClient(serverName, onAuthenticate, null);
stream = sslStream;
}
else
{
OnConnect();
waitForData();
}
}
catch (SocketException e)
{
OnConnectFailed(ConnectError.SocketError, e.ErrorCode);
}
catch (Exception e)
{
OnConnectFailed(ConnectError.SocketError, null);
System.Diagnostics.Debug.WriteLine("Connect failed: " + e.Message);
throw;
}
}
示例11: 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);
}
}
}
示例12: TestNetworkStream
public void TestNetworkStream()
{
EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2021);
var resetEvent = new AutoResetEvent(false);
var args = new SocketAsyncEventArgs();
args.RemoteEndPoint = serverAddress;
args.Completed += (sender, e) =>
{
resetEvent.Set();
};
Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, args);
resetEvent.WaitOne();
var encoding = new UTF8Encoding();
using (Socket socket = args.ConnectSocket)
{
var socketStream = new SslStream(new NetworkStream(socket));
socketStream.BeginAuthenticateAsClient("localhost", new AsyncCallback(r =>
{
resetEvent.Set();
}), null);
resetEvent.WaitOne();
using (var reader = new StreamReader(socketStream, encoding, true))
using (var writer = new StreamWriter(socketStream, encoding, 1024 * 8))
{
string welcomeString = reader.ReadLine();
Console.WriteLine("Welcome: " + welcomeString);
char[] chars = new char[] { 'a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E', 'f', 'F', 'g', 'G', 'h', 'H' };
Random rd = new Random(1);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 50; i++)
{
sb.Append(chars[rd.Next(0, chars.Length - 1)]);
string command = sb.ToString();
writer.WriteLine("ECHO " + command);
writer.Flush();
string echoMessage = reader.ReadLine();
Console.WriteLine("C:" + echoMessage);
Assert.AreEqual(command, echoMessage);
}
}
}
}
示例13: beginAuthenticate
private bool beginAuthenticate(IceInternal.AsyncCallback callback, object state)
{
NetworkStream ns = new NetworkStream(_fd, true);
_stream = new SslStream(ns, false, new RemoteCertificateValidationCallback(validationCallback), null);
try
{
if(_adapterName == null)
{
//
// Client authentication.
//
_writeResult = _stream.BeginAuthenticateAsClient(_host, _instance.certs(),
_instance.protocols(),
_instance.checkCRL() > 0,
delegate(IAsyncResult result)
{
if(!result.CompletedSynchronously)
{
callback(result.AsyncState);
}
}, state);
}
else
{
//
// Server authentication.
//
// Get the certificate collection and select the first one.
//
X509Certificate2Collection certs = _instance.certs();
X509Certificate2 cert = null;
if(certs.Count > 0)
{
cert = certs[0];
}
_writeResult = _stream.BeginAuthenticateAsServer(cert, _verifyPeer > 1, _instance.protocols(),
_instance.checkCRL() > 0,
delegate(IAsyncResult result)
{
if(!result.CompletedSynchronously)
{
callback(result.AsyncState);
}
}, state);
}
}
catch(IOException ex)
{
if(IceInternal.Network.connectionLost(ex))
{
//
// This situation occurs when connectToSelf is called; the "remote" end
// closes the socket immediately.
//
throw new Ice.ConnectionLostException();
}
throw new Ice.SocketException(ex);
}
catch(AuthenticationException ex)
{
Ice.SecurityException e = new Ice.SecurityException(ex);
e.reason = ex.Message;
throw e;
}
catch(Exception ex)
{
throw new Ice.SyscallException(ex);
}
Debug.Assert(_writeResult != null);
return _writeResult.CompletedSynchronously;
}
示例14: ConnectCallback
private void ConnectCallback( IAsyncResult ar )
{
bool retry = false;
try {
TcpClient.EndConnect( ar );
}
catch ( SocketException e ) {
Debug.Print( "ServerConnector.ConnectCallback: TcpClient.EndConnect: caught SocketException, error code {0}:\n{1}", e.ErrorCode, e );
OnConnectionAttemptFailed( CurrentEndPoint, e );
retry = true;
}
catch ( Exception e ) {
Debug.Print( "ServerConnector.ConnectCallback: TcpClient.EndConnect: caught exception:\n{0}", e );
OnConnectionAttemptFailed( CurrentEndPoint, e );
retry = true;
}
if ( retry ) {
TryEstablishConnection( );
return;
}
EndPointEnumerator.Dispose( );
EndPoints = null;
Debug.Print( "ServerConnector.ConnectCallback: Connected!" );
SocketRegistry.Register( TcpClient.Client.LocalEndPoint as IPEndPoint, TcpClient.Client.RemoteEndPoint as IPEndPoint );
Debug.Print( "ServerConnector.ConnectCallback: Constructing objects." );
var selfUser = new SelfUser {
NickName = Configuration.NickName,
HostName = Configuration.LocalHostName,
RealHostName = Configuration.LocalHostName,
RealName = Configuration.RealName,
UserName = Configuration.UserName,
NickServUserName = Configuration.NickServUserName,
NickServPassword = Configuration.NickServPassword,
};
_server = new Server {
ServerEndPoint = CurrentEndPoint,
SelfUser = selfUser,
ServerHostName = Configuration.ServerHostName,
ServerPassword = Configuration.Password,
};
_protocolHandler = new ProtocolHandler {
TcpClient = TcpClient,
SelfUser = selfUser,
Server = _server,
};
_server.ProtocolHandler = _protocolHandler;
selfUser.Server = _server;
if ( CurrentEndPoint.UseSsl ) {
Debug.Print( "ServerConnector.ConnectCallback: Starting SSL." );
_sslStream = new SslStream( TcpClient.GetStream( ), true, ServerCertificateValidationCallback, LocalCertificateSelectionCallback, EncryptionPolicy.RequireEncryption );
try {
_sslStream.BeginAuthenticateAsClient( Configuration.ServerHostName, CertificateCollection, SslProtocols.Default, true, AuthenticateAsClientCallback, null );
}
catch ( Exception e ) {
Debug.Print( "ServerConnector.ConnectCallback: Caught exception calling BeginAuthenticateAsClient:\n{0}", e );
throw;
}
} else {
FinishConnection( TcpClient.GetStream( ) );
}
}
示例15: OnConnected
/// <summary>
/// Initializes the connection
/// </summary>
/// <param name="connection"></param>
internal void OnConnected(BaseSocketConnection connection)
{
if (Disposed || !connection.Active)
return;
try
{
switch (connection.Context.EventProcessing)
{
case EventProcessing.epEncrypt:
switch (connection.Context.Creator.Context.EncryptType)
{
case EncryptType.etRijndael:
if (connection.Context.Host.Context.HostType == HostType.htClient)
{
ISocketSecurityProvider socketSecurityProvider = new SocketRSACryptoProvider(connection, null);
MemoryStream m = socketSecurityProvider.EcryptForClient();
connection.BeginSend(m.ToArray());
}
else
{
connection.BeginReceive();
}
break;
case EncryptType.etSSL:
if (connection.Context.Host.Context.HostType == HostType.htClient)
{
//----- Get SSL items
X509Certificate2Collection certs = null;
string serverName = null;
bool checkRevocation = true;
connection.Context.Creator.Context.CryptoService.OnSSLClientAuthenticate(connection, out serverName, ref certs, ref checkRevocation);
//----- Authenticate SSL!
SslStream ssl = new SslStream(new NetworkStream(connection.Context.SocketHandle), true, new RemoteCertificateValidationCallback(connection.Context.Creator.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.Tls, checkRevocation, new AsyncCallback(SslAuthenticateCallback), new AuthenticateCallbackData(connection, ssl, HostType.htClient));
}
}
else
{
//----- Get SSL items!
X509Certificate2 cert = null;
bool clientAuthenticate = false;
bool checkRevocation = true;
connection.Context.Creator.Context.CryptoService.OnSSLServerAuthenticate(connection, out cert, out clientAuthenticate, ref checkRevocation);
//----- Authneticate SSL!
SslStream ssl = new SslStream(new NetworkStream(connection.Context.SocketHandle));
ssl.BeginAuthenticateAsServer(cert, clientAuthenticate, System.Security.Authentication.SslProtocols.Default, checkRevocation, new AsyncCallback(SslAuthenticateCallback), new AuthenticateCallbackData(connection, ssl, HostType.htServer));
}
break;
}
break;
case EventProcessing.epProxy:
ProxyInfo proxyInfo = ((SocketConnector)connection.Context.Creator).ProxyInfo;
IPEndPoint endPoint = ((SocketConnector)connection.Context.Creator).Context.RemotEndPoint;
byte[] proxyBuffer = ProxyUtils.GetProxyRequestData(proxyInfo, endPoint);
connection.BeginSend(proxyBuffer);
break;
}
}
catch (Exception ex)
{
FireOnException(connection, ex);
}
}