#include <stdio.h> #include <string.h> #include 'aes.h'

#define KEY_SIZE 16 #define INPUT_SIZE 16

int main(void){ unsigned char key[KEY_SIZE+1] = '0123456789abcdef'; // 16字节的密钥 unsigned char input[INPUT_SIZE+1] = 'Hello World!'; // 16字节的输入数据 unsigned char output[INPUT_SIZE+1];

mbedtls_aes_context ctx;
mbedtls_aes_init(&ctx);

// 设置密钥
mbedtls_aes_setkey_enc(&ctx, key, KEY_SIZE *8);

// 加密数据
mbedtls_aes_crypt_ecb(&ctx, MBEDTLS_AES_ENCRYPT, input, output);

printf("AES128 Encrypted: ");
for (int i = 0; i < INPUT_SIZE; i++){
    printf("%02x", output[i]);
}
printf("\n");

// 解密数据
mbedtls_aes_setkey_dec(&ctx, key, KEY_SIZE *8);
mbedtls_aes_crypt_ecb(&ctx, MBEDTLS_AES_DECRYPT, output, output);

output[INPUT_SIZE] = '\0'; // 添加空字符

printf("AES128 Decrypted: %s\n", output);

mbedtls_aes_free(&ctx);

getchar();
return 0;

}

在这段代码中,有一个错误是将unsigned char数组传递给strlen函数,但是strlen函数接受的是const char类型的参数。这是因为unsigned char和const char*之间的隐式转换是不允许的。要解决这个问题,可以使用strlen函数的替代方案,例如使用sizeof来获取数组的长度。

另外,为了在输出之后打印字符串,需要将output数组的末尾添加一个空字符'\0'。

下面是修改后的代码:

#include <stdio.h>
#include <string.h>
#include "aes.h"

#define KEY_SIZE 16
#define INPUT_SIZE 16

int main(void){
    unsigned char key[KEY_SIZE+1] = '0123456789abcdef'; // 16字节的密钥
    unsigned char input[INPUT_SIZE+1] = 'Hello World!'; // 16字节的输入数据
    unsigned char output[INPUT_SIZE+1];

    mbedtls_aes_context ctx;
    mbedtls_aes_init(&ctx);

    // 设置密钥
    mbedtls_aes_setkey_enc(&ctx, key, KEY_SIZE *8);

    // 加密数据
    mbedtls_aes_crypt_ecb(&ctx, MBEDTLS_AES_ENCRYPT, input, output);

    printf("AES128 Encrypted: ");
    for (int i = 0; i < INPUT_SIZE; i++){
        printf("%02x", output[i]);
    }
    printf("\n");

    // 解密数据
    mbedtls_aes_setkey_dec(&ctx, key, KEY_SIZE *8);
    mbedtls_aes_crypt_ecb(&ctx, MBEDTLS_AES_DECRYPT, output, output);

    output[INPUT_SIZE] = '\0'; // 添加空字符

    printf("AES128 Decrypted: %s\n", output);

    mbedtls_aes_free(&ctx);

    getchar();
    return 0;
}
C语言AES加密解密代码错误分析及修正

原文地址: https://www.cveoy.top/t/topic/qENZ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录