Exemplo n.º 1
0
        private async Task ProcessDeliveriesAsync(ChannelReader <Letter> channelReader)
        {
            while (await channelReader.WaitToReadAsync().ConfigureAwait(false))
            {
                while (channelReader.TryRead(out var letter))
                {
                    if (letter == null)
                    {
                        continue;
                    }

                    if (_compress)
                    {
                        letter.Body = await Gzip.CompressAsync(letter.Body).ConfigureAwait(false);

                        letter.LetterMetadata.Compressed = _compress;
                        letter.LetterMetadata.CustomFields[Utils.Constants.HeaderForEncrypt] = Utils.Constants.HeaderValueForGzipCompress;
                    }

                    if (_encrypt)
                    {
                        letter.Body = AesEncrypt.Encrypt(letter.Body, _hashKey);
                        letter.LetterMetadata.Encrypted = _encrypt;
                        letter.LetterMetadata.CustomFields[Utils.Constants.HeaderForEncrypt] = Utils.Constants.HeaderValueForArgonAesEncrypt;
                    }

                    _logger.LogDebug(LogMessages.AutoPublisher.LetterPublished, letter.LetterId, letter.LetterMetadata?.Id);

                    await PublishAsync(letter, _createPublishReceipts, _withHeaders)
                    .ConfigureAwait(false);
                }
            }
        }
