2012-02-06 9 views
5

AES-256暗号化の出力を文字列に連結しようとしました(この文字列をAndroid電話から送信された暗号化された文字列と比較しようとしています)。Arduino:文字列を連結するときのクラッシュとエラー

基本的に、連結は機能しているようですが、いくつかの実行エラー(読み取り不可能な文字列、長い文字列ではなく短い文字列)またはクラッシュが発生しました。再現性があり、再起動後も全く同じポイントでクラッシュします。

問題を示すいくつかのArduinoコードを抽出しました。これは、次のん:

  1. (作品)
  2. AES-は、この配列をコード化する乱数を作成し、配列に書き込む(作品)
  3. は、各配列インデックス(作品)のHEX表現を構築
  4. を連結文字列へのインデックス(クラッシュ)

#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 
} 

フォーラムを検索し、(+演算子、strcat)を連結する別の方法を試みました。すべてが同様の効果を示した。 Stringライブラリにバグがあり、Arduino IDEを1.0にアップデートしました。

これは、任意のヘルプは高く評価され、日のために忙しい

おかげで多くのことを私を維持しています!

+0

文字列はどれくらい大きいですか? – Anycorn

+0

0から始まり32バイトになります(各ループは2個の可視バイトを追加します) –

答えて

3

Arduinoのメモリが不足している可能性があります。

ループ中にメモリがどれくらいあるか確認してください。free

原因は、Stringの実装(Arduino WString.cppを参照)がrealloc()を使用している可能性があります。メモリがおそらく1つまたは2つのバイト文字列(それぞれが16バイトのヒープヘッダコストを持っています)

バッファを事前に割り当てるためにString reserve()関数を事前に割り当てることで、上記をより効率的に書き直すことができます。または、ネイティブのC++ char配列を使用して書き直します。

+0

petereptからの提案は私の問題に完璧に機能しました。私は、 "encrypted.reserve(33);という行を挿入しました。変数宣言の下でarduinoのreserve()関数をインターネットで検索し、その説明を見つけました:http://code.google.com/p/arduino/issues/detail?id=449 –