Arduino: crashing and string concatenation errors

I am trying to combine AES-256 encryption output into a string (to compare this string with the encrypted string sent from the Android phone).

Basically, concatenation seems to work, but after several startup errors (unreadable characters, the string gets shorter, not longer), or crashes occur. It is reproducible, crashing at the same point after a restart.

I extracted some lines of Arduino code that demonstrate the problem. It performs the following actions:

  • Create a random number and write it to an array (works)
  • AES-encode this array (works)
  • Build a HEX representation of each array index (works)
  • Merge indexes with string (crash)

#include <SPI.h>
#include "aes256.h"  //include this lib

uint8_t key[] = {9,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8,
                 1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8 }; //the encryption key

aes256_context ctxt; //context needed for aes library


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


void loop() {

  uint8_t data[] = {
       0x53, 0x73, 0x64, 0x66, 0x61, 0x73, 0x64, 0x66,
       0x61, 0x73, 0x64, 0x66, 0x61, 0x73, 0x64, 0x65, }; //the message to be encoded  

  long InitialRandom = random(2147483647); //0 to highest possible long
  String RandomString = "" ; 
  RandomString+=InitialRandom; //random number to String            
  Serial.println(RandomString); //for debugging

  //update data array: Random String into data array                 
  for (int x=0; x<RandomString.length(); x++){
       data[x] = RandomString[x];
  }

  //this encrypts data array, which changes  
  aes256_init(&ctxt, key); //initialize the lib
  aes256_encrypt_ecb(&ctxt, data); //do the encryption     
  aes256_done(&ctxt);  

  //Here the problem starts.............................................
  String encrypted=""; //the string I need finally 

  for (int x=0; x<sizeof(data); x++){ //data array is 16 in size    
        int a = data[x]; 
        String b = String (a, HEX);
        if(b.length()==1) b="0"+b;  //if result is e.g "a" it should be "0a"                         
        encrypted.concat(b);  //this line causes the problem!!! 
        //Serial.println(b); //works perfect if above line commented out    
        Serial.println(encrypted); //see the string geting longer until problems occur      
  }
  //Here the problem ends.............................................

        Serial.println(); //go for next round, until crashing
}

, (+ operator, strcat). . , String , IDE Arduino 1.0.

, ,

!

+5
1

, , Arduino .

, .

, String (. Arduino WString.cpp) realloc(), , , ( 16 ).

, String reserve() . ++ char .

+3

All Articles