本文整理汇总了C#中Org.Mentalis.Security.Ssl.SecureSocket类的典型用法代码示例。如果您正苦于以下问题:C# SecureSocket类的具体用法?C# SecureSocket怎么用?C# SecureSocket使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
SecureSocket类属于Org.Mentalis.Security.Ssl命名空间,在下文中一共展示了SecureSocket类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: Start
public void Start()
{
// create a new ManualResetEvent. This will be used to make the main application
// thread wait until the full server reply has been received.
m_ResetEvent = new ManualResetEvent(false);
// initialize the security options
SecurityOptions options = new SecurityOptions(
SecureProtocol.Ssl3 | SecureProtocol.Tls1, // use SSL3 or TLS1
null, // do not use client authentication
ConnectionEnd.Client, // this is the client side
CredentialVerification.None, // do not check the certificate -- this should not be used in a real-life application :-)
null, // not used with automatic certificate verification
"www.microsoft.com", // this is the common name of the Microsoft web server
SecurityFlags.Default, // use the default security flags
SslAlgorithms.SECURE_CIPHERS, // only use secure ciphers
null); // do not process certificate requests.
try {
// create the securesocket with the specified security options
m_Socket = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options);
// resolve www.microsoft.com
IPEndPoint endpoint = new IPEndPoint(Dns.GetHostEntry("www.microsoft.com").AddressList[0], 443);
// start connecting to www.microsoft.com
m_Socket.BeginConnect(endpoint, new AsyncCallback(this.OnConnect), null);
// wait until the entire web page has been received
m_ResetEvent.WaitOne();
// close the SecureSocket
m_Socket.Close();
} catch {
OnError("Could not connect to the website");
}
}
开发者ID:maikgreubel,项目名称:securitylibrary,代码行数:31,代码来源:AsynchronousSocket.cs
示例2: CreateStream
public static DuplexStream CreateStream()
{
var options = new SecurityOptions(SecureProtocol.Tls1, null, new[] { Protocols.Http1 }, ConnectionEnd.Client);
var socket = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options);
return new Mock<DuplexStream>(socket, false).Object;
}
开发者ID:jamesgodfrey,项目名称:http2-katana,代码行数:7,代码来源:TestHelpers.cs
示例3: Attach
public override void Attach(SecureSocket socket)
{
this.Socket = socket;
this.AlpnExtension = this.Socket.m_Options.ExtensionList.GetExtesionOfType<ALPNExtension>();
AttachToExtension(this.AlpnExtension);
}
开发者ID:jamesgodfrey,项目名称:http2-katana,代码行数:7,代码来源:ALPNExtensionMonitor.cs
示例4: Attach
internal void Attach(SecureSocket socket, ServerHandshakeLayer layer)
{
this.Socket = socket;
this.Layer = layer;
layer.OnHandshakeFinished += this.Socket.HandshakeFinishedHandler;
}
开发者ID:nunnun,项目名称:http2-katana,代码行数:7,代码来源:SslTlsHandshakeMonitor.cs
示例5: StartAuthentication
///<summary>Starts the authentication process.</summary>
///<param name="Connection">The connection with the SOCKS client.</param>
///<param name="Callback">The method to call when the authentication is complete.</param>
internal override void StartAuthentication(SecureSocket Connection, AuthenticationCompleteDelegate Callback) {
this.Connection = Connection;
this.Callback = Callback;
try {
Bytes = null;
Connection.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(this.OnRecvRequest), Connection);
} catch {
Callback(false);
}
}
开发者ID:QardenEden,项目名称:Suru,代码行数:13,代码来源:AuthUserPass.cs
示例6: HandleAcceptedClient
private void HandleAcceptedClient(SecureSocket incomingClient, ALPNExtensionMonitor monitor)
{
bool backToHttp11 = false;
string selectedProtocol = Protocols.Http1;
if (_useHandshake)
{
try
{
if (_options.Protocol != SecureProtocol.None)
{
incomingClient.MakeSecureHandshake(_options);
selectedProtocol = incomingClient.SelectedProtocol;
}
}
catch (SecureHandshakeException ex)
{
switch (ex.Reason)
{
case SecureHandshakeFailureReason.HandshakeInternalError:
backToHttp11 = true;
break;
case SecureHandshakeFailureReason.HandshakeTimeout:
incomingClient.Close();
Http2Logger.LogError("Handshake timeout. Client was disconnected.");
return;
default:
incomingClient.Close();
Http2Logger.LogError("Unknown error occurred during secure handshake");
return;
}
}
catch (Exception e)
{
Http2Logger.LogError("Exception occurred. Closing client's socket. " + e.Message);
incomingClient.Close();
return;
}
}
var clientStream = new DuplexStream(incomingClient, true);
var transportInfo = GetTransportInfo(incomingClient);
monitor.Dispose();
try
{
HandleRequest(clientStream, selectedProtocol, transportInfo, backToHttp11);
}
catch (Exception e)
{
Http2Logger.LogError("Exception occurred. Closing client's socket. " + e.Message);
incomingClient.Close();
}
}
开发者ID:jamesgodfrey,项目名称:http2-katana,代码行数:55,代码来源:HttpConnectingClient.cs
示例7: MakeHandshakeEnvironment
private IDictionary<string, object> MakeHandshakeEnvironment(SecureSocket incomingClient)
{
var result = new Dictionary<string, object>
{
{"securityOptions", _options},
{"secureSocket", incomingClient},
{"end", ConnectionEnd.Server}
};
return result;
}
开发者ID:Ewert02,项目名称:http2-katana,代码行数:11,代码来源:HttpConnectingClient.cs
示例8: Http2Session
public Http2Session(SecureSocket sessionSocket, ConnectionEnd end,
bool usePriorities, bool useFlowControl,
IDictionary<string, object> handshakeResult = null)
{
_ourEnd = end;
_usePriorities = usePriorities;
_useFlowControl = useFlowControl;
_handshakeHeaders = new Dictionary<string, string>(16);
ApplyHandshakeResults(handshakeResult);
if (_ourEnd == ConnectionEnd.Client)
{
_remoteEnd = ConnectionEnd.Server;
_lastId = -1; // Streams opened by client are odd
}
else
{
_remoteEnd = ConnectionEnd.Client;
_lastId = 0; // Streams opened by server are even
}
_goAwayReceived = false;
_settingsManager = new SettingsManager();
_comprProc = new CompressionProcessor(_ourEnd);
_sessionSocket = sessionSocket;
_frameReader = new FrameReader(_sessionSocket);
ActiveStreams = new ActiveStreams();
_writeQueue = new WriteQueue(_sessionSocket, ActiveStreams, _usePriorities);
if (_sessionSocket != null && sessionSocket.SecureProtocol == SecureProtocol.None)
{
OurMaxConcurrentStreams = int.Parse(_handshakeHeaders[":max_concurrent_streams"]);
RemoteMaxConcurrentStreams = int.Parse(_handshakeHeaders[":max_concurrent_streams"]);
InitialWindowSize = int.Parse(_handshakeHeaders[":initial_window_size"]);
}
else
{
OurMaxConcurrentStreams = 100; //Spec recommends value 100 by default
RemoteMaxConcurrentStreams = 100;
InitialWindowSize = 2000000;
}
_flowControlManager = new FlowControlManager(this);
if (!_useFlowControl)
{
_flowControlManager.Options = (byte) FlowControlOptions.DontUseFlowControl;
}
SessionWindowSize = 0;
_toBeContinuedHeaders = new HeadersList();
}
开发者ID:sgrebnov,项目名称:http2-katana,代码行数:54,代码来源:Http2Session.cs
示例9: Bind
public void Bind( IPEndPoint endPoint )
{
if( fAcceptSocket != null )
{
throw new InvalidOperationException( "Socket is already bound" );
}
fAcceptSocket = new SecureSocket
(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, fOptions );
fAcceptSocket.Bind( endPoint );
fAcceptSocket.Listen( 10 );
}
开发者ID:rafidzal,项目名称:OpenADK-csharp,代码行数:11,代码来源:AdkSSLAcceptSocket.cs
示例10: SecureNetworkStream
/// <summary>
/// Creates a new instance of the SecureNetworkStream class for the specified <see cref="SecureSocket"/>.
/// </summary>
/// <param name="socket">The SecureSocket that provides the network data.</param>
/// <param name="access">One of the FileAccess values that sets the CanRead and CanWrite properties of the SecureNetworkStream.</param>
/// <param name="ownsSocket"><b>true</b> if the socket will be owned by this SecureNetworkStream instance; otherwise, <b>false</b>.</param>
/// <exception cref="ArgumentNullException"><paramref name="socket"/> is a null reference (<b>Nothing</b> in Visual Basic).</exception>
/// <exception cref="ArgumentException"><paramref name="socket"/> is not connected -or- the SocketType property of socket is not SocketType.Stream.</exception>
/// <exception cref="IOException"><paramref name="socket"/> is a nonblocking socket.</exception>
public SecureNetworkStream(SecureSocket socket, FileAccess access, bool ownsSocket) {
if (socket == null)
throw new ArgumentNullException();
if (!socket.Blocking)
throw new IOException();
if (!socket.Connected || socket.SocketType != SocketType.Stream)
throw new ArgumentException();
m_CanRead = (access == FileAccess.Read || access == FileAccess.ReadWrite);
m_CanWrite = (access == FileAccess.Write || access == FileAccess.ReadWrite);
m_OwnsSocket = ownsSocket;
m_Socket = socket;
}
开发者ID:QardenEden,项目名称:Suru,代码行数:21,代码来源:SecureNetworkStream.cs
示例11: SecureHandshaker
public SecureHandshaker(SecureSocket socket, SecurityOptions options)
{
InternalSocket = socket;
InternalSocket.OnHandshakeFinish += HandshakeFinishedHandler;
Options = options;
_handshakeFinishedEventRaised = new ManualResetEvent(false);
if (Options.Protocol == SecureProtocol.None)
{
HandshakeFinishedHandler(this, null);
}
}
开发者ID:jamesgodfrey,项目名称:http2-katana,代码行数:13,代码来源:SecureHandshaker.cs
示例12: ProcessPort
///<summary>Initializes a new instance of the FtpDataConnection class.</summary>
///<param name="RemoteAddress">The address on the local FTP client to connect to.</param>
///<returns>The PORT command string to send to the FTP server.</returns>
public string ProcessPort(IPEndPoint RemoteAddress) {
try {
ListenSocket = new SecureSocket(IPAddress.Any.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
ListenSocket.Bind(new IPEndPoint(IPAddress.Any, 0));
ListenSocket.Listen(1);
ListenSocket.BeginAccept(new AsyncCallback(this.OnPortAccept), ListenSocket);
ClientSocket = new SecureSocket(RemoteAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
ClientSocket.BeginConnect(RemoteAddress, new AsyncCallback(this.OnPortConnected), ClientSocket);
return "PORT " + Listener.GetLocalExternalIP().ToString().Replace('.', ',') + "," + Math.Floor(((IPEndPoint)ListenSocket.LocalEndPoint).Port / 256).ToString() + "," + (((IPEndPoint)ListenSocket.LocalEndPoint).Port % 256).ToString() + "\r\n";
} catch {
Dispose();
return "PORT 0,0,0,0,0,0\r\n";
}
}
开发者ID:QardenEden,项目名称:Suru,代码行数:17,代码来源:FtpDataConnection.cs
示例13: WriteQueue
public WriteQueue(SecureSocket socket, ActiveStreams streams, bool isPriorityTurnedOn)
{
IsPriorityTurnedOn = isPriorityTurnedOn;
_streams = streams;
if (isPriorityTurnedOn)
{
_messageQueue = new PriorityQueue();
}
else
{
_messageQueue = new QueueWrapper();
}
_socket = socket;
_disposed = false;
}
开发者ID:sgrebnov,项目名称:http2-katana,代码行数:15,代码来源:WriteQueue.cs
示例14: GetHttp11Headers
public static string[] GetHttp11Headers(SecureSocket socket)
{
var headers = new List<string>(5);
var lineBuffer = new byte[1024];
string header = String.Empty;
int totalBytesCame = 0;
int bytesOfLastHeader = 0;
while (true)
{
bool gotException = false;
var bf = new byte[1];
int bytesCame = socket.Receive(bf);
if (bytesCame == 0)
break;
Buffer.BlockCopy(bf, 0, lineBuffer, totalBytesCame, bytesCame);
totalBytesCame += bytesCame;
try
{
header = Encoding.UTF8.GetString(lineBuffer, bytesOfLastHeader, totalBytesCame - bytesOfLastHeader);
}
catch
{
gotException = true;
}
if (totalBytesCame != 0 && !gotException && header[header.Length - 1] == '\n')
{
headers.Add(header.TrimEnd('\n', '\r'));
bytesOfLastHeader = totalBytesCame;
}
// empty header means we got \r\n\r\n which was trimmed. This means end of headers block.
if (headers.Count >= 2 && String.IsNullOrEmpty(headers.LastOrDefault()))
{
break;
}
}
headers.RemoveAll(String.IsNullOrEmpty);
return headers.ToArray();
}
开发者ID:nunnun,项目名称:http2-katana,代码行数:44,代码来源:Http11Manager.cs
示例15: ProcessRequest
///<summary>Processes a SOCKS request from a client.</summary>
///<param name="Request">The request to process.</param>
protected override void ProcessRequest(byte [] Request) {
int Ret;
try {
if (Request[0] == 1) { // CONNECT
IPAddress RemoteIP;
int RemotePort = Request[1] * 256 + Request[2];
Ret = Array.IndexOf(Request, (byte)0, 7);
Username = Encoding.ASCII.GetString(Request, 7, Ret - 7);
if (Request[3] == 0 && Request[4] == 0 && Request[5] == 0 && Request[6] != 0) {// Use remote DNS
Ret = Array.IndexOf(Request, (byte)0, Ret + 1);
RemoteIP = Dns.Resolve(Encoding.ASCII.GetString(Request, Username.Length + 8, Ret - Username.Length - 8)).AddressList[0];
} else { //Do not use remote DNS
RemoteIP = IPAddress.Parse(Request[3].ToString() + "." + Request[4].ToString() + "." + Request[5].ToString() + "." + Request[6].ToString());
}
RemoteConnection = new SecureSocket(RemoteIP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
RemoteConnection.BeginConnect(new IPEndPoint(RemoteIP, RemotePort), new AsyncCallback(this.OnConnected), RemoteConnection);
} else if (Request[0] == 2) { // BIND
byte [] Reply = new byte[8];
long LocalIP = Listener.GetLocalExternalIP().Address;
AcceptSocket = new SecureSocket(IPAddress.Any.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
AcceptSocket.Bind(new IPEndPoint(IPAddress.Any, 0));
AcceptSocket.Listen(50);
RemoteBindIP = IPAddress.Parse(Request[3].ToString() + "." + Request[4].ToString() + "." + Request[5].ToString() + "." + Request[6].ToString());
Reply[0] = 0; //Reply version 0
Reply[1] = 90; //Everything is ok :)
Reply[2] = (byte)(Math.Floor(((IPEndPoint)AcceptSocket.LocalEndPoint).Port / 256)); //Port/1
Reply[3] = (byte)(((IPEndPoint)AcceptSocket.LocalEndPoint).Port % 256); //Port/2
Reply[4] = (byte)(Math.Floor((LocalIP % 256))); //IP Address/1
Reply[5] = (byte)(Math.Floor((LocalIP % 65536) / 256)); //IP Address/2
Reply[6] = (byte)(Math.Floor((LocalIP % 16777216) / 65536)); //IP Address/3
Reply[7] = (byte)(Math.Floor(LocalIP / 16777216)); //IP Address/4
Connection.BeginSend(Reply, 0, Reply.Length, SocketFlags.None, new AsyncCallback(this.OnStartAccept), Connection);
}
} catch {
Dispose(91);
}
}
开发者ID:QardenEden,项目名称:Suru,代码行数:39,代码来源:Socks4Handler.cs
示例16: DuplexStream
public DuplexStream(SecureSocket socket, bool ownsSocket = false)
{
if (socket == null)
throw new ArgumentNullException("socket is null");
_writeBuffer = new StreamBuffer(1024);
_readBuffer = new StreamBuffer(1024);
_ownsSocket = ownsSocket;
_socket = socket;
_isClosed = false;
_waitLock = new object();
_closeLock = new object();
_streamStateChangeRaised = new ManualResetEvent(false);
OnDataAvailable += (sender, args) => _streamStateChangeRaised.Set();
OnClose += (sender, args) => _streamStateChangeRaised.Set();
Task.Run(async () =>
{
Thread.CurrentThread.Name = "Duplex listening thread";
await PumpIncomingData();
});
}
开发者ID:jamesgodfrey,项目名称:http2-katana,代码行数:24,代码来源:DuplexStream.cs
示例17: AdkSSLConnectedSocket
public AdkSSLConnectedSocket( SecureSocket wrappedSocket )
{
fSocket = wrappedSocket;
}
开发者ID:rafidzal,项目名称:OpenADK-csharp,代码行数:4,代码来源:AdkSSLConnectedSocket.cs
示例18: OnVerify
public void OnVerify(SecureSocket socket, Certificate remote, CertificateChain chain, VerifyEventArgs e)
{
Console.WriteLine("\r\nThe certificate of the FTP server:");
Console.WriteLine(remote.ToString(true) + "\r\n");
// certificate chain verification can be placed here
}
开发者ID:maikgreubel,项目名称:securitylibrary,代码行数:6,代码来源:FtpClient.cs
示例19: Connect
public bool Connect(Uri connectUri)
{
_path = connectUri.PathAndQuery;
_version = Protocols.Http2;
_scheme = connectUri.Scheme;
_host = connectUri.Host;
_port = connectUri.Port;
ServerUri = connectUri.Authority;
if (_sessionAdapter != null)
{
return false;
}
try
{
int port = connectUri.Port;
int securePort;
if (!int.TryParse(ConfigurationManager.AppSettings["securePort"], out securePort))
{
Http2Logger.LogError("Incorrect port in the config file!");
return false;
}
//Connect alpn extension, set known protocols
var extensions = new[] {ExtensionType.Renegotiation, ExtensionType.ALPN};
Options = port == securePort
? new SecurityOptions(SecureProtocol.Tls1, extensions, new[] { Protocols.Http1, Protocols.Http2 },
ConnectionEnd.Client)
: new SecurityOptions(SecureProtocol.None, extensions, new[] { Protocols.Http1, Protocols.Http2 },
ConnectionEnd.Client);
Options.VerificationType = CredentialVerification.None;
Options.Certificate = Org.Mentalis.Security.Certificates.Certificate.CreateFromCerFile(CertificatePath);
Options.Flags = SecurityFlags.Default;
Options.AllowedAlgorithms = SslAlgorithms.RSA_AES_256_SHA | SslAlgorithms.NULL_COMPRESSION;
var socket = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, Options);
using (var monitor = new ALPNExtensionMonitor())
{
monitor.OnProtocolSelected += (o, args) => { _selectedProtocol = args.SelectedProtocol; };
socket.Connect(new DnsEndPoint(connectUri.Host, connectUri.Port), monitor);
_clientStream = new DuplexStream(socket, true);
if (_useHandshake)
{
MakeHandshakeEnvironment();
//Handshake manager determines what handshake must be used: upgrade or secure
if (socket.SecureProtocol != SecureProtocol.None)
{
socket.MakeSecureHandshake(Options);
_selectedProtocol = socket.SelectedProtocol;
}
if (socket.SecureProtocol == SecureProtocol.None || _selectedProtocol == Protocols.Http1)
{
try
{
var handshakeResult = new UpgradeHandshaker(_environment).Handshake();
_environment.Add(HandshakeKeys.Result, handshakeResult);
_useHttp20 = handshakeResult[HandshakeKeys.Successful] as string == HandshakeKeys.True;
if (!_useHttp20)
{
Dispose(false);
return true;
}
}
catch (Http2HandshakeFailed ex)
{
if (ex.Reason == HandshakeFailureReason.InternalError)
{
_useHttp20 = false;
}
else
{
Http2Logger.LogError("Specified server did not respond");
Dispose(true);
return false;
}
}
}
}
}
Http2Logger.LogDebug("Handshake finished");
if (_useHttp20)
{
//TODO provide transport info
_sessionAdapter = new Http2ClientMessageHandler(_clientStream, ConnectionEnd.Client, default(TransportInformation),
CancellationToken.None);
}
}
//.........这里部分代码省略.........
开发者ID:jamesgodfrey,项目名称:http2-katana,代码行数:101,代码来源:Http2SessionHandler.cs
示例20: DownloadFile
private void DownloadFile(Url url, int choice)
{
SecurityOptions options = new SecurityOptions(SecureProtocol.None);;
m_Socket = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, options);
// connect to the FTP server using a normal TCP connection
m_Socket.Connect(new IPEndPoint(Dns.GetHostEntry(url.Host).AddressList[0], url.Port));
// wait for the server hello
ReceiveReply();
// if the user selected to use the AUTH command..
if (choice == 2) {
// ..send the command to the server and start the SSL handshake
DoAuthCommand(url.Host);
}
// log on and quit
if (!SendCommand("USER " + url.Username))
return;
if (!SendCommand("PASS " + url.Password))
return;
if (!SendCommand("QUIT"))
return;
// clean up
m_Socket.Shutdown(SocketShutdown.Both);
m_Socket.Close();
}
开发者ID:maikgreubel,项目名称:securitylibrary,代码行数:24,代码来源:FtpClient.cs
注:本文中的Org.Mentalis.Security.Ssl.SecureSocket类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论