本文整理汇总了C#中SslStream.Write方法的典型用法代码示例。如果您正苦于以下问题:C# SslStream.Write方法的具体用法?C# SslStream.Write怎么用?C# SslStream.Write使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SslStream
的用法示例。
在下文中一共展示了SslStream.Write方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SslStream_StreamToStream_Successive_ClientWrite_Sync_Success
public void SslStream_StreamToStream_Successive_ClientWrite_Sync_Success()
{
byte[] recvBuf = new byte[_sampleMsg.Length];
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
using (var serverSslStream = new SslStream(serverStream))
{
bool result = DoHandshake(clientSslStream, serverSslStream);
Assert.True(result, "Handshake completed.");
clientSslStream.Write(_sampleMsg);
serverSslStream.Read(recvBuf, 0, _sampleMsg.Length);
Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify first read data is as expected.");
clientSslStream.Write(_sampleMsg);
serverSslStream.Read(recvBuf, 0, _sampleMsg.Length);
Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify second read data is as expected.");
}
}
示例2: SslStream_StreamToStream_Successive_ClientWrite_Success
public void SslStream_StreamToStream_Successive_ClientWrite_Success()
{
byte[] recvBuf = new byte[sampleMsg.Length];
MockNetwork network = new MockNetwork();
using (var clientStream = new FakeNetworkStream(false, network))
using (var serverStream = new FakeNetworkStream(true, network))
using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
using (var serverSslStream = new SslStream(serverStream))
{
bool result = DoHandshake(clientSslStream, serverSslStream);
Assert.True(result, "Handshake completed.");
clientSslStream.Write(sampleMsg);
serverSslStream.Read(recvBuf, 0, sampleMsg.Length);
clientSslStream.Write(sampleMsg);
// TODO Test Issue #3802
// The condition on which read method (UpdateReadStream) in FakeNetworkStream does a network read is flawed.
// That works fine in single read/write but fails in multi read write as stream size can be more, but real data can be < stream size.
// So I am doing an explicit read here. This issue is specific to test only & irrespective of xplat.
serverStream.DoNetworkRead();
serverSslStream.Read(recvBuf, 0, sampleMsg.Length);
Assert.True(VerifyOutput(recvBuf, sampleMsg), "verify second read data is as expected.");
}
}
示例3: SslStream_StreamToStream_LargeWrites_Sync_Success
public void SslStream_StreamToStream_LargeWrites_Sync_Success(bool randomizedData)
{
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer:false))
using (var serverStream = new VirtualNetworkStream(network, isServer:true))
using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
using (var serverSslStream = new SslStream(serverStream))
{
Assert.True(DoHandshake(clientSslStream, serverSslStream), "Handshake complete");
byte[] largeMsg = new byte[4096 * 5]; // length longer than max read chunk size (16K + headers)
if (randomizedData)
{
new Random().NextBytes(largeMsg); // not very compressible
}
else
{
for (int i = 0; i < largeMsg.Length; i++)
{
largeMsg[i] = (byte)i; // very compressible
}
}
byte[] receivedLargeMsg = new byte[largeMsg.Length];
// First do a large write and read blocks at a time
clientSslStream.Write(largeMsg);
int bytesRead = 0, totalRead = 0;
while (totalRead < largeMsg.Length &&
(bytesRead = serverSslStream.Read(receivedLargeMsg, totalRead, receivedLargeMsg.Length - totalRead)) != 0)
{
totalRead += bytesRead;
}
Assert.Equal(receivedLargeMsg.Length, totalRead);
Assert.Equal(largeMsg, receivedLargeMsg);
// Then write again and read bytes at a time
clientSslStream.Write(largeMsg);
foreach (byte b in largeMsg)
{
Assert.Equal(b, serverSslStream.ReadByte());
}
}
}
示例4: SslStream_StreamToStream_Write_ReadByte_Success
public void SslStream_StreamToStream_Write_ReadByte_Success()
{
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer:false))
using (var serverStream = new VirtualNetworkStream(network, isServer:true))
using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
using (var serverSslStream = new SslStream(serverStream))
{
bool result = DoHandshake(clientSslStream, serverSslStream);
Assert.True(result, "Handshake completed.");
for (int i = 0; i < 3; i++)
{
clientSslStream.Write(_sampleMsg);
foreach (byte b in _sampleMsg)
{
Assert.Equal(b, serverSslStream.ReadByte());
}
}
}
}
示例5: SslStream_StreamToStream_LargeWrites_Sync_Success
public void SslStream_StreamToStream_LargeWrites_Sync_Success()
{
MockNetwork network = new MockNetwork();
using (var clientStream = new FakeNetworkStream(false, network))
using (var serverStream = new FakeNetworkStream(true, network))
using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
using (var serverSslStream = new SslStream(serverStream))
{
Assert.True(DoHandshake(clientSslStream, serverSslStream), "Handshake complete");
byte[] largeMsg = Enumerable.Range(0, 4096 * 5).Select(i => (byte)i).ToArray();
byte[] receivedLargeMsg = new byte[largeMsg.Length];
// First do a large write and read blocks at a time
clientSslStream.Write(largeMsg);
int bytesRead = 0, totalRead = 0;
while (totalRead < largeMsg.Length &&
(bytesRead = serverSslStream.Read(receivedLargeMsg, totalRead, receivedLargeMsg.Length - totalRead)) != 0)
{
totalRead += bytesRead;
}
Assert.Equal(receivedLargeMsg.Length, totalRead);
Assert.Equal(largeMsg, receivedLargeMsg);
// Then write again and read bytes at a time
clientSslStream.Write(largeMsg);
foreach (byte b in largeMsg)
{
Assert.Equal(b, serverSslStream.ReadByte());
}
}
}
示例6: SslStream_StreamToStream_Successive_ClientWrite_WithZeroBytes_Success
public void SslStream_StreamToStream_Successive_ClientWrite_WithZeroBytes_Success()
{
byte[] recvBuf = new byte[_sampleMsg.Length];
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate))
using (var serverSslStream = new SslStream(serverStream))
{
bool result = DoHandshake(clientSslStream, serverSslStream);
Assert.True(result, "Handshake completed.");
clientSslStream.Write(Array.Empty<byte>());
clientSslStream.WriteAsync(Array.Empty<byte>(), 0, 0).Wait();
clientSslStream.Write(_sampleMsg);
int bytesRead = 0;
while (bytesRead < _sampleMsg.Length)
{
bytesRead += serverSslStream.Read(recvBuf, bytesRead, _sampleMsg.Length - bytesRead);
}
Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify first read data is as expected.");
clientSslStream.Write(_sampleMsg);
clientSslStream.WriteAsync(Array.Empty<byte>(), 0, 0).Wait();
clientSslStream.Write(Array.Empty<byte>());
bytesRead = 0;
while (bytesRead < _sampleMsg.Length)
{
bytesRead += serverSslStream.Read(recvBuf, bytesRead, _sampleMsg.Length - bytesRead);
}
Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify second read data is as expected.");
}
}
示例7: iOSAPNS
/*
public string iOSAPNS(String DeviceTokenlistString, String content)
{
APNSSender test = new APNSSender();
return test.SendAPNS(DeviceTokenlistString, content);
}
*/
/// <summary>
/// 傳入 DeviceToken 與 要傳的訊息
/// </summary>
/// 手機上方 最多五則
/// 警報日期:2015/03/04 11:55:00 \n類型/嚴重度:超速 / [嚴重]\n名稱:連續超速70km 3分鐘\n車號/駕駛人:kw-car03 / 易大師
/// APNS 限制 payload 256bytes 超過就不發了 不过由于aps,alert等会占用部分长度,所以一般剩余140-200之间。
/// 實測560個字都傳的出去 只是手機顯示最多4行而已
/// <param name="inDeviceToken ID"> 手機端 Registration ID</param>
/// <param name="inMessage">訊息內容</param>
public String SendAPNS(String inDeviceToken, String inMessage)
{
//http://blog.sina.com.cn/s/blog_6f9a9718010128hi.html
//太連續用單一個發送 會被蘋果認為是 dos 攻擊 而中斷連線 用單一個多次發送 遇到錯誤的token會中斷發送 接下來的都會無法發送
System.Threading.Thread.Sleep(50);
// str = "{\"aps\":{\"alert\":\"" + s2 + "\",\"badge\":10,\"sound\":\"default\"}}";
// badge 設為 0 就不會出現數字
mAPNSMessage = "{\"aps\":{\"alert\":\"" + inMessage + "\",\"badge\":0,\"sound\":\"default\"}}";
int port = 2195;
// string certificatepath = ConfigurationManager.AppSettings["p12FilePath"];
// string certificatepath = "D:\\VisualStudioProject\\Fleet\\new_aps_developer.p12";
//string certificatepath = "D:\\VisualStudioProject\\Fleet\\distribution_aps_developer.p12";
// string certificatepath = "D:\\VisualStudioProject\\Fleet\\fleetivity_aps_developer.p12";
// string certificatepath = "C:\\inetpub\\DotNetNuke\\fleetivity_aps_developer.p12";
string certificatepath = HttpContext.Current.Server.MapPath("/") + "certificate\\fleetivity_aps_developer.p12";
string password = "abc123";
// Apple development server address
string hostIP = "gateway.sandbox.push.apple.com";//
string p12Filename = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, certificatepath);
certificate = new X509Certificate2(System.IO.File.ReadAllBytes(p12Filename), password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
certificates = new X509CertificateCollection();
certificates.Add(certificate);
if (certificate.ToString().Contains("Production"))
{
hostIP = "gateway.push.apple.com";
}
else
{
hostIP = "gateway.sandbox.push.apple.com";
}
TcpClient apnsClient = new TcpClient();
apnsClient.Connect(hostIP, port);
SslStream apnsStream = new SslStream(apnsClient.GetStream(), false, new RemoteCertificateValidationCallback(validateServerCertificate), new LocalCertificateSelectionCallback(selectLocalCertificate));
try
{
apnsStream.AuthenticateAsClient(hostIP, certificates, System.Security.Authentication.SslProtocols.Tls, false);
}
catch (System.Security.Authentication.AuthenticationException ex)
{
Console.WriteLine("error:" + ex.Message);
}
if (!apnsStream.IsMutuallyAuthenticated)
{
Console.WriteLine("error:" + "Ssl Stream Failed to Authenticate");
}
if (!apnsStream.CanWrite)
{
Console.WriteLine("error:" + "Ssl Stream is not Writable");
}
Byte[] message = ToBytes(inDeviceToken);
apnsStream.Write(message);
return System.Text.Encoding.UTF8.GetString(message);
}
示例8: 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);
}
示例9: TestSyncIntermediate
public void TestSyncIntermediate()
{
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()))
{
Console.WriteLine("Server> authenticate");
sslStream.AuthenticateAsServer(
_ctx.ServerCertificate,
false,
null,
SslProtocols.Default,
SslStrength.Low,
false
);
Console.WriteLine("Server> CurrentCipher: {0}", sslStream.Ssl.CurrentCipher.Name);
Assert.AreEqual("DES-CBC-SHA", sslStream.Ssl.CurrentCipher.Name);
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()))
{
Console.WriteLine("Client> authenticate");
sslStream.AuthenticateAsClient(
"localhost",
null,
null,
SslProtocols.Default,
SslStrength.Low,
false
);
Console.WriteLine("Client> CurrentCipher: {0}", sslStream.Ssl.CurrentCipher.Name);
Assert.AreEqual("DES-CBC-SHA", sslStream.Ssl.CurrentCipher.Name);
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");
}
});
serverTask.Wait();
clientTask.Wait();
}
示例10: WriteJSONMessage
static void WriteJSONMessage(SslStream sslStream, JSONEvent eventObj)
{
string message = JsonConvert.SerializeObject(eventObj);
//Console.WriteLine(message);
byte[] msg = Encoding.UTF8.GetBytes(message);
sslStream.Write(msg);
sslStream.Flush();
}
示例11: 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();
}