我尝试将AES-256加密的输出连接到一个字符串(将此字符串与Android手机发送的加密字符串进行比较)。Arduino:连接字符串时崩溃和错误
基本上,concatination似乎可以工作,但是在几次运行错误(非可读字符,字符串变短而不是更长)之后,或发生崩溃之后。它是可重复的,重启后在完全相同的点上崩溃。
我提取了一些演示问题的Arduino代码行。它执行以下操作:
- 创建一个随机数,并将其写入到一个数组(作品)
- AES-编码此阵列(作品)
- 构建每个数组索引的HEX表示(作品)
- 串联的索引为一个字符串(崩溃)
#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。
这已经让我忙了好几天,任何帮助表示高度赞赏,
非常感谢!
字符串有多大? – Anycorn 2012-02-06 23:33:45
它从0开始,增长到32字节(每个for-loop增加2个可见字节) – 2012-02-07 18:07:01