/// <summary> /// Connect to a group to start streaming /// </summary> /// <param name="groupId"></param> /// <param name="simulator"></param> /// <returns></returns> public async Task Connect(Guid entertainmentAreaId, bool simulator = false) { _simulator = simulator; var enableResult = await _localHueClient.SetStreamingAsync(entertainmentAreaId).ConfigureAwait(false); entConfigIdBytes = Encoding.ASCII.GetBytes(entertainmentAreaId.ToString().ToLowerInvariant()); byte[] psk = FromHex(_clientKey); BasicTlsPskIdentity pskIdentity = new BasicTlsPskIdentity(_appKey, psk); var dtlsClient = new DtlsClient(null !, pskIdentity); DtlsClientProtocol clientProtocol = new DtlsClientProtocol(new SecureRandom()); #if NET461 _socket.Connect(IPAddress.Parse(_ip), 2100); #else await _socket.ConnectAsync(IPAddress.Parse(_ip), 2100).ConfigureAwait(false); #endif _udp = new UdpTransport(_socket); if (!simulator) { _dtlsTransport = clientProtocol.Connect(dtlsClient, _udp); } }
public static void Main(string[] args) { string hostname = "localhost"; int port = 5556; long time1 = DateTime.UtcNow.Ticks; /* * Note: This is the default PSK identity for 'openssl s_server' testing, the server must be * started with "-psk 6161616161" to make the keys match, and possibly the "-psk_hint" * option should be present. */ //string psk_identity = "Client_identity"; //byte[] psk = new byte[]{ 0x61, 0x61, 0x61, 0x61, 0x61 }; // These correspond to the configuration of MockPskTlsServer string psk_identity = "client"; byte[] psk = Strings.ToUtf8ByteArray("TLS_TEST_PSK"); BasicTlsPskIdentity pskIdentity = new BasicTlsPskIdentity(psk_identity, psk); MockPskTlsClient client = new MockPskTlsClient(null, pskIdentity); TlsClientProtocol protocol = OpenTlsConnection(hostname, port, client); protocol.Close(); long time2 = DateTime.UtcNow.Ticks; Console.WriteLine("Elapsed 1: " + (time2 - time1) / TimeSpan.TicksPerMillisecond + "ms"); client = new MockPskTlsClient(client.GetSessionToResume(), pskIdentity); protocol = OpenTlsConnection(hostname, port, client); long time3 = DateTime.UtcNow.Ticks; Console.WriteLine("Elapsed 2: " + (time3 - time2) / TimeSpan.TicksPerMillisecond + "ms"); byte[] req = Encoding.UTF8.GetBytes("GET / HTTP/1.1\r\n\r\n"); Stream tlsStream = protocol.Stream; tlsStream.Write(req, 0, req.Length); tlsStream.Flush(); StreamReader reader = new StreamReader(tlsStream); String line; while ((line = reader.ReadLine()) != null) { Console.WriteLine(">>> " + line); } protocol.Close(); }
static async Task Main(string[] args) { var host = "localhost"; var port = Coap.PortDTLS; var identity = new BasicTlsPskIdentity("user", Encoding.UTF8.GetBytes("password")); // Create a new client using a DTLS endpoint with the remote host and Identity var client = new CoapClient(new CoapDtlsClientEndPoint(host, port, new ExamplePskDtlsClient(identity))); // Create a cancelation token that cancels after 1 minute var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMinutes(1)); // Capture the Control + C event Console.CancelKeyPress += (s, e) => { Console.WriteLine("Exiting"); cancellationTokenSource.Cancel(); // Prevent the Main task from being destroyed prematurely. e.Cancel = true; }; Console.WriteLine("Press <Ctrl>+C to exit"); try { // Create a simple GET request var message = new CoapMessage { Code = CoapMessageCode.Get, Type = CoapMessageType.Confirmable, }; // Get the /hello resource from localhost. message.SetUri($"coaps://{host}:{port}/hello"); Console.WriteLine($"Sending a {message.Code} {message.GetUri().GetComponents(UriComponents.PathAndQuery, UriFormat.Unescaped)} request"); await client.SendAsync(message, cancellationTokenSource.Token); // Wait for the server to respond. var response = await client.ReceiveAsync(cancellationTokenSource.Token); // Output our response Console.WriteLine($"Received a response from {response.Endpoint}\n{Encoding.UTF8.GetString(response.Message.Payload)}"); } catch (Exception ex) { Console.WriteLine($"Exception caught: {ex}"); } finally { Console.WriteLine($"Press <Enter> to exit"); Console.Read(); } }
public static void Main(string[] args) { string hostname = "localhost"; int port = 5556; long time1 = DateTime.UtcNow.Ticks; /* * Note: This is the default PSK identity for 'openssl s_server' testing, the server must be * started with "-psk 6161616161" to make the keys match, and possibly the "-psk_hint" * option should be present. */ string psk_identity = "Client_identity"; byte[] psk = new byte[]{ 0x61, 0x61, 0x61, 0x61, 0x61 }; BasicTlsPskIdentity pskIdentity = new BasicTlsPskIdentity(psk_identity, psk); MockPskTlsClient client = new MockPskTlsClient(null, pskIdentity); TlsClientProtocol protocol = OpenTlsConnection(hostname, port, client); protocol.Close(); long time2 = DateTime.UtcNow.Ticks; Console.WriteLine("Elapsed 1: " + (time2 - time1)/TimeSpan.TicksPerMillisecond + "ms"); client = new MockPskTlsClient(client.GetSessionToResume(), pskIdentity); protocol = OpenTlsConnection(hostname, port, client); long time3 = DateTime.UtcNow.Ticks; Console.WriteLine("Elapsed 2: " + (time3 - time2)/TimeSpan.TicksPerMillisecond + "ms"); byte[] req = Encoding.UTF8.GetBytes("GET / HTTP/1.1\r\n\r\n"); Stream tlsStream = protocol.Stream; tlsStream.Write(req, 0, req.Length); tlsStream.Flush(); StreamReader reader = new StreamReader(tlsStream); String line; while ((line = reader.ReadLine()) != null) { Console.WriteLine(">>> " + line); } protocol.Close(); }
/// <summary> /// Create the DTLS connection over a specific UDP channel. /// We already know what address we are going to use /// </summary> /// <param name="udpChannel">UDP channel to use</param> public void Connect(UDPChannel udpChannel) { #if SUPPORT_TLS_CWT if (CwtTrustKeySet != null) { _client = new DtlsClient(null, _userKey, CwtTrustKeySet); } else { #endif if (_userKey.PrivateKey.HasKeyType((int)GeneralValuesInt.KeyType_Octet)) { CBORObject kid = _userKey.PrivateKey[CoseKeyKeys.KeyIdentifier]; BasicTlsPskIdentity pskIdentity; pskIdentity = new BasicTlsPskIdentity(kid != null ? kid.GetByteString() : new byte[0], _userKey.PrivateKey[CoseKeyParameterKeys.Octet_k].GetByteString()); _client = new DtlsClient(null, pskIdentity); } else if (_userKey.PrivateKey.HasKeyType((int)GeneralValuesInt.KeyType_EC2)) { _client = new DtlsClient(null, _userKey); } #if SUPPORT_TLS_CWT } #endif _client.TlsEventHandler += OnTlsEvent; DtlsClientProtocol clientProtocol = new DtlsClientProtocol(new SecureRandom()); _transport.UDPChannel = udpChannel; AuthenticationKey = _userKey.PrivateKey; _listening = 1; DtlsTransport dtlsClient = clientProtocol.Connect(_client, _transport); _listening = 0; _dtlsSession = dtlsClient; // We are now in the world of a connected system - // We need to do the receive calls new Thread(StartListen).Start(); }
/// <summary> /// Connect to a group to start streaming /// </summary> /// <param name="groupId"></param> /// <param name="simulator"></param> /// <returns></returns> public async Task Connect(string groupId, bool simulator = false) { _simulator = simulator; var enableResult = await _localHueClient.SetStreamingAsync(groupId).ConfigureAwait(false); byte[] psk = FromHex(_clientKey); BasicTlsPskIdentity pskIdentity = new BasicTlsPskIdentity(_appKey, psk); var dtlsClient = new DtlsClient(null !, pskIdentity); DtlsClientProtocol clientProtocol = new DtlsClientProtocol(new SecureRandom()); await _socket.ConnectAsync(IPAddress.Parse(_ip), 2100).ConfigureAwait(false); _udp = new UdpTransport(_socket); if (!simulator) { _dtlsTransport = clientProtocol.Connect(dtlsClient, _udp); } }
private void but_Click(object sender2, EventArgs e) { if (InputBox.Show("Server", "Server", ref address) != DialogResult.OK) { return; } if (InputBox.Show("Server port", "Server port", ref port) != DialogResult.OK) { return; } string username = Settings.Instance.GetString("ex_api_username"); string token = Settings.Instance.GetString("ex_api_psk"); if (InputBox.Show("Username", "Username", ref username) != DialogResult.OK) { return; } if (InputBox.Show("Token", "Token", ref token) != DialogResult.OK) { return; } Settings.Instance["ex_api_address"] = address; Settings.Instance["ex_api_port"] = port.ToString(); Settings.Instance["ex_api_username"] = username; Settings.Instance["ex_api_psk"] = token; Task.Run(() => { try { var psk = new BasicTlsPskIdentity(username, token.MakeBytes()); var pskclient = new DTLSPsk(psk); DtlsClientProtocol client = new DtlsClientProtocol(new Org.BouncyCastle.Security.SecureRandom()); DatagramTransport transport = new UDPTransport(address, port); var dtlstx = client.Connect(pskclient, transport); MainV2.comPort.OnPacketReceived += (sender, message) => { dtlstx.Send(message.buffer, 0, message.buffer.Length); }; var buf = new byte[dtlstx.GetReceiveLimit()]; while (MainV2.comPort.BaseStream.IsOpen) { try { var read = dtlstx.Receive(buf, 0, buf.Length, 1000); lock (MainV2.comPort.objlock) { if (MainV2.comPort.BaseStream.IsOpen) { MainV2.comPort.BaseStream.Write(buf, 0, read); } } } catch (Exception ex) { } } } catch (Exception ex) { CustomMessageBox.Show(Strings.ERROR, ex.ToString()); } }); }
public void Connect() { BasicTlsPskIdentity pskIdentity = null; if (_userKey != null) { if (_userKey.HasKeyType((int)COSE.GeneralValuesInt.KeyType_Octet)) { CBORObject kid = _userKey[COSE.CoseKeyKeys.KeyIdentifier]; if (kid != null) { pskIdentity = new BasicTlsPskIdentity(kid.GetByteString(), _userKey[CoseKeyParameterKeys.Octet_k].GetByteString()); } else { pskIdentity = new BasicTlsPskIdentity(new byte[0], _userKey[CoseKeyParameterKeys.Octet_k].GetByteString()); } } } _tlsSession = new TLSClient(null, pskIdentity); _authKey = _userKey; TlsClientProtocol clientProtocol = new TlsClientProtocol(new SecureRandom()); _client = new TcpClient(_ipEndPoint.AddressFamily); _client.Connect(_ipEndPoint); _stm = _client.GetStream(); clientProtocol.Connect(_tlsSession); while (_tlsSession.InHandshake) { bool sleep = true; int cbToRead = clientProtocol.GetAvailableOutputBytes(); if (cbToRead != 0) { byte[] data = new byte[cbToRead]; int cbRead = clientProtocol.ReadOutput(data, 0, cbToRead); _stm.Write(data, 0, cbRead); sleep = false; } if (_stm.DataAvailable) { byte[] data = new byte[1024]; int cbRead = _stm.Read(data, 0, data.Length); Array.Resize(ref data, cbRead); clientProtocol.OfferInput(data); sleep = false; } if (sleep) { Thread.Sleep(100); } } _tlsClient = clientProtocol; // Send over the capability block SendCSMSignal(); // if (_toSend != null) { _queue.Enqueue(_toSend); _toSend = null; } _stm.BeginRead(_buffer, 0, _buffer.Length, ReadCallback, this); WriteData(); }