private void ExecuteMessage(AESMessage message)
        {
            switch (message.AESAction)
            {
            case AESAction.Generate:
                aesKey            = aesCryptographicService.GenerateKey();
                IsActiveKey       = true;
                message.AESAction = AESAction.None;
                break;

            case AESAction.OpenKey:
                aesKey            = aesSerializaionService.DeserializeKey(message.Path);
                IsActiveKey       = true;
                message.AESAction = AESAction.None;
                break;

            case AESAction.OpenEncryptedData:
                encryptedBuffer        = aesSerializaionService.Deserialize(message.Path);
                EncryptedText          = Encoding.UTF8.GetString(encryptedBuffer);
                Text                   = string.Empty;
                AreActiveEncryptedData = true;
                message.AESAction      = AESAction.None;
                break;

            case AESAction.SaveKey:
                aesSerializaionService.SerializeKey(aesKey, message.Path);
                message.AESAction = AESAction.None;
                break;

            case AESAction.SaveEncryptedData:
                aesSerializaionService.Serialize(encryptedBuffer, message.Path);
                message.AESAction = AESAction.None;
                break;
            }
        }
Example #2
0
        public void CanParseEncryptFile()
        {
            //open file and get json string
            string encrypt_text = GetFileStringContent(encrypt_instruction_filepath);

            //deserialize message
            AESMessage encrypt_message = ParseJson <AESMessage>(encrypt_text, true);

            //check if the plaintext is correct
            List <byte> result_output1 = new List <byte>(encrypt_message.UserText);

            CollectionAssert.AreEqual(TEST_PLAINTEXT, result_output1);

            //check if the key is correct
            List <byte> result_output2 = new List <byte>(encrypt_message.UserKey);

            CollectionAssert.AreEqual(TEST_KEY, result_output2);

            //check if the message type is correct
            int result_output3 = encrypt_message.MessageType;

            Assert.AreEqual((int)MAES_INSTRUCTION.ENCRYPT, result_output3);

            //check if the schema id is correct
            int result_output4 = encrypt_message.SchemaId;

            Assert.AreEqual(SCHEMA_ID, result_output4);

            enc_msg = encrypt_message;
        }
Example #3
0
        private static void Decrypt(AESMessage cyphertext)
        {
            //get the details for the newly created message
            //padding and char replacement
            ReplacedMessage         decrypted_text       = new ReplacedMessage(cyphertext.SchemaId);
            List <CharReplacedText> decrypt_these_blocks = schemaManager.SplitChunks(cyphertext.UserText, decrypted_text.SchemaId).ToList();

            byte[] userkey = cyphertext.UserKey;

            //send to uart
            //receive from uart
            foreach (CharReplacedText byte_block in decrypt_these_blocks)
            {
                List <byte>      dec_rslt        = SendDecryptInstruction(byte_block.Text, userkey).ToList();
                CharReplacedText decrypted_block = new CharReplacedText(decrypted_text.SchemaId);
                decrypted_block.TextPosition = byte_block.TextPosition;
                decrypted_block.Text         = dec_rslt.ToArray();
                decrypted_text.replacedTexts.Add(decrypted_block);
            }

            CharReplacedText replacedMessage = schemaManager.CharacterReplaceCyphertext(decrypted_text);

            //create return message
            AESMessage decrypt_result = new AESMessage();

            decrypt_result.MessageType = (int)MAES_INSTRUCTION.DECRYPTRESULT;
            decrypt_result.SchemaId    = replacedMessage.SchemaId;
            decrypt_result.ServerText  = replacedMessage.Text;

            //send message back to the device it came from
            SendAESMessage(decrypt_result);
        }
Example #4
0
        private static void Encrypt(AESMessage plaintext)
        {
            //get the details for the newly created message
            //padding and char replacement
            CharReplacedText charReplacedText = new CharReplacedText(plaintext.SchemaId);

            charReplacedText.Text = plaintext.UserText;
            ReplacedMessage full_message = schemaManager.CharacterReplacePlaintext(charReplacedText);

            byte[] userkey = plaintext.UserKey;

            List <byte> encryption_result = new List <byte>();

            //send to uart
            //receive from uart
            foreach (CharReplacedText byte_block in full_message.replacedTexts)
            {
                List <byte> enc_rslt = SendEncryptInstruction(byte_block.Text, userkey).ToList();
                encryption_result.AddRange(enc_rslt);
            }

            //create return message
            AESMessage encrypt_result = new AESMessage();

            encrypt_result.MessageType = (int)MAES_INSTRUCTION.ENCRYPTRESULT;
            encrypt_result.SchemaId    = full_message.SchemaId;
            encrypt_result.ServerText  = encryption_result.ToArray();

            //send message back to the device it came from
            SendAESMessage(encrypt_result);
        }
 private void ExecuteAESMessage(AESMessage message)
 {
     if (message.AESAction == AESAction.Encrypt)
     {
         AreActiveAESEncryptedData = true;
     }
     SetAESStatus(AESAction);
 }
