using System.Collections.Generic;
enum ProtocolType {TCP , UDP};
internal static byte[] EncryptMessage(byte[] pMessage, ProtocolType pProtocolType)
List<byte> mBuffer = new List<byte>();
if ((pMessage != null) && (pMessage.Length > 0))
if (pProtocolType == ProtocolType.TCP)
byte[] intBytes = BitConverter.GetBytes(pMessage.Length);
if (BitConverter.IsLittleEndian) Array.Reverse(intBytes);
mBuffer.AddRange(intBytes);
for (int i = 0; i < pMessage.Length; i++)
byte b = (byte)(key ^ pMessage[i]);
return mBuffer.ToArray();
internal static byte[] DecryptMessage(byte[] pMessage, ProtocolType pProtocolType)
List<byte> mBuffer = new List<byte>();
if (pProtocolType == ProtocolType.TCP)
byte[] intBytes = new byte[4];
Array.Copy(pMessage,0,intBytes,0,4);
if (BitConverter.IsLittleEndian) Array.Reverse(intBytes);
Console.WriteLine(BitConverter.ToInt32(intBytes,0));
if ((pMessage != null) && (pMessage.Length > 0))
for (int i = header; i < pMessage.Length; i++)
byte b = (byte)(key ^ pMessage[i]);
return mBuffer.ToArray();
public static void Main(){
input = "{\"system\":{\"get_sysinfo\":{}}}";
Console.WriteLine("String:");
Console.WriteLine(input);
inputBytes = Encoding.UTF8.GetBytes(input);
byte[] encryptedBytes = EncryptMessage(inputBytes, ProtocolType.TCP);
StringBuilder sb = new StringBuilder(encryptedBytes.Length * 2);
foreach (byte b in encryptedBytes)
sb.AppendFormat("{0:x2}", b);
string encryptedStr = Encoding.UTF8.GetString(encryptedBytes);
Console.WriteLine("Encrypted string:");
Console.WriteLine(encryptedStr);
byte[] decryptedBytes = DecryptMessage(encryptedBytes, ProtocolType.TCP);
string decryptedStr = Encoding.UTF8.GetString(decryptedBytes);
Console.WriteLine("Decrypted string:");
Console.WriteLine(decryptedStr);