2012-02-06 91 views
5

我尝试将AES-256加密的输出连接到一个字符串(将此字符串与Android手机发送的加密字符串进行比较)。Arduino:连接字符串时崩溃和错误

基本上,concatination似乎可以工作,但是在几次运行错误(非可读字符,字符串变短而不是更长)之后,或发生崩溃之后。它是可重复的,重启后在完全相同的点上崩溃。

我提取了一些演示问题的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库有一个bug,将Arduino IDE更新到1.0。

这已经让我忙了好几天,任何帮助表示高度赞赏,

非常感谢!

+0

字符串有多大? – Anycorn 2012-02-06 23:33:45

+0

它从0开始,增长到32字节(每个for-loop增加2个可见字节) – 2012-02-07 18:07:01

回答

3

由于Arduino只有少量内存,您可能内存不足。

检查你的循环过程中你有多少内存free

罪魁祸首可能是String的实现(请参阅Arduino WString.cpp)正在使用realloc(),并且您的内存可能被严重失去了一个或两个字节的字符串(每个字符串都有16字节的堆头代价)。

您可以通过预先分配一个String reserve()函数预先分配缓冲区来更有效地重写上述内容。或者使用本地C++ char数组重新编写它。

+0

peterept的建议对我的问题起到了很好的作用。我插入行“encrypted.reserve(33);”在变量声明下。我在网上搜索了arduino上的reserve()函数,并找到了一些解释:http://code.google.com/p/arduino/issues/detail?id = 449感谢您的好评 – 2012-02-08 19:52:47