我的 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 , key 为 1234567891234567、IV 7654321987654321 和 CBC 128(即使使用没有 IV 的 ECB 128),我只会收到一条错误消息:
Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
我的代码有什么问题吗?
最佳答案
几乎所有在线“AES 工具”的制作都很差劲,通常是由对密码学知之甚少的人制作的 - 不要依赖它们来测试您的代码。
相反,根据明确定义的测试 vector 测试您的代码,like these ones 。我在下面包含了第一个测试用例:
Key : 0x06a9214036b8a15b512e03d534120006
IV : 0x3dafba429d9eb430b422da802c9fac41
Plaintext : "Single block msg"
Ciphertext: 0xe353779c1079aeb82708942dbe77181a
关于c - Arduino AES128加密-解密问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59270547/