Exemplo n.º 2
0
        private async Task ProcessDeliveriesAsync(ChannelReader <Letter> channelReader)
        {
            while (await channelReader.WaitToReadAsync().ConfigureAwait(false))
            {
                while (channelReader.TryRead(out var letter))
                {
                    if (letter == null)
                    {
                        continue;
                    }

                    if (Compress)
                    {
                        letter.Body = await Gzip.CompressAsync(letter.Body).ConfigureAwait(false);

                        letter.LetterMetadata.Compressed = Compress;
                    }

                    if (Encrypt && (_hashKey != null || _hashKey.Length == 0))
                    {
                        letter.Body = AesEncrypt.Encrypt(letter.Body, _hashKey);
                        letter.LetterMetadata.Encrypted = Encrypt;
                    }

                    _logger.LogDebug(LogMessages.AutoPublisher.LetterPublished, letter.LetterId, letter.LetterMetadata?.Id);

                    await Publisher
                    .PublishAsync(letter, CreatePublishReceipts, _withHeaders)
                    .ConfigureAwait(false);
                }
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// 数据处理 GetHostVersion
        /// </summary>
        /// <param name="_IPEndPoint"></param>
        private void PacketAction2(IPEndPoint _IPEndPoint)
        {
            if (!this.IncludeRemote(_IPEndPoint))
            {
                return;
            }
            else
            {
                this.UpdateRemote(_IPEndPoint);
            }
            Process p1     = Process.GetCurrentProcess();
            Object  packet = new{
                ActionId                    = 2, ActionName = "GetHostVersion", ErrorCode = 0, ErrorMessage = String.Empty,
                HostServiceVersion          = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(),
                HostServicePid              = p1.Id,
                HostServiceMemoryUsageBytes = p1.PrivateMemorySize64,
                HostServiceThreadsCount     = p1.Threads.Count,
#pragma warning disable IDE0037 // 使用推断的成员名称
                MachineName = p1.MachineName,
#pragma warning restore IDE0037 // 使用推断的成员名称
                MachineProcessorCount = Environment.ProcessorCount,
                //MachineMemoryTotalBytes=WMI.GetPhysicalMemorySize()
                //MachineMemoryAvailableBytes=PerformanceCounters.GetMachineMemoryAvailableBytes(),
            };

            p1.Dispose();
            String json = JsonConvert.SerializeObject(packet);

            Program.Logger.Log("UdpSocketServer", $"UdpPacketSent=>{_IPEndPoint.Address}:{_IPEndPoint.Port}=>{json}");
            this.AsyncNetUdpServer.SendAsync(AesEncrypt.Encrypt(Program.AppSettings.ControlKey, json), _IPEndPoint);
        }
Exemplo n.º 4
0
        public async Task ComcryptDecomcryptTest()
        {
            var message = new Message {
                StringMessage = $"Sensitive ReceivedLetter 0", MessageId = 0
            };
            var data = JsonSerializer.SerializeToUtf8Bytes(message);

            var hashKey = await ArgonHash
                          .GetHashKeyAsync(Passphrase, Salt, Constants.EncryptionKeySize)
                          .ConfigureAwait(false);

            _output.WriteLine(Encoding.UTF8.GetString(hashKey));
            _output.WriteLine($"HashKey: {Encoding.UTF8.GetString(hashKey)}");

            // Comcrypt
            var payload = await Gzip.CompressAsync(data);

            var encryptedPayload = AesEncrypt.Encrypt(payload, hashKey);

            // Decomcrypt
            var decryptedData = AesEncrypt.Decrypt(encryptedPayload, hashKey);

            Assert.NotNull(decryptedData);

            var decompressed = await Gzip.DecompressAsync(decryptedData);

            JsonSerializer.SerializeToUtf8Bytes(decompressed);
            _output.WriteLine($"Data: {Encoding.UTF8.GetString(data)}");
            _output.WriteLine($"Decrypted: {Encoding.UTF8.GetString(decryptedData)}");

            Assert.Equal(data, decompressed);
        }
Exemplo n.º 5
0
    /// <summary>
    /// aes加混淆加密接口
    /// </summary>
    static public byte[] ExecuteEncrypt(byte[] buffer, string key)
    {
        //这里后续附加混淆规则
        int bufferLen = buffer.Length;

        if (bufferLen > MAX_ENCRYPT_LEN)
        {
            //规定 ECBMode:(明文长度/16 + 1) * 16 = 密文长度
            int    retLen      = bufferLen - MAX_ENCRYPT_LEN + (MAX_ENCRYPT_LEN / BLOCK_SIZE + 1) * BLOCK_SIZE;
            byte[] encryBuffer = new byte[MAX_ENCRYPT_LEN];
            byte[] retBuffer   = new byte[retLen];
            Array.Copy(buffer, encryBuffer, MAX_ENCRYPT_LEN);
            byte[] beEncryBuffer = AesEncrypt.Encrypt(encryBuffer, key);
            beEncryBuffer.CopyTo(retBuffer, 0);
            Array.Copy(buffer, MAX_ENCRYPT_LEN, retBuffer, beEncryBuffer.Length, bufferLen - MAX_ENCRYPT_LEN);

            for (int i = beEncryBuffer.Length, j = 0; i < retBuffer.Length; i += CONFUSE_OFFSET)
            {
                retBuffer[i] += buffer[j];
                j            += 2;
                if (j >= MAX_ENCRYPT_LEN)
                {
                    j = 0;
                }
            }

            return(retBuffer);
        }
        else
        {
            return(AesEncrypt.Encrypt(buffer, key));
        }
    }
Exemplo n.º 6
0
        public bool Encrypt(Letter letter)
        {
            if (!letter.LetterMetadata.Encrypted && (_hashKey?.Length > 0))
            {
                try
                {
                    letter.Body = AesEncrypt.Encrypt(letter.Body, _hashKey);
                    letter.LetterMetadata.Encrypted = true;
                }
                catch { }
            }

            return(letter.LetterMetadata.Encrypted);
        }
Exemplo n.º 7
0
        /// <summary>
        /// 数据处理 StopAllUnits
        /// </summary>
        /// <param name="_IPEndPoint"></param>
        private void PacketAction1004(IPEndPoint _IPEndPoint)
        {
            if (!this.IncludeRemote(_IPEndPoint))
            {
                return;
            }
            else
            {
                this.UpdateRemote(_IPEndPoint);
            }
            UnitControl.StopAllUnits();
            Object packet = new{ ActionId = 1004, ActionName = "StopAllUnits", ErrorCode = 0, ErrorMessage = String.Empty };
            String json   = JsonConvert.SerializeObject(packet);

            Program.Logger.Log("UdpSocketServer", $"UdpPacketSent=>{_IPEndPoint.Address}:{_IPEndPoint.Port}=>{json}");
            this.AsyncNetUdpServer.SendAsync(AesEncrypt.Encrypt(Program.AppSettings.ControlKey, json), _IPEndPoint);
        }
Exemplo n.º 8
0
        /// <summary>
        /// 数据处理 Hello
        /// </summary>
        /// <param name="_IPEndPoint"></param>
        private void PacketAction1(IPEndPoint _IPEndPoint)
        {
            if (!this.IncludeRemote(_IPEndPoint))
            {
                this.Remotes.Add(new Entity.UdpSocketRemote {
                    IPEndPoint = _IPEndPoint, LastUpdateTime = DateTimeOffset.Now.ToUnixTimeSeconds()
                });
            }
            else
            {
                this.UpdateRemote(_IPEndPoint);
            }
            Object packet = new{ ActionId = 1, ActionName = "Hello", ErrorCode = 0, ErrorMessage = String.Empty, Message = $"Hello,{_IPEndPoint.Address}:{_IPEndPoint.Port}" };
            String json   = JsonConvert.SerializeObject(packet);

            Program.Logger.Log("UdpSocketServer", $"UdpPacketSent=>{_IPEndPoint.Address}:{_IPEndPoint.Port}=>{json}");
            this.AsyncNetUdpServer.SendAsync(AesEncrypt.Encrypt(Program.AppSettings.ControlKey, json), _IPEndPoint);
        }
Exemplo n.º 9
0
        public bool Encrypt(Letter letter)
        {
            if (letter.LetterMetadata.Encrypted || (_hashKey == null && _hashKey.Length == 0))
            {
                return(false);
            }                 // Don't double encrypt.

            try
            {
                letter.Body = AesEncrypt.Encrypt(letter.Body, _hashKey);
                letter.LetterMetadata.Encrypted = true;
                letter.LetterMetadata.CustomFields[Utils.Constants.HeaderForEncrypt]     = Utils.Constants.HeaderValueForArgonAesEncrypt;
                letter.LetterMetadata.CustomFields[Utils.Constants.HeaderForEncryptDate] = Time.GetDateTimeUtcNow();
            }
            catch { return(false); }

            return(true);
        }
Exemplo n.º 10
0
        /// <summary>
        /// 数据处理 StopUnit
        /// </summary>
        /// <param name="_IPEndPoint"></param>
        /// <param name="_UdpSocketPacketRecive"></param>
        private void PacketAction1005(IPEndPoint _IPEndPoint, Entity.UdpSocketPacketRecive _UdpSocketPacketRecive)
        {
            if (!this.IncludeRemote(_IPEndPoint))
            {
                return;
            }
            else
            {
                this.UpdateRemote(_IPEndPoint);
            }
            Object packet = new{ ActionId = 1005, ActionName = "StopUnit", ErrorCode = 0, ErrorMessage = String.Empty };

            if (String.IsNullOrWhiteSpace(_UdpSocketPacketRecive.UnitName))
            {
                packet = new{ ActionId = 1005, ActionName = "StopUnit", ErrorCode = 101, ErrorMessage = "单元名称无效" };
            }                                                                                                                                                   //TODO 优化
            UnitControl.StopUnit(_UdpSocketPacketRecive.UnitName);
            String json = JsonConvert.SerializeObject(packet);

            Program.Logger.Log("UdpSocketServer", $"UdpPacketSent=>{_IPEndPoint.Address}:{_IPEndPoint.Port}=>{json}");
            this.AsyncNetUdpServer.SendAsync(AesEncrypt.Encrypt(Program.AppSettings.ControlKey, json), _IPEndPoint);
        }
Exemplo n.º 11
0
        public async Task EncryptDecryptTest()
        {
            var data = new byte[] { 0xFF, 0x00, 0xAA, 0xFF, 0x00, 0x00, 0xFF, 0xAA, 0x00, 0xFF, 0x00, 0xFF };

            var hashKey = await ArgonHash
                          .GetHashKeyAsync(Passphrase, Salt, 32)
                          .ConfigureAwait(false);

            _output.WriteLine(Encoding.UTF8.GetString(hashKey));
            _output.WriteLine($"HashKey: {Encoding.UTF8.GetString(hashKey)}");

            var encryptedData = AesEncrypt.Encrypt(data, hashKey);

            _output.WriteLine($"Encrypted: {Encoding.UTF8.GetString(encryptedData)}");

            var decryptedData = AesEncrypt.Decrypt(encryptedData, hashKey);

            _output.WriteLine($"Data: {Encoding.UTF8.GetString(data)}");
            _output.WriteLine($"Decrypted: {Encoding.UTF8.GetString(decryptedData)}");

            Assert.Equal(data, decryptedData);
        }
Exemplo n.º 12
0
        /// <summary>
        /// 数据处理 FetchUnits
        /// </summary>
        /// <param name="_IPEndPoint"></param>
        private void PacketAction1001(IPEndPoint _IPEndPoint)
        {
            if (!this.IncludeRemote(_IPEndPoint))
            {
                return;
            }
            else
            {
                this.UpdateRemote(_IPEndPoint);
            }
            Dictionary <String, Object> d1 = new Dictionary <String, Object>();

#pragma warning disable IDE0037 // 使用推断的成员名称
            foreach (KeyValuePair <String, Entity.Unit> kvp in Program.Units)
            {
                d1[kvp.Key] = new { State = kvp.Value.State, UnitSettings = kvp.Value.UnitSettings };
            }
#pragma warning restore IDE0037 // 使用推断的成员名称
            Object packet = new{ ActionId = 1001, ActionName = "FetchUnits", ErrorCode = 0, ErrorMessage = String.Empty, Units = d1 };
            String json   = JsonConvert.SerializeObject(packet);
            Program.Logger.Log("UdpSocketServer", $"UdpPacketSent=>{_IPEndPoint.Address}:{_IPEndPoint.Port}=>{json}");
            this.AsyncNetUdpServer.SendAsync(AesEncrypt.Encrypt(Program.AppSettings.ControlKey, json), _IPEndPoint);
        }
Exemplo n.º 13
0
        public async Task ComcryptAsync(Letter letter)
        {
            if (letter.LetterMetadata.Compressed)
            {
                try
                {
                    letter.Body = await Gzip.CompressAsync(letter.Body).ConfigureAwait(false);

                    letter.LetterMetadata.Compressed = true;
                }
                catch { }
            }

            if (!letter.LetterMetadata.Encrypted && (_hashKey?.Length > 0))
            {
                try
                {
                    letter.Body = AesEncrypt.Encrypt(letter.Body, _hashKey);
                    letter.LetterMetadata.Encrypted = true;
                }
                catch { }
            }
        }
Exemplo n.º 14
0
 public void Encrypt256()
 {
     var encryptedData = AesEncrypt.Encrypt(Payload1, HashKey);
 }
Exemplo n.º 15
0
 public void EncryptDecrypt2048()
 {
     var decryptedData = AesEncrypt.Decrypt(AesEncrypt.Encrypt(Payload4, HashKey), HashKey);
 }
Exemplo n.º 16
0
 public void EncryptDecrypt1024()
 {
     var decryptedData = AesEncrypt.Decrypt(AesEncrypt.Encrypt(Payload3, HashKey), HashKey);
 }
Exemplo n.º 17
0
 public void EncryptDecrypt512()
 {
     var decryptedData = AesEncrypt.Decrypt(AesEncrypt.Encrypt(Payload2, HashKey), HashKey);
 }
Exemplo n.º 18
0
 public void Encrypt2048()
 {
     var encryptedData = AesEncrypt.Encrypt(Payload4, HashKey);
 }
Exemplo n.º 19
0
 public void Encrypt1024()
 {
     var encryptedData = AesEncrypt.Encrypt(Payload3, HashKey);
 }
Exemplo n.º 20
0
 public void Encrypt512()
 {
     var encryptedData = AesEncrypt.Encrypt(Payload2, HashKey);
 }