C语言 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);
}

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

NJf0oXNZ92NVczkeXEUhkg==
Decrypted: 123456789

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

给定最终块未正确填充。如果在解密过程中使用了错误的密钥,则可能会出现此类问题。

我的代码有什么问题?

几乎所有的在线"AES工具"都非常糟糕,通常是由对密码学知之甚少的人制作的 - 不要依赖它们来测试你的代码。

相反,请针对定义良好的测试向量(如这些向量(测试代码。 我在下面包含了第一个测试用例:

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

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

最新更新