我尝试将 AES-256 加密的输出连接到一个字符串(将此字符串与从 Android 手机发送的加密字符串进行比较)。
基本上,连接似乎有效,但在几次运行后会出现错误(不可读的字符、字符串变得更短而不是更长)或崩溃。它是可重现的,重启后在同一点崩溃。
我提取了几行 Arduino 代码来演示该问题。它执行以下操作:
- 创建一个随机数并将其写入数组(有效)
- AES-对该数组进行编码(有效)
- 构建每个数组索引的十六进制表示(有效)
- 将索引连接到字符串(崩溃)
#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。
这让我忙了好几天,非常感谢任何帮助,
多谢!