本文整理汇总了C#中SslStream.AuthenticateAsClient方法的典型用法代码示例。如果您正苦于以下问题:C# SslStream.AuthenticateAsClient方法的具体用法?C# SslStream.AuthenticateAsClient怎么用?C# SslStream.AuthenticateAsClient使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SslStream
的用法示例。
在下文中一共展示了SslStream.AuthenticateAsClient方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
static void Main(string[] args)
{
string host = "localhost";
if (args.Length > 0)
host = args[0];
SslProtocols protocol = SslProtocols.Tls;
if (args.Length > 1) {
switch (args [1].ToUpper ()) {
case "SSL":
protocol = SslProtocols.Ssl3;
break;
}
}
X509CertificateCollection certificates = null;
if (args.Length > 2) {
string password = null;
if (args.Length > 3)
password = args [3];
p12 = Mono.Security.X509.PKCS12.LoadFromFile(args [2], password);
certificates = new X509CertificateCollection ();
foreach (Mono.Security.X509.X509Certificate cert in p12.Certificates) {
certificates.Add(new X509Certificate2(args [2], password));
break;
}
}
TcpClient client = new TcpClient ();
client.Connect (host, 4433);
SslStream ssl = new SslStream (client.GetStream(), false, new RemoteCertificateValidationCallback (CertificateValidation), new LocalCertificateSelectionCallback (ClientCertificateSelection));
ssl.AuthenticateAsClient (host, certificates, protocol, false);
StreamWriter sw = new StreamWriter (ssl, System.Text.Encoding.ASCII);
sw.WriteLine ("GET /clientcert.aspx{0}", Environment.NewLine);
sw.Flush ();
StreamReader sr = new StreamReader (ssl);
Console.WriteLine (sr.ReadToEnd ());
}
示例2: Connect
/// <summary>
/// Connect to the registry end point
/// </summary>
public void Connect()
{
var client = new TcpClient(EPP_REGISTRY_COM, PORT);
stream = new SslStream(client.GetStream(), false, ValidateServerCertificate);
if (clientCertificate != null)
{
var clientCertificates = new X509CertificateCollection {clientCertificate};
stream.AuthenticateAsClient(EPP_REGISTRY_COM, clientCertificates, SslProtocols.Ssl3, false);
}
else
{
stream.AuthenticateAsClient(EPP_REGISTRY_COM);
}
}
示例3: Connect
/// <summary>
/// Connect to the registry end point
/// </summary>
public void Connect(SslProtocols sslProtocols)
{
var client = new TcpClient(EPP_REGISTRY_COM, PORT);
stream = new SslStream(client.GetStream(), false, ValidateServerCertificate)
{
ReadTimeout = READ_TIMEOUT,
WriteTimeout = WRITE_TIMEOUT
};
if (clientCertificate != null)
{
var clientCertificates = new X509CertificateCollection {clientCertificate};
stream.AuthenticateAsClient(EPP_REGISTRY_COM, clientCertificates, sslProtocols, false);
}
else
{
stream.AuthenticateAsClient(EPP_REGISTRY_COM);
}
}
示例4: ServerNoEncryption_ClientRequireEncryption_NoConnect
public async Task ServerNoEncryption_ClientRequireEncryption_NoConnect()
{
using (var serverNoEncryption = new DummyTcpServer(
new IPEndPoint(IPAddress.Loopback, 0), EncryptionPolicy.NoEncryption))
using (var client = new TcpClient())
{
await client.ConnectAsync(serverNoEncryption.RemoteEndPoint.Address, serverNoEncryption.RemoteEndPoint.Port);
using (var sslStream = new SslStream(client.GetStream(), false, AllowAnyServerCertificate, null, EncryptionPolicy.RequireEncryption))
{
Assert.Throws<IOException>(() =>
{
sslStream.AuthenticateAsClient("localhost", null, SslProtocolSupport.DefaultSslProtocols, false);
});
}
}
}
示例5: TransportContext_ConnectToServerWithSsl_GetExpectedChannelBindings
public async Task TransportContext_ConnectToServerWithSsl_GetExpectedChannelBindings()
{
using (var testServer = new DummyTcpServer(
new IPEndPoint(IPAddress.Loopback, 0), EncryptionPolicy.RequireEncryption))
using (var client = new TcpClient())
{
await client.ConnectAsync(testServer.RemoteEndPoint.Address, testServer.RemoteEndPoint.Port);
using (var sslStream = new SslStream(client.GetStream(), false, AllowAnyServerCertificate, null, EncryptionPolicy.RequireEncryption))
{
sslStream.AuthenticateAsClient("localhost", null, SslProtocols.Tls, false);
TransportContext context = sslStream.TransportContext;
CheckTransportContext(context);
}
}
}
示例6: ServerAllowNoEncryption_ClientRequireEncryption_ConnectWithEncryption
public async Task ServerAllowNoEncryption_ClientRequireEncryption_ConnectWithEncryption()
{
using (var serverAllowNoEncryption = new DummyTcpServer(
new IPEndPoint(IPAddress.Loopback, 0), EncryptionPolicy.AllowNoEncryption))
using (var client = new TcpClient())
{
await client.ConnectAsync(serverAllowNoEncryption.RemoteEndPoint.Address, serverAllowNoEncryption.RemoteEndPoint.Port);
using (var sslStream = new SslStream(client.GetStream(), false, AllowAnyServerCertificate, null, EncryptionPolicy.RequireEncryption))
{
sslStream.AuthenticateAsClient("localhost", null, TestConfiguration.DefaultSslProtocols, false);
_log.WriteLine("Client({0}) authenticated to server({1}) with encryption cipher: {2} {3}-bit strength",
client.Client.LocalEndPoint, client.Client.RemoteEndPoint,
sslStream.CipherAlgorithm, sslStream.CipherStrength);
Assert.NotEqual(CipherAlgorithmType.Null, sslStream.CipherAlgorithm);
Assert.True(sslStream.CipherStrength > 0);
}
}
}
示例7: ImapClient
public ImapClient(string hostname, int port, string username, string password, bool ssl = false)
{
this.hostname = hostname;
this.username = username;
this.password = password;
this.port = port;
this.ssl = ssl;
RemoteCertificateValidationCallback validate = null;
TcpClient client = new TcpClient(hostname, port);
stream = client.GetStream();
SslStream sslStream = new SslStream(stream, false, validate ??
((sender, cert, chain, err) => true));
sslStream.AuthenticateAsClient(hostname);
stream = sslStream;
List<string> str = readstreamdata("* OK");
string tagStr = GetTag();
writestreamdata(tagStr + "LOGIN " + QuoteString(username) + " " + QuoteString(password) + "\r\n");
readstreamdata(tagStr + "OK");
}
示例8: ClientDefaultEncryption_ServerAllowNoEncryption_ConnectWithEncryption
public void ClientDefaultEncryption_ServerAllowNoEncryption_ConnectWithEncryption()
{
using (var serverAllowNoEncryption = new DummyTcpServer(
new IPEndPoint(IPAddress.Loopback, 0), EncryptionPolicy.AllowNoEncryption))
using (var client = new TcpClient())
{
client.Connect(serverAllowNoEncryption.RemoteEndPoint);
using (var sslStream = new SslStream(client.GetStream(), false, AllowAnyServerCertificate, null))
{
sslStream.AuthenticateAsClient("localhost", null, TestConfiguration.DefaultSslProtocols, false);
_log.WriteLine("Client({0}) authenticated to server({1}) with encryption cipher: {2} {3}-bit strength",
client.Client.LocalEndPoint, client.Client.RemoteEndPoint,
sslStream.CipherAlgorithm, sslStream.CipherStrength);
Assert.True(sslStream.CipherAlgorithm != CipherAlgorithmType.Null, "Cipher algorithm should not be NULL");
Assert.True(sslStream.CipherStrength > 0, "Cipher strength should be greater than 0");
}
}
}
示例9: ServerAllowNoEncryption_ClientNoEncryption_ConnectWithNoEncryption
public void ServerAllowNoEncryption_ClientNoEncryption_ConnectWithNoEncryption()
{
using (var serverAllowNoEncryption = new DummyTcpServer(
new IPEndPoint(IPAddress.Loopback, 0), EncryptionPolicy.AllowNoEncryption))
using (var client = new TcpClient())
{
client.Connect(serverAllowNoEncryption.RemoteEndPoint);
using (var sslStream = new SslStream(client.GetStream(), false, AllowAnyServerCertificate, null, EncryptionPolicy.NoEncryption))
{
sslStream.AuthenticateAsClient("localhost", null, TestConfiguration.DefaultSslProtocols, false);
_log.WriteLine("Client({0}) authenticated to server({1}) with encryption cipher: {2} {3}-bit strength",
client.Client.LocalEndPoint, client.Client.RemoteEndPoint,
sslStream.CipherAlgorithm, sslStream.CipherStrength);
CipherAlgorithmType expected = CipherAlgorithmType.Null;
Assert.Equal(expected, sslStream.CipherAlgorithm);
Assert.Equal(0, sslStream.CipherStrength);
}
}
}
示例10: Main
static void Main(string[] args)
{
if (args.Length != 1)
Environment.Exit(1);
Uri uri = new Uri(args[0]);
string server = uri.Host;
int port = uri.Port;
if (port < 0)
port = 443;
try {
TcpClient client = new TcpClient(server, port);
SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback (ValidateServerCertificate), null);
sslStream.AuthenticateAsClient(server);
} catch (Exception e) {
Console.WriteLine("Failed to get certificate. {0}", e);
}
try {
if (data != null) {
string filePath = System.IO.Path.GetTempPath() + "server.cer";
Console.WriteLine("Get certificate to {0}", filePath);
File.WriteAllBytes(filePath, data);
Process process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.FileName = "CertUtil";
process.StartInfo.Arguments = "-addstore root \"" + filePath + "\"";
process.Start();
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
Console.WriteLine(output);
}
} catch (Exception e) {
Console.WriteLine("{0}", e);
}
}
示例11: DoHandshake
protected override bool DoHandshake(SslStream clientSslStream, SslStream serverSslStream)
{
using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate())
{
Task t1 = Task.Run(() => clientSslStream.AuthenticateAsClient(certificate.GetNameInfo(X509NameType.SimpleName, false)));
Task t2 = Task.Run(() => serverSslStream.AuthenticateAsServer(certificate));
return Task.WaitAll(new[] { t1, t2 }, TestConfiguration.PassingTestTimeoutMilliseconds);
}
}
示例12: ConnectAsync
/// <summary>
/// Async connection to the server.
/// </summary>
/// <param name="args">Object type of SocketAsyncEventArgs that determines args for
/// connect. </param>
/// <returns>If connect's state is successfully than true else false.</returns>
public bool ConnectAsync(SocketAsyncEventArgs args)
{
if (_isSecure)
{
DnsEndPoint remoteEndpoint = (DnsEndPoint) args.RemoteEndPoint;
_socket.Connect(remoteEndpoint);
_stream = new NetworkStream(_socket);
_sslStream = new SslStream(_stream, true, ValidateServerCertificate, null);
X509Certificate certificate = new X509Certificate("certificate.pfx");
try
{
_sslStream.AuthenticateAsClient(remoteEndpoint.Host, new X509CertificateCollection(new[] { certificate }), SslProtocols.Tls, false);
}
catch (Exception)
{
// socket was closed forcibly, protocol will handle this
}
return false;
}
else
{
return _socket.ConnectAsync(args);
}
}
示例13: PerformTls
private void PerformTls()
{
// Create an SSL stream that will close the client's stream.
SecureStream = new SslStream(
Stream,
true,
new RemoteCertificateValidationCallback(ValidateServerCertificate));
// The server name must match the name on the server certificate.
try
{
SecureStream.AuthenticateAsClient(ServerName);
}
catch (AuthenticationException e)
{
Debug.LogError("Exception: " + e.Message);
if (e.InnerException != null)
{
Debug.LogError("Inner exception: " + e.InnerException.Message);
}
// Console.WriteLine("Authentication failed - closing the connection.");
Client.Close();
return;
}
// Authenticated!
string request = @"<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' to='xmpp.livecoding.tv' version='1.0'>";
Debug.Log("Asking to open a new XMPP stream on authenticated SecureStream! " + request);
byte[] message = Encoding.UTF8.GetBytes(request);
// byte[] message = Convert.FromBase64String(@"<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' to='xmpp.livecoding.tv' version='1.0'>");
// Set up new readers and writers.
SecureStream.Write(message);
SecureStream.Flush();
}
示例14: AdvancedClientTest
public void AdvancedClientTest() {
//Initialize delegates for certificate callbacks
clientRemoteCertificateValidationCallback = new RemoteCertificateValidationHandler(ValidateRemoteCert);
clientLocalCertificateSelectionCallback = new LocalCertificateSelectionHandler(clientCertificateSelectionCallback);
try {
testName = "AdvancedClientTest";
client = new TcpClient("localhost", 9000);
// Create the SslStream object with the certificate callbacks
sslStream = new SslStream(client.GetStream(), false, clientRemoteCertificateValidationCallback, clientLocalCertificateSelectionCallback);
// Initialize with client certificate list, and client CA chain
sslStream.AuthenticateAsClient("localhost", testServer.clientCertificateList, testServer.clientCAChain, SslProtocols.Tls, SslStrength.Medium | SslStrength.High, true);
// Verify mutual authentication
if (!sslStream.IsMutuallyAuthenticated) {
Console.WriteLine("{0} failed - Stream is not mutally authenticated", testName);
Shutdown(false);
}
// Verify protocol
if (sslStream.SslProtocol != SslProtocols.Tls) {
Console.WriteLine("{0} failed - negotiated a non Tls connection", testName);
Shutdown(false);
}
// Verify cipher strength
if (sslStream.CipherStrength < 256) {
Console.WriteLine("{0} failed - negotiated less that 256bit cipher", testName);
Console.WriteLine("Cipher={0}\nCipherStrength = {1}", sslStream.CipherAlgorithm.ToString(), sslStream.CipherStrength);
Shutdown(false);
}
// Verify cipher
if (sslStream.CipherAlgorithm != CipherAlgorithmType.Aes256) {
Console.WriteLine("{0} failed - negotiatied cipher wasn't Aes256", testName);
Console.WriteLine("Cipher was {0}, expected {0}", sslStream.CipherAlgorithm.ToString(), CipherAlgorithmType.Aes256.ToString());
Shutdown(false);
}
if (DoClientReadWrite()) {
Shutdown(true);
}
else {
Shutdown(false);
}
}
catch (Exception ex) {
Shutdown(false);
Console.WriteLine(ex);
}
}
示例15: TestSyncAdvanced
public void TestSyncAdvanced()
{
IPEndPoint ep = null;
var evtReady = new AutoResetEvent(false);
var serverTask = Task.Factory.StartNew(() =>
{
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start(5);
ep = (IPEndPoint)listener.LocalEndpoint;
evtReady.Set();
Console.WriteLine("Server> waiting for accept");
using (var tcp = listener.AcceptTcpClient())
using (var sslStream = new SslStream(tcp.GetStream(), false, ValidateRemoteCert))
{
Console.WriteLine("Server> authenticate");
sslStream.AuthenticateAsServer(
_ctx.ServerCertificate,
true,
_ctx.CAChain,
SslProtocols.Tls,
SslStrength.All,
true
);
Console.WriteLine("Server> CurrentCipher: {0}", sslStream.Ssl.CurrentCipher.Name);
Assert.AreEqual("AES256-GCM-SHA384", sslStream.Ssl.CurrentCipher.Name);
Assert.IsTrue(sslStream.IsMutuallyAuthenticated);
Console.WriteLine("Server> rx msg");
var buf = new byte[256];
sslStream.Read(buf, 0, buf.Length);
Assert.AreEqual(clientMessage.ToString(), buf.ToString());
Console.WriteLine("Server> tx msg");
sslStream.Write(serverMessage, 0, serverMessage.Length);
Console.WriteLine("Server> done");
}
listener.Stop();
});
var clientTask = Task.Factory.StartNew(() =>
{
evtReady.WaitOne();
Console.WriteLine("Client> Connecting to: {0}:{1}", ep.Address, ep.Port);
using (var tcp = new TcpClient(ep.Address.ToString(), ep.Port))
using (var sslStream = new SslStream(
tcp.GetStream(),
false,
ValidateRemoteCert,
SelectClientCertificate))
{
Console.WriteLine("Client> authenticate");
sslStream.AuthenticateAsClient(
"localhost",
_ctx.ClientCertificateList,
_ctx.CAChain,
SslProtocols.Tls,
SslStrength.All,
true
);
Console.WriteLine("Client> CurrentCipher: {0}", sslStream.Ssl.CurrentCipher.Name);
Assert.AreEqual("AES256-GCM-SHA384", sslStream.Ssl.CurrentCipher.Name);
Assert.IsTrue(sslStream.IsMutuallyAuthenticated);
Console.WriteLine("Client> tx msg");
sslStream.Write(clientMessage, 0, clientMessage.Length);
Console.WriteLine("Client> rx msg");
var buf = new byte[256];
sslStream.Read(buf, 0, buf.Length);
Assert.AreEqual(serverMessage.ToString(), buf.ToString());
Console.WriteLine("Client> done");
}
});
Task.WaitAll(clientTask, serverTask);
}