Example #6
0
        private static void DelSchema(AESMessage message)
        {
            bool can_delete = schemaManager.RequestDeleteSchema(message.SchemaId);

            if (!can_delete)
            {
                throw new KeyNotFoundException("Schema::Delete::Request::NOT::FOUND");
            }
        }
Example #7
0
        private static void NewSchema(AESMessage message)
        {
            int        new_schema = schemaManager.RequestNewSchema();
            AESMessage result     = new AESMessage()
            {
                MessageType = (int)MAES_INSTRUCTION.NEWSCHEMARESULT,
                SchemaId    = new_schema
            };

            SendAESMessage(result);
        }
Example #8
0
        private static void SendAESMessage(AESMessage msg)
        {
            byte[] encoded_text = encode_set.GetBytes(JsonConvert.SerializeObject(msg));
#if DEBUG
            Console.WriteLine("UDP::TX::TRANS::{0}::{1}", System.DateTime.Now.ToString("HH:mm:ss:ffff"), m_udp.identifier_one);
            m_udp.Send(encoded_text);
#endif
#if RELEASE
            Console.WriteLine("UDP::TX::TRANS::{0}::{1}", System.DateTime.Now.ToString("HH:mm:ss:ffff"), m_udp.identifier_one);
            m_udp.Send(encoded_text);
#endif
        }
Example #9
0
        public void EncrptedSendLarge <T>(Connection connection, ref T message) where T : IMessage
        {
            if (!AESKeys.TryGetValue(connection, out string Key))
            {
                Log.WriteNow("Failed to find AES Key for this connection. Failed to send encrypted message");
                return;
            }

            AESMessage aesMessage = new AESMessage(message)
            {
                ID = message.ID
            };

            aesMessage.Encrypt(Key);
            byte[] data = MessageUtil.Serialize(ref aesMessage);

            SendLarge(connection, ref aesMessage, data);
        }
Example #10
0
        public void EncrptedSend <T>(ref T message) where T : IMessage
        {
            message.TotalParts = 1;
            message.Part       = 0;
            message.ID         = message.ID != 0 ? message.ID : NextID;

            AESMessage aesMessage = new AESMessage(message)
            {
                ID = message.ID
            };

            aesMessage.Encrypt(AESKey);

            byte[] data = MessageUtil.Serialize(ref aesMessage);
            BitConverter.GetBytes(data.Length).CopyTo(data, 6);

            rawClient.Send(data);
        }
Example #11
0
        // =============== Process Data ===================

        void ProcessData(Connection conn, byte[] payload, int len)
        {
            Header header = MessageUtil.DeserializeHeader(payload, len);

            // ======== Encypted Message ===============
            if (header.Channel == MessageTypes.AESMessage)
            {
                if (AESKeys.TryGetValue(conn, out string key))
                {
                    try
                    {
                        AESMessage message = AESMessage.Desserialize(payload, len);
                        message.Decrypt(key);
                        payload = message.message;
                        header  = MessageUtil.DeserializeHeader(payload, payload.Length);

                        if (header.Parted)
                        {
                            ProcessMesagePart(ref header, conn, payload, payload.Length);
                        }
                        else
                        {
                            ProcessMessage(ref header, conn, payload, payload.Length);
                        }
                        return;
                    }
                    catch { Log.WriteNow("Failed to pass Encrypted Message. Wrong Key?"); return; }
                }
                else
                {
                    Log.WriteNow("Failed to pass Encrypted Message. No Key Found For Connection"); return;
                }
            }
            // ========= End Encrpted Message ==================

            if (header.Parted)
            {
                ProcessMesagePart(ref header, conn, payload, len);
            }
            else
            {
                ProcessMessage(ref header, conn, payload, len);
            }
        }
Example #12
0
        public void EncrptedSend <T>(Connection connection, ref T message) where T : IMessage
        {
            if (!AESKeys.TryGetValue(connection, out string Key))
            {
                Log.WriteNow("Failed to find AES Key for this connection. Failed to send encrypted message");
                return;
            }

            AESMessage aesMessage = new AESMessage(message)
            {
                ID = message.ID
            };

            aesMessage.Encrypt(Key);
            byte[] buffer = MessageUtil.Serialize(ref aesMessage);
            BitConverter.GetBytes(buffer.Length).CopyTo(buffer, 6);

            rawServer.Send(connection, buffer);
        }
