提问者:小点点

Arduino AES128加密-解密问题


我的Arduino板上有以下代码:

#include <Crypto.h>
#include <base64.hpp>
#define BLOCK_SIZE 16
uint8_t key[BLOCK_SIZE] = { 1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7 };
uint8_t iv[BLOCK_SIZE] = { 7,6,5,4,3,2,1,9,8,7,6,5,4,3,2,1 };

void bufferSize(char* text, int &length)
{
  int i = strlen(text);
  int buf = round(i / BLOCK_SIZE) * BLOCK_SIZE;
  length = (buf <= i) ? buf + BLOCK_SIZE : length = buf;
}

void encrypt(char* plain_text, char* output, int length)
{
  byte enciphered[length];
  AES aesEncryptor(key, iv, AES::AES_MODE_128, AES::CIPHER_ENCRYPT);
  aesEncryptor.process((uint8_t*)plain_text, enciphered, length);
  int encrypted_size = sizeof(enciphered);
  char encoded[encrypted_size];
  encode_base64(enciphered, encrypted_size, (unsigned char*)encoded);
  strcpy(output, encoded);
}

void decrypt(char* enciphered, char* output, int length)
{
  length = length + 1; //re-adjust
  char decoded[length];
  decode_base64((unsigned char*)enciphered, (unsigned char*)decoded);
  bufferSize(enciphered, length);
  byte deciphered[length];
  AES aesDecryptor(key, iv, AES::AES_MODE_128, AES::CIPHER_DECRYPT);
  aesDecryptor.process((uint8_t*)decoded, deciphered, length);
  strcpy(output, (char*)deciphered);
}

void setup() {
  Serial.begin(115200);
  while (!Serial) {
    ; //wait
  }

}

void loop() {
  char plain_text[] = "123456789";
  unsigned long time = 0;

  time = micros();
  encrypt;
  int length = 0;
  bufferSize(plain_text, length);
  char encrypted[length];
  encrypt(plain_text, encrypted, length);
  Serial.println(encrypted); 
  decrypt;
  length = strlen(encrypted);
  char decrypted[length];
  decrypt(encrypted, decrypted, length);
  Serial.print("Decrypted: ");
  Serial.println(decrypted);
  delay(1000);
}

它可以加密和解密,我在串行下一个输出:

njf 00 xnz 92 nvczkexeuhkg = = < br >解密:123456789

但问题是,如果我使用在线工具进行解密https://www.devglan.com/online-tools/aes-encryption-decryption,键1234567891234567、IV 7654321987654321和CBC 128(即使ECB 128没有IV),我只收到一条错误消息:

给定的最后一个块没有正确填充。如果在解密过程中使用了错误的密钥,就会出现这样的问题。

我的代码有什么问题?


共2个答案

匿名用户

几乎所有的在线“AES工具”都做得很差,通常是由对密码学知之甚少的人制作的——不要依赖它们来测试代码。

相反,用定义良好的测试向量来测试你的代码,就像这些。我在下面包含了第一个测试案例:

Key       : 0x06a9214036b8a15b512e03d534120006
IV        : 0x3dafba429d9eb430b422da802c9fac41
Plaintext : "Single block msg"
Ciphertext: 0xe353779c1079aeb82708942dbe77181a

匿名用户

如果您将密钥指定为1234567891234567,在线工具可能会错误地解释它,它们大多数都希望密钥以十六进制提供,因此您应该尝试将密钥指定为010203040506080901020304050607,这同样适用于IV