private async Task ProcessSend(byte[] buffer, int offset, int size, int alignmentSize) { await _processSend.WaitAsync(); try { _sendStopwatch.Restart(); unsafe { fixed(byte *ptr = buffer) { var header = (NetworkMessageHeader *)ptr; header->Serial = MessageSerialService.ComputeSend(buffer, offset); header->Checksum = _messageChecksumService.Compute(buffer, offset); header->BodyLength += (ushort)alignmentSize; } } #if DEBUG LogPacket(buffer, offset, size, "Send"); #endif CryptographyService.Encrypt(buffer, offset, size + alignmentSize); if (_alignBuffer) { buffer[offset + alignmentSize + size] = (byte)(alignmentSize ^ buffer[3]); } await _connection.WriteAsync(buffer, offset, size + alignmentSize + (_alignBuffer ? 1 : 0)); } catch (SocketException ex) { await DisconnectAsync(); Logger.LogTrace(ex.Message, "ProcessSend"); } catch (IOException ex) { await DisconnectAsync(); Logger.LogTrace(ex.Message, "ProcessSend"); } finally { ArrayPool <byte> .Shared.Return(buffer); _sendStopwatch.Stop(); _processSend.Release(); } }
protected async Task UseXorCryptography() { if (_saidHello) { throw new Exception("Already said hello."); } _saidHello = true; var rnd = new Random(); var bfEncKey = rnd.Next(); var bfDecKey = rnd.Next(); var sendSerialKey = rnd.Next(0, 5); var receiveSerialKey = rnd.Next(0, 5); await SendAsync(new XorSessionHello(bfDecKey, bfEncKey, sendSerialKey, receiveSerialKey)); MessageSerialService.UpdateKeys(receiveSerialKey, sendSerialKey); CryptographyService = _cryptographyServiceFactory.CreateXor(new CryptographicOption(BitConverter.GetBytes(bfDecKey)), new CryptographicOption(BitConverter.GetBytes(bfEncKey))); }
protected virtual async Task ProcessReceive(INetworkMessage message) { await _processRead.WaitAsync(); try { if (MessageSerialService.ValidateReceive(message.Header.Serial)) { await _networkMessageHandlerService.Process(message, _self); } } catch (Exception ex) { Logger.LogError(ex, "ProcessMessage"); } finally { _processRead.Release(); } }