Example #13
0
        public void EncrptedSendLarge <T>(ref T message, byte[] Data = null) where T : IMessage
        {
            message.ID = message.ID != 0 ? message.ID : NextID;

            if (Data == null)
            {
                // Message not already serialized
                Data = MessageUtil.Serialize(ref message);
                BitConverter.GetBytes(Data.Length).CopyTo(Data, 6);
            }

            AESMessage aesMessage = new AESMessage(Data)
            {
                ID = message.ID
            };

            aesMessage.Encrypt(AESKey);
            byte[] data = MessageUtil.Serialize(ref message);

            SendLarge(ref aesMessage, data);
        }
Example #14
0
        public void CanParseSchemaFiles()
        {
            //open file and get json string
            string new_msg_text = GetFileStringContent(new_schema_instruction_filepath);
            string del_msg_text = GetFileStringContent(del_schema_instruction_filepath);

            //deserialize message
            AESMessage new_schema_msg = ParseJson <AESMessage>(new_msg_text, true);
            AESMessage del_schema_msg = ParseJson <AESMessage>(del_msg_text, true);

            /// check if the message type is correct
            Assert.AreEqual((int)MAES_INSTRUCTION.NEWSCHEMA, new_schema_msg.MessageType);
            Assert.AreEqual((int)MAES_INSTRUCTION.DELSCHEMA, del_schema_msg.MessageType);

            //check if the schema id is correct
            Assert.AreEqual(NEW_SCHEMA_ID, new_schema_msg.SchemaId);
            Assert.AreEqual(NEW_SCHEMA_ID, del_schema_msg.SchemaId);

            new_msg = new_schema_msg;
            del_msg = del_schema_msg;
        }
Example #15
0
        // ============== Processing Data ===============

        void ProcessData(byte[] payload, int len)
        {
            Header header = MessageUtil.DeserializeHeader(payload, len);

            // ======== Encypted Message ===============
            if (header.Channel == MessageTypes.AESMessage)
            {
                try
                {
                    AESMessage message = AESMessage.Desserialize(payload, len);
                    message.Decrypt(AESKey);
                    payload = message.message;
                    header  = MessageUtil.DeserializeHeader(payload, payload.Length);

                    if (header.Parted)
                    {
                        ProcessMessagePart(ref header, payload, payload.Length);
                    }
                    else
                    {
                        ProcessMessage(ref header, payload, payload.Length);
                    }

                    return;
                }
                catch { Log.WriteNow("Failed to pass Encrypted Message. Wrong Key?"); return; }
            }
            // ========= End Encrpted Message ==================

            if (header.Parted)
            {
                ProcessMessagePart(ref header, payload, len);
            }
            else
            {
                ProcessMessage(ref header, payload, len);
            }
        }
Example #16
0
        //TODO: Make Service Scalable (OPTIONAL)

        private static void MessageControllerService()
        {
            //thread
            Console.WriteLine("Message Controller Start");
            while (true)
            {
                //message flow will happen here
                byte[] from_udp    = WaitForOrderFromUDP();
                string json_string = encode_set.GetString(from_udp);
                try
                {
                    //MessageType 1 Encrypt this
                    //MessageType 2 Decrypt this
                    //MessageType 3 Encryption Result
                    //MessageType 4 Decryption Result
                    //MessageType 5 new Character Replacement Schema
                    //MessageType 6 delete Character Replacement Schema
                    //MessageType 7 notify new Character Replacement Schema

                    string replace_null = json_string.Replace("\"null\"", "null");
#if DEBUG
                    Console.WriteLine("UDP::MSG::{0}", replace_null);
#endif
                    AESMessage incoming_message = JsonConvert.DeserializeObject <AESMessage>(replace_null);

                    int CharSchemaId = incoming_message.SchemaId;

                    switch (incoming_message.MessageType)
                    {
                    case (int)MAES_INSTRUCTION.ENCRYPT:
                    {
                        Encrypt(incoming_message);
                        break;
                    };

                    case (int)MAES_INSTRUCTION.DECRYPT:
                    {
                        Decrypt(incoming_message);
                        break;
                    };

                    case (int)MAES_INSTRUCTION.NEWSCHEMA:
                    {
                        NewSchema(incoming_message);
                        break;
                    }

                    case (int)MAES_INSTRUCTION.DELSCHEMA:
                    {
                        DelSchema(incoming_message);
                        break;
                    }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.StackTrace);
                    AESMessage error_result = new AESMessage();
                    error_result.MessageType = (int)MAES_INSTRUCTION.ERRORRESULT;
                    error_result.SchemaId    = 1;
                    error_result.ServerText  = encode_set.GetBytes(e.StackTrace);

                    //send message back to the device it came from
                    SendAESMessage(error_result);
                }
                Thread.Sleep(50);
            }
        }