namespace JiLinApp.Docking.FenceAlarm; public class AlarmEncode { private static byte[] TEA_key = new byte[16] { 0x08,0x01,0x08,0x06,0x07,0x08,0x07,0x08, 0x08,0x90,0xC5,0x04,0x0D,0x0E,0x0F,0x10 }; public static byte[] encodeMessage(byte[] msg) { if (!checkMessage(msg)) return null; return getMessage(msg[0], btea_encrypt(getContent(msg, msg[0] - 1))); } public static byte[] decodeMessage(byte[] msg) { if (!checkMessage(msg)) return null; return getMessage(msg[0], btea_decrpyt(getContent(msg, msg[0] - 1))); } public static byte[] CRC16(byte[] data) { int len = data.Length; if (len > 0) { ushort crc = 0xFFFF; for (int i = 0; i < len; i++) { crc = (ushort)(crc ^ (data[i])); for (int j = 0; j < 8; j++) { crc = (crc & 1) != 0 ? (ushort)((crc >> 1) ^ 0xA001) : (ushort)(crc >> 1); } } byte hi = (byte)((crc & 0xFF00) >> 8); //高位置 byte lo = (byte)(crc & 0x00FF); //低位置 return new byte[] { hi, lo }; } return new byte[] { 0, 0 }; } private static byte version = 0x12; private static byte[] head = new byte[] { 0xF0, 0xFA }; private static byte end = 0x0D; public static byte[] getSendMessage(byte command, byte[] data) { byte[] msg = null; if (data == null) { msg = new byte[8]; } else { msg = new byte[data.Length + 8]; } msg[0] = (byte)msg.Length; msg[1] = version; msg[2] = head[0]; msg[3] = head[1]; msg[4] = command; if (data != null) { for (int i = 0; i < data.Length; i++) { msg[i + 5] = data[i]; } } byte[] subMsg = null; if (data == null) { subMsg = new byte[4]; } else { subMsg = new byte[4 + data.Length]; } for (int i = 0; i < subMsg.Length; i++) { subMsg[i] = msg[i + 1]; } byte[] crc = CRC16(subMsg); msg[msg.Length - 3] = crc[1]; msg[msg.Length - 2] = crc[0]; msg[msg.Length - 1] = end; return msg; } private static bool checkMessage(byte[] msg) { if (msg == null) return false; if (msg[0] > msg.Length) return false; return true; } private static byte[] getContent(byte[] msg, int len) { byte[] bytes = new byte[len]; for (int i = 0; i < len; i++) { bytes[i] = msg[i + 1]; } return bytes; } private static byte[] getMessage(byte msgLen, byte[] msg) { byte[] out_msg = new byte[msg.Length + 1]; out_msg[0] = msgLen; for (int i = 0; i < msg.Length; i++) { out_msg[i + 1] = msg[i]; } return out_msg; } private static byte[] btea_encrypt(byte[] bytes) { byte[] output = new byte[bytes.Length]; for (int i = 0; i < bytes.Length; i++) { byte abyte = (byte)(bytes[i] ^ TEA_key[i % 16]); output[i] = (byte)(((byte)(abyte >> 3)) | ((byte)(abyte << 5))); } return output; } private static byte[] btea_decrpyt(byte[] bytes) { byte[] output = new byte[bytes.Length]; for (int i = 0; i < bytes.Length; i++) { byte abyte = (byte)(((byte)(bytes[i] << 3)) | ((byte)(bytes[i] >> 5))); output[i] = (byte)(abyte ^ TEA_key[i % 16]); } return output; } }