public static DecryptedLoraMessage Decrypt(byte[] data, byte[] key, byte[] iv) { // int8 -> sbyte // uint8 -> byte // word -> ushort using (var aes = new AesManaged { Mode = CipherMode.ECB, Padding = PaddingMode.None }) { var encryptor = aes.CreateEncryptor(key, iv); var dataLengte = data.Length - 13; var blockA = new byte[16]; var work = new byte[dataLengte]; for (var i = 0; i < dataLengte; i++) { work[i] = data[i + 9]; } for (var i = 0; i < dataLengte; i += 16) { blockA[0] = 0x01; blockA[1] = 0x00; blockA[2] = 0x00; blockA[3] = 0x00; blockA[4] = 0x00; blockA[5] = 0; // 0 for uplink frames 1 for downlink frames; blockA[6] = data[1]; // LSB devAddr 4 bytes blockA[7] = data[2]; // .. blockA[8] = data[3]; // .. blockA[9] = data[4]; // MSB blockA[10] = data[6]; // LSB framecounter blockA[11] = data[7]; // MSB framecounter blockA[12] = 0x00; // Frame counter upper Bytes} blockA[13] = 0x00; blockA[14] = 0x00; blockA[15] = Convert.ToByte((i >> 4) + 1); // block sequence counter 1.. var ox = Encrypt(encryptor, blockA); var xor = ox.Select(o => (ushort)o).ToArray(); var k = Math.Min(dataLengte - i, 16); for (var j = 0; j < k; j++) { work[i + j] = (byte)(work[i + j] ^ xor[j]); } } var node = data[1] + (data[2] << 8) + (data[3] << 16) + (data[4] << 24); var decryptedLoraMessage = new DecryptedLoraMessage { Node = node.ToString("X"), Payload = Encoding.ASCII.GetString(work) }; return(decryptedLoraMessage); } }
public static DecryptedLoraMessage Decrypt(byte[] data, byte[] key, byte[] iv) { // int8 -> sbyte // uint8 -> byte // word -> ushort using (var aes = new AesManaged { Mode = CipherMode.ECB, Padding = PaddingMode.None }) { var encryptor = aes.CreateEncryptor(key, iv); var dataLengte = data.Length - 13; var blockA = new byte[16]; var work = new byte[dataLengte]; for (var i = 0; i < dataLengte; i++) { work[i] = data[i + 9]; } for (var i = 0; i < dataLengte; i += 16) { blockA[0] = 0x01; blockA[1] = 0x00; blockA[2] = 0x00; blockA[3] = 0x00; blockA[4] = 0x00; blockA[5] = 0; // 0 for uplink frames 1 for downlink frames; blockA[6] = data[1]; // LSB devAddr 4 bytes blockA[7] = data[2]; // .. blockA[8] = data[3]; // .. blockA[9] = data[4]; // MSB blockA[10] = data[6]; // LSB framecounter blockA[11] = data[7]; // MSB framecounter blockA[12] = 0x00; // Frame counter upper Bytes} blockA[13] = 0x00; blockA[14] = 0x00; blockA[15] = Convert.ToByte((i >> 4) + 1); // block sequence counter 1.. var ox = Encrypt(encryptor, blockA); var xor = ox.Select(o => (ushort) o).ToArray(); var k = Math.Min(dataLengte - i, 16); for (var j = 0; j < k; j++) { work[i + j] = (byte) (work[i + j] ^ xor[j]); } } var node = data[1] + (data[2] << 8) + (data[3] << 16) + (data[4] << 24); var decryptedLoraMessage = new DecryptedLoraMessage { Node = node.ToString("X"), Payload = Encoding.ASCII.GetString(work) }; return decryptedLoraMessage; } }