sandeepmistry / arduino-LoRa

An Arduino library for sending and receiving data using LoRa radios.
MIT License
1.6k stars 621 forks source link

Problem with aes256 #632

Closed alemori closed 1 year ago

alemori commented 1 year ago

I am encrypting data that I send by Lora with Aes256, I use:#include "mbedtls/aes.h" #include <mbedtls/md.h>, and when I receive it I get a memory dump.

include

include

ifdef ARDUINO_SAMD_MKRWAN1300

error "This example is not compatible with the Arduino MKR WAN 1300 board!"

endif

define ss 5

define rst 2

define dio0 4

void setup() { Serial.begin(9600); while (!Serial);

Serial.println("LoRa Receiver Callback"); LoRa.setPins(ss, rst,dio0);

if (!LoRa.begin(433E6)) {
  Serial.println("Starting LoRa failed!");
  while (1);
}

// Uncomment the next line to disable the default AGC and set LNA gain, values between 1 - 6 are supported // LoRa.setGain(6);

// register the receive callback LoRa.onReceive(onReceive);

// put the radio into receive mode LoRa.receive(); }

void loop() { // do nothing }

void onReceive(int packetSize) { // received a packet Serial.print("Received packet '");

// read packet for (int i = 0; i < packetSize; i++) { Serial.print((char)LoRa.read()); }

// print RSSI of packet Serial.print("' with RSSI "); Serial.println(LoRa.packetRssi()); }

⸮E0⸮⸮1⸮⸮ʄ⸮⸮⸮⸮⸮J⸮LoRa Receiver Callback Guru Meditation Error: Core 1 panic'ed (Interrupt wdt timeout on CPU1).

Core 1 register dump: PC : 0x4008aa52 PS : 0x00060b35 A0 : 0x800899c6 A1 : 0x3ffbf13c
A2 : 0x3ffb8a00 A3 : 0x3ffb8890 A4 : 0x00000004 A5 : 0x00060b23
A6 : 0x00060b23 A7 : 0x00000001 A8 : 0x3ffb8890 A9 : 0x00000018
A10 : 0x3ffb8890 A11 : 0x00000018 A12 : 0x3ffc2adc A13 : 0x00060b23
A14 : 0x007bf328 A15 : 0x003fffff SAR : 0x0000001b EXCCAUSE: 0x00000006
EXCVADDR: 0x00000000 LBEG : 0x4008638d LEND : 0x4008639d LCOUNT : 0xfffffffc
Core 1 was running in ISR context: EPC1 : 0x400db87b EPC2 : 0x00000000 EPC3 : 0x00000000 EPC4 : 0x00000000

Backtrace: 0x4008aa4f:0x3ffbf13c |<-CORRUPTED

Core 0 register dump: PC : 0x4008abeb PS : 0x00060035 A0 : 0x800895ef A1 : 0x3ffbea4c
A2 : 0x3ffbf328 A3 ⸮

Decoding 3 results 0x4008aa52: vListInsert at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/freertos/list.c line 166 (discriminator 1) 0x4008638d: strlen at /builds/idf/crosstool-NG/.build/HOST-i686-w64-mingw32/xtensa-esp32-elf/src/newlib/newlib/libc/machine/xtensa/strlen.S line 84 0x4008639d: strlen at /builds/idf/crosstool-NG/.build/HOST-i686-w64-mingw32/xtensa-esp32-elf/src/newlib/newlib/libc/machine/xtensa/strlen.S line 96

Kongduino commented 1 year ago

Please surround your code with 3 backticks + c and 3 backticks to make it readable. Or select it and click add code...

alemori commented 1 year ago

Hi, I am going to put the code I use for sending the package, and the other sketch is the one I use for receiving. I clarify that in order not to put more complexity to the problem, for the case of the one that receives the package, there is not the decryption process.

/ Modified from the examples of the Arduino LoRa library More resources: https://randomnerdtutorials.com /

#include <SPI.h>
#include <LoRa.h>
#include "mbedtls/aes.h"
#include <mbedtls/md.h>

//define the pins used by the transceiver module
#define ss 5
#define rst 2
#define dio0 4

String strToSHA256(String input) {
  char payload[input.length() + 1];
  input.toCharArray(payload, input.length() + 1);
  byte shaResult[32];
  mbedtls_md_context_t ctx;
  mbedtls_md_type_t md_type = MBEDTLS_MD_SHA256;
  mbedtls_md_init(&ctx);
  mbedtls_md_setup(&ctx, mbedtls_md_info_from_type(md_type), 0);
  mbedtls_md_starts(&ctx);
  mbedtls_md_update(&ctx, (const unsigned char *) payload,
                    strlen(payload));
  mbedtls_md_finish(&ctx, shaResult);
  mbedtls_md_free(&ctx);
  String output;
  for (int i = 0; i < sizeof(shaResult); i++) {
    char str[3];
    sprintf(str, "%02x", (int)shaResult[i]);
    output += str;
  }
  return output;
}

String str_AES256_enc(String i_key, String salt, String input) {
  char s2[input.length() + 1];
  input.toCharArray(s2, input.length() + 1);
  size_t bs = ((input.length() / 16) + 1) * 16;
  char plaintext[bs];
  char encrypted[bs];
  char key[256];
  String o_key = strToSHA256(i_key);
  o_key.toCharArray(key, 256);
  char iv[16];
  // String o_iv = strToSHA256(salt).substring(48, 64);
  String o_iv = strToSHA256(salt);
  o_iv.toCharArray(iv, 16);
  memset(plaintext, 0, sizeof(plaintext));
  memset(encrypted, 0, sizeof(encrypted));
  strcpy(plaintext, (const char*)s2);
  esp_aes_context aes;
  esp_aes_init(&aes);
  esp_aes_setkey(&aes, (const unsigned char *)key, 256);
  esp_aes_crypt_cbc(&aes, ESP_AES_ENCRYPT, sizeof(plaintext),
                    (unsigned char*)iv, (uint8_t*)plaintext, (uint8_t*)encrypted);
  esp_aes_free(&aes);
  memset(plaintext, 0, sizeof( plaintext));
  memset(iv, 0, sizeof(iv));
  return encrypted;
}

String str_AES256_dec(String i_key, String salt, String input) {
  char s2[input.length() + 1];
  input.toCharArray(s2, input.length() + 1);
  size_t bs = ((input.length() / 16) + 1) * 16;
  char plaintext[bs];
  char encrypted[bs];
  char key[256];
  String o_key = strToSHA256(i_key);
  o_key.toCharArray(key, 256);
  char iv[16];
  //String o_iv = strToSHA256(salt).substring(48, 64);
   String o_iv = strToSHA256(salt);
  o_iv.toCharArray(iv, 16);
  memset(encrypted, 0, sizeof(encrypted));
  strcpy(encrypted, (const char*)s2);
  esp_aes_context aes;
  esp_aes_init(&aes);
  esp_aes_setkey(&aes, (const unsigned char *)key, 256);
  esp_aes_crypt_cbc(&aes, ESP_AES_DECRYPT, sizeof(encrypted),
                    (unsigned char*)iv, (uint8_t*)encrypted, (uint8_t*)plaintext);
  esp_aes_free(&aes);
  return plaintext;
}

int counter = 0;

void setup() {
  //initialize Serial Monitor
  Serial.begin(9600);
  while (!Serial);
  Serial.println("LoRa Sender");

  //setup LoRa transceiver module
  LoRa.setPins(ss, rst, dio0);

  //replace the LoRa.begin(---E-) argument with your location's frequency
  //433E6 for Asia
  //866E6 for Europe
  //915E6 for North America
  while (!LoRa.begin(433E6)) {
    Serial.print(".");
    delay(500);
  }

  Serial.println("LoRa Initializing OK!");
}

void loop() {
  Serial.print("Sending packet: ");
  Serial.println(counter);

  String pepito = "Hola como te va";
  Serial.println("pepito");
  String salida1 = strToSHA256(pepito);
  Serial.println (salida1);
  String i_key = "esta la clave";
  String salt = pepito;
  String input = "Tech tutorials ";
  String Encryp = str_AES256_enc(i_key, salt, input);
  delay(100);
  Serial.println("encripto");
  Serial.println (Encryp);

  //Send LoRa packet to receiver
  LoRa.beginPacket();
  LoRa.print("hello ");
  LoRa.print("|");
  LoRa.print(i_key);
  LoRa.print("|");
  LoRa.print(salt);
  LoRa.print("|");
  Serial.println(sizeof(Encryp));
  LoRa.print(Encryp);

  LoRa.endPacket();

  counter++;

  delay(100);
}
Kongduino commented 1 year ago

The first thing to do is to put the error log into the ESP Exception Decoder. This will tell you – hopefully – where the problem happens.

After that, there are a few general issues with your code.

• Do not use Arduino String objects. They're not only wasteful, and slow down your program, but also, since your AES functions and the LoRa library use char arrays, there's no reason not to use that throughout the code.

• Also, you're sending a hex string instead of just the bytes, which is again wasteful and doesn't make sense. You could just send the char array with LoRa.write(buf, len). A much shorter and faster transmission...

• You're sending the key, in clear, in the packet. WHY!?!? You should only send the IV (first) + ciphertext blocks.

• You're using a static IV. DON'T. It defeats the purpose of an IV. Generate a non-predictable IV on the spot, every time. You could use the random generator that the SX1276 provides, except it is broken in this library. See LoRandom for an example of a functioning LoRa RNG.

alemori commented 1 year ago

Thank you for your response. I activated the debug and the output is in the first code I sent, which is about the reception of the package. The truth is that I use String because it is easier for me, and it is what I saw in examples, but I will try to modify the code. On the other hand, the dump will stop when I avoid the use of the onRecive() function. I would like to know what is the problem with the dump. Please wait for instructions, and I clarify that I do not have too much expertise in the handling of c++ but with a guide I can follow the problem. Thank you very much for your help.

⸮E0��⸮⸮1⸮⸮ʄ⸮�⸮⸮⸮�⸮J⸮LoRa Receiver Callback Guru Meditation Error: Core 1 panic'ed (Interrupt wdt timeout on CPU1).

Core 1 register dump: PC : 0x4008aa52 PS : 0x00060b35 A0 : 0x800899c6 A1 : 0x3ffbf13c A2 : 0x3ffb8a00 A3 : 0x3ffb8890 A4 : 0x00000004 A5 : 0x00060b23 A6 : 0x00060b23 A7 : 0x00000001 A8 : 0x3ffb8890 A9 : 0x00000018 A10 : 0x3ffb8890 A11 : 0x00000018 A12 : 0x3ffc2adc A13 : 0x00060b23 A14 : 0x007bf328 A15 : 0x003fffff SAR : 0x0000001b EXCCAUSE: 0x00000006 EXCVADDR: 0x00000000 LBEG : 0x4008638d LEND : 0x4008639d LCOUNT : 0xfffffffc Core 1 was running in ISR context: EPC1 : 0x400db87b EPC2 : 0x00000000 EPC3 : 0x00000000 EPC4 : 0x00000000

Backtrace: 0x4008aa4f:0x3ffbf13c |<-CORRUPTED

Core 0 register dump: PC : 0x4008abeb PS : 0x00060035 A0 : 0x800895ef A1 : 0x3ffbea4c A2 : 0x3ffbf328 A3 ⸮

Decoding 3 results 0x4008aa52: vListInsert at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/freertos/list.c line 166 (discriminator 1) 0x4008638d: strlen at /builds/idf/crosstool-NG/.build/HOST-i686-w64-mingw32/xtensa-esp32-elf/src/newlib/newlib/libc/machine/xtensa/strlen.S line 84 0x4008639d: strlen at /builds/idf/crosstool-NG/.build/HOST-i686-w64-mingw32/xtensa-esp32-elf/src/newlib/newlib/libc/machine/xtensa/strlen.S line 96

Kongduino commented 1 year ago

The debug log isn't at its clearest but it does seem to point to a string issue. Unfortunately it doesn't say where it originates from in your code, just where in the IDF.

Also, another mistake I hadn't spotted before, silly me. Delays between LoRa sends should be in tens of seconds, not milliseconds. If you do delay(100); there's not enough time to send your packet: you're sending packets of around 60 bytes, which takes more than 100 ms even at SF7 BW125. At SF10 BW125, we're talking about 650 ms. And that's just the technical reason. You also should not flood the airwaves with your stuff – there may be other people around you trying to send / receive.

And on the subject of delays, do not use delay – delays are blocking. In loop() you should use a reference time, acquired from millis(), and compare with the present time. eg

// global object
uint32_t t0;
// time between pings in milliseconds
#define PING_DELAY 10000 // ten seconds

void setup() {
  // last line in setup()
  t0 = millis(); // get an initial time reference
}

void loop() {
  if(millis() - t0 > MY_PING_DELAY) {
    // send a lora packet
    [...]
    t0 = millis(); // update time reference
  }
}

That way your code is non-blocking.

morganrallen commented 1 year ago

@alemori does it seem to pause for a moment between LoRa Receiver Callback and Guru Meditation Error: Core 1 panic'ed (Interrupt wdt timeout on CPU1). ?

That error message indicates something it holding the task and taking too long. Check any loops in the decryption portion of the code, something could be looping forever.

alemori commented 1 year ago

Thanks again. I think the problem may come from the timing issue, I did not take into account not to use delay, but to produce the delay with millis(). I will make the changes and see what result I get. As for the issue of avoiding String, I understand that they can be more inefficient, but they should not cause a dump.

Kongduino commented 1 year ago

Considering that the error happens in strlen.S and list.c I wouldn't be so quick dismissing the usage of String as an issue...

alemori commented 1 year ago

Hi, I made the proposed changes regarding the delays and changing the String. It still gives a memory overwrite. Copy the send and receive sketches. Thank you very much for your help.

// Sketch Emisor

include

include

include

include "DHT.h"

include "WiFi.h"

include

/ Clase para registrar nodo /

include

include

/ Biblioteca AES256 /

include "mbedtls/aes.h"

include <mbedtls/md.h>

define ss 5

define rst 2

define dio0 4

if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)

error Bluetooth is not enabled! Please run make menuconfig to and enable it

endif

define DHTPIN 33 // Pin donde está conectado el sensor

define DHTTYPE DHT22 // Sensor DHT22

DHT dht(DHTPIN, DHTTYPE);

String json; String json2;

int counter = 0; int counterWakeUp = 0; String message = ""; char incomingChar; int s1 = 0; int s2 = 0; int s3 = 0; int mando = 0; int alerta_a = 1; float primer_ciclo = 0; long tiempo_inicial = 0;

StaticJsonDocument<200> doc; StaticJsonDocument<50> doc2;

define uS_TO_S_FACTOR 1000000ULL / Conversion factor for micro seconds to seconds /

define TIME_TO_SLEEP 9 / Time ESP32 will go to sleep (in seconds) /

uint32_t t0;

define MY_PING_DELAY 5000 // ten seconds

void print_wakeup_reason() { esp_sleep_wakeup_cause_t wakeup_reason; wakeup_reason = esp_sleep_get_wakeup_cause();

switch (wakeup_reason) { case ESP_SLEEP_WAKEUP_EXT0 : Serial.println("Wakeup caused by external signal using RTC_IO"); break; case ESP_SLEEP_WAKEUP_EXT1 : Serial.println("Wakeup caused by external signal using RTC_CNTL"); break; case ESP_SLEEP_WAKEUP_TIMER : Serial.println("Wakeup caused by timer"); break; case ESP_SLEEP_WAKEUP_TOUCHPAD : Serial.println("Wakeup caused by touchpad"); break; case ESP_SLEEP_WAKEUP_ULP : Serial.println("Wakeup caused by ULP program"); break; default : Serial.printf("Wakeup was not caused by deep sleep: %dn", wakeup_reason); break; } }

/ Rutinas de AES para encriptar, descencriptar y SHA256 /

String strToSHA256(String input) { char payload[input.length() + 1]; input.toCharArray(payload, input.length() + 1); byte shaResult[32]; mbedtls_md_context_t ctx; mbedtls_md_type_t md_type = MBEDTLS_MD_SHA256; mbedtls_md_init(&ctx); mbedtls_md_setup(&ctx, mbedtls_md_info_from_type(md_type), 0); mbedtls_md_starts(&ctx); mbedtls_md_update(&ctx, (const unsigned char *) payload, strlen(payload)); mbedtls_md_finish(&ctx, shaResult); mbedtls_md_free(&ctx); String output; for (int i = 0; i < sizeof(shaResult); i++) { char str[3]; sprintf(str, "%02x", (int)shaResult[i]); output += str; } return output; }

String str_AES256_enc(String i_key, String salt, String input) { char s2[input.length() + 1]; input.toCharArray(s2, input.length() + 1); size_t bs = ((input.length() / 16) + 1) 16; char plaintext[bs]; char encrypted[bs]; char key[256]; String o_key = strToSHA256(i_key); o_key.toCharArray(key, 256); char iv[16]; String o_iv = strToSHA256(salt).substring(48, 64); // String o_iv = strToSHA256(salt); o_iv.toCharArray(iv, 16); memset(plaintext, 0, sizeof(plaintext)); memset(encrypted, 0, sizeof(encrypted)); strcpy(plaintext, (const char)s2); esp_aes_context aes; esp_aes_init(&aes); esp_aes_setkey(&aes, (const unsigned char )key, 256); esp_aes_crypt_cbc(&aes, ESP_AES_ENCRYPT, sizeof(plaintext), (unsigned char)iv, (uint8_t)plaintext, (uint8_t)encrypted); esp_aes_free(&aes); memset(plaintext, 0, sizeof( plaintext)); memset(iv, 0, sizeof(iv)); return encrypted; }

String str_AES256_dec(String i_key, String salt, String input) { char s2[input.length() + 1]; input.toCharArray(s2, input.length() + 1); size_t bs = ((input.length() / 16) + 1) 16; char plaintext[bs]; char encrypted[bs]; char key[256]; String o_key = strToSHA256(i_key); o_key.toCharArray(key, 256); char iv[16]; String o_iv = strToSHA256(salt).substring(48, 64); // String o_iv = strToSHA256(salt); o_iv.toCharArray(iv, 16); memset(encrypted, 0, sizeof(encrypted)); strcpy(encrypted, (const char)s2); esp_aes_context aes; esp_aes_init(&aes); esp_aes_setkey(&aes, (const unsigned char )key, 256); esp_aes_crypt_cbc(&aes, ESP_AES_DECRYPT, sizeof(encrypted), (unsigned char)iv, (uint8_t)encrypted, (uint8_t)plaintext); esp_aes_free(&aes); return plaintext; }

void setup() { Serial.begin(9600); dht.begin();

Serial.println("LoRa Sender"); LoRa.setPins(ss, rst, dio0); while (!LoRa.begin(433E6)) { Serial.print("."); delay(500); } t0 = millis(); // get an initial time reference }

void loop() { if(millis() - t0 > MY_PING_DELAY) { print_wakeup_reason(); //Print the wakeup reason for ESP32 counterWakeUp++; float h = dht.readHumidity(); //Leemos la Humedad float tt = dht.readTemperature(); //Leemos la temperatura en grados Celsius float f = dht.readTemperature(true); //Leemos la temperatura en grados Fahrenheit doc["sensor"] = h; doc["time"] = tt; int Boton_alerta = digitalRead(32);

// print_wakeup_reason(); //Print the wakeup reason for ESP32 counterWakeUp++; // Serial.println(counterWakeUp%30); if (counterWakeUp % 30 == 0) //Cada 30 segundos envía { Serial.println("Starting LoRa"); if (!LoRa.begin(433E6)) { Serial.println("Starting LoRa failed!"); delay(100); while (1); } esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR); // ESP32 wakes up every 5 seconds Serial.println("Going to light-sleep now"); Serial.flush(); esp_light_sleep_start(); Serial.println("Sending packet: "); //Serial.println(counter);

Serial.println(json);
String input = json;
String i_key = "esta la clave";
String tghash = strToSHA256(i_key).substring(0, 8);
String packedhash = strToSHA256(input).substring(0, 8);
String Encryp = str_AES256_enc(packedhash, tghash, input);
LoRa.beginPacket();
Serial.println("envio");
byte dec[packedhash.length() + 1];
packedhash.getBytes(dec, packedhash.length());
LoRa.write(dec, packedhash.length() + 1);
Serial.println(packedhash.length());
LoRa.print("|");
byte dec1[tghash.length() + 1];
tghash.getBytes(dec1, tghash.length());
LoRa.write(dec1, tghash.length() + 1);
Serial.println(tghash.length());
LoRa.print("|");
byte dec2[Encryp.length() + 1];
tghash.getBytes(dec2, Encryp.length());
LoRa.write(dec2, Encryp.length() + 1);
Serial.println(Encryp.length());
LoRa.endPacket();
json = "";
json2 = "";

} t0 = millis(); // update time reference delay(1000); } }

// Sketch Receptor

include

include

include

include

include

include

include "mbedtls/aes.h"

include <mbedtls/md.h>

define accessPointButtonPin 33 // Connect a button to this pin

WebServer server(80); // the Access Point Server

include

define accessPointLed 2

define eepromTextVariableSize 33 // the max size of the ssid, password etc. 32+null terminated

define LORA_PACKET_ID_SIZE 8

define LORA_TG_ID_SIZE 8

define MY_PING_DELAY 100000

//---------- wifi default settings ------------------

/ Enable these lines in case you want to change the default Access Point ip: 192.168.4.1. You have to enable the line: WiFi.softAPConfig(local_ip, gateway, subnet); on the void initAsAccessPoint too /

boolean accessPointMode = false; // is true every time the board is started as Access Point boolean debug = true; unsigned long lastUpdatedTime = 0;

int pushDownCounter = 0; int lastConnectedStatus = 0;

define ss 5

define rst 2

define dio0 4

int newMessage = 0; char mensaje; String inString = ""; // string to hold String magnitudLora; String valorLora; int contador = 0; String outputs; uint32_t t0; WiFiManager wifiManager; bool loraConfig = 0; String strToSHA256(String input) { char payload[input.length() + 1]; input.toCharArray(payload, input.length() + 1); byte shaResult[32]; mbedtls_md_context_t ctx; mbedtls_md_type_t md_type = MBEDTLS_MD_SHA256; mbedtls_md_init(&ctx); mbedtls_md_setup(&ctx, mbedtls_md_info_from_type(md_type), 0); mbedtls_md_starts(&ctx); mbedtls_md_update(&ctx, (const unsigned char *) payload, strlen(payload)); mbedtls_md_finish(&ctx, shaResult); mbedtls_md_free(&ctx); String output; for (int i = 0; i < sizeof(shaResult); i++) { char str[3]; sprintf(str, "%02x", (int)shaResult[i]); output += str; } return output; }

String str_AES256_dec(String i_key, String salt, String input) { char s2[input.length() + 1]; input.toCharArray(s2, input.length() + 1); size_t bs = ((input.length() / 16) + 1) 16; char plaintext[bs]; char encrypted[bs]; char key[256]; String o_key = strToSHA256(i_key); o_key.toCharArray(key, 256); char iv[16]; String o_iv = strToSHA256(salt).substring(48, 64); // String o_iv = strToSHA256(salt); o_iv.toCharArray(iv, 16); memset(encrypted, 0, sizeof(encrypted)); strcpy(encrypted, (const char)s2); esp_aes_context aes; esp_aes_init(&aes); esp_aes_setkey(&aes, (const unsigned char )key, 256); esp_aes_crypt_cbc(&aes, ESP_AES_DECRYPT, sizeof(encrypted), (unsigned char)iv, (uint8_t)encrypted, (uint8_t)plaintext); esp_aes_free(&aes); return plaintext; }

//================================================ void setup() { Serial.begin(115200); delay(500); pinMode(32, INPUT); int sensorVal = digitalRead(25); Serial.println("sensorval"); Serial.println(sensorVal); if (sensorVal == 1) { Serial.println("reset wifi"); wifiManager.resetSettings(); delay(500); } wifiManager.autoConnect("AutoConnectAP"); Serial.println("connected...yeey :)"); wifiManager.setTimeout(120); //so if it restarts and router is not yet online, it keeps rebooting and retrying to connect

t0 = millis();

}

//============================================== loop //============================================== void loop() { if(millis() - t0 > MY_PING_DELAY) { t0 = millis(); // update time reference if (!loraConfig) { LoRa.setPins(ss, rst, dio0); Serial.println("LoRa Receptor"); Serial.println(LoRa.begin(433E6));

if (!LoRa.begin(433E6)) {
  Serial.println("Starting LoRa failed!");
     while (1);
}
//LoRa.setSyncWord(0xF3);
// register the receive callback
LoRa.onReceive(onReceive);

// put the radio into receive mode
LoRa.receive();
loraConfig = 1;

}

if (newMessage) { // || contador%30 == 0){//Enciende el led para avisar que está recibiendo el mensaje digitalWrite(32, true);

//-----------------------------------------Enviar los datos al servidor --------------------------------------------------------------------------------------
Serial.println("vengo http");
HTTPClient http; //Declare an object of class HTTPClient
if (!LoRa.begin(433E6)) {
  Serial.println("Starting LoRa failed!");
  while (1);
}
// register the receive callback
LoRa.onReceive(onReceive);

// put the radio into receive mode
LoRa.receive();
newMessage = 0;

} delay(10);

} }

void onReceive(int packetSize) {

if(millis() - t0 < MY_PING_DELAY) { // received a packet Serial.println("Received packet "); inString = ""; int i = 0; char packet[packetSize]; char packet_copy[packetSize]; while (LoRa.available()) { byte inChar = LoRa.read(); packet[i++] = (char)inChar; } Serial.println(packet);

const char delim = "|"; char packetHashId = strtok(packet, delim); char receivedTgHash = strtok(NULL, delim); char encryptedPacket = strtok(NULL, delim);

Serial.print("Decryp"); // decryptedPacket.toCharArray(dec, decryptedPacket.length()+1); newMessage = 1; Serial.println("fin de primera recepcion"); t0 = millis(); // update time reference } } String encontrarTexto (String textoBuscado) { // put your main code here, to run repeatedly: int pos1 = inString.indexOf(textoBuscado); String mynewcopystring = inString.substring(pos1 + textoBuscado.length()); pos1 = mynewcopystring.indexOf("&"); mynewcopystring = mynewcopystring.substring(0, pos1); return (mynewcopystring); }

// Error y decodificacion

Guru Meditation Error: Core 1 panic'ed (Interrupt wdt timeout on CPU1).

Core 1 register dump: PC : 0x4008e822 PS : 0x00060235 A0 : 0x8008d4c6 A1 : 0x3ffbf3dc
A2 : 0x3ffb8a00 A3 : 0x3ffb8890 A4 : 0x00000004 A5 : 0x00060223
A6 : 0x00060223 A7 : 0x00000001 A8 : 0x3ffb8890 A9 : 0x00000018
A10 : 0x3ffb8890 A11 : 0x00000018 A12 : 0x3ffc5a4c A13 : 0x00060223
A14 : 0x007bf5d8 A15 : 0x003fffff SAR : 0x0000000a EXCCAUSE: 0x00000006
EXCVADDR: 0x00000000 LBEG : 0x40089939 LEND : 0x40089949 LCOUNT : 0xfffffffb
Core 1 was running in ISR context: EPC1 : 0x400efa8b EPC2 : 0x00000000 EPC3 : 0x00000000 EPC4 : 0x00000000

Backtrace: 0x4008e81f:0x3ffbf3dc |<-CORRUPTED

0x4008e822: vListInsert at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/freertos/list.c line 183 0x40089939: strlen at /builds/idf/crosstool-NG/.build/HOST-i686-w64-mingw32/xtensa-esp32-elf/src/newlib/newlib/libc/machine/xtensa/strlen.S line 84 0x40089949: strlen at /builds/idf/crosstool-NG/.build/HOST-i686-w64-mingw32/xtensa-esp32-elf/src/newlib/newlib/libc/machine/xtensa/strlen.S line 96 0x400efa8b: uart_hal_write_txfifo at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/hal/uart_hal_iram.c line 35

Kongduino commented 1 year ago

Your sketch is again unreadable, please edit the last post and put 3 backticks each before and after. One comment I have though – besides the fact that there are String objects all over the code still – is that your key isn't 16 bytes in length (or 24 or 32, depending on which AES you were thinking of using). That in itself is a problem. Whether it's THE problem, no idea, but you'd better fix that too. Also, the length of the plaintext to encrypt has to be a multiple of 16.

Also, the receiver sketch doesn't need the if (millis() - t0 > MY_PING_DELAY), neither in loop(), nor, especially nor, in void onReceive(int packetSize). In that sketch also, the LoRa init code has no business being in loop(). It should be in setup().

In the sender sketch, you have two String variables json and json2, and two StaticJsonDocument variables, doc and doc2 that are never assigned any value. Why? Considering that you assign json to input, making it an empty string, and that you try to hash and encrypt that...

There is much more but that should get you started. In fact, LoRa might be the only thing that doesn't have a problem in your code. Making this thread quite irrelevant to the subject.

alemori commented 1 year ago

Thank you very much for your comments, I will try to clean up the code to make it readable, and correct the points you indicate. Thanks for your patience and help.

alemori commented 1 year ago

I have to modify the code, and look at the encryption issue, maybe changing the library or method. Also look at the locking issue. For the moment I close the case, and thank you very much for all the information you gave me.