gpt4 book ai didi

c - 如何使用 mbedtls 以 aes 方式加密字符串?

转载 作者:行者123 更新时间:2023-11-30 16:37:56 24 4
gpt4 key购买 nike

我们都知道mbedtls库是一个非常轻量级的c库。我想使用该库来加密字符串。所以我有一个这样的函数:

aes_加密.h:

#ifndef AES_ENCRYPT_H
#define AES_ENCRYPT_H

#define BOOL int
#define TRUE 1
#define FALSE 0

extern const unsigned char key[16];

BOOL ENC_STR(unsigned char *plain, size_t plain_len,
unsigned char *cipher, size_t *cipher_len);
#endif

以及实现:

const unsigned char KEY[16] = { 0x00, 0x01, 0x02, 0x03,
0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0A, 0x0B,
0x0C, 0x0D, 0x0F, 0xA0 };

BOOL ENC_STR(unsigned char *plain, size_t plain_len, unsigned char *cipher, size_t *cipher_len)
{
BOOL ret = FALSE;

// Prepare the cipher context
const mbedtls_cipher_info_t *cipher_info;
mbedtls_cipher_context_t cipher_ctx;
mbedtls_cipher_init(&cipher_ctx);

if ((cipher_info = mbedtls_cipher_info_from_type(AES_PARM)) == NULL)
{
printf("Cipher Info ERR!\n");
ret = -1;
goto EXIT;
}

if ( (ret = mbedtls_cipher_setup(&cipher_ctx, cipher_info)) != 0)
{
printf("Cipher Setup ERR!\n");
goto EXIT;
}

if ( (ret = mbedtls_cipher_setkey(&cipher_ctx, KEY, cipher_info->key_bitlen, MBEDTLS_ENCRYPT)) != 0)
{
printf("Cipher SetKey ERR!\n");
goto EXIT;
}

// if ( (ret = mbedtls_cipher_set_padding_mode(&cipher_ctx, 1)) != 0) {
// printf("Cipher SetPadding ERR!\n");
// goto EXIT;
// }


if ( (ret = mbedtls_cipher_reset(&cipher_ctx)) != 0)
{
printf("Cipher Reset ERR!\n");
goto EXIT;
}

// encrypt
if ((ret = mbedtls_cipher_update(&cipher_ctx, plain, plain_len, cipher, cipher_len)) != 0) {
printf("Cipher Update ERR!\n");
goto EXIT;
}

EXIT:
if (ret != TRUE) {
char buf[1024] = {0};
mbedtls_strerror(ret, buf, 1024);
printf("Error Msg:\t%s\n", buf);
}

mbedtls_cipher_free(&cipher_ctx);
return ret;
}

我调用该函数如下:

unsigned char *plain = (unsigned char*)"hello world";
size_t plain_len = 12;
unsigned char cipher[128] = {0};
size_t cipher_len = -1;
printf("the encrypt result is:\t%d\n", ENC_STR(plain, plain_len, cipher, &cipher_len));

我收到如下错误消息:

CIPHER - Decryption of block requires a full block

谁能帮我解释一下错误消息的含义吗?谢谢。

最佳答案

您需要通过调用mbedtls_cipher_finish来完成加密。

finish 的原因是需要添加填充,而 update 没有做到这一点。即使源数据具有 N * BlockSize 长度,PKCS7 填充方案(默认使用)也始终会添加一些内容。

https://tls.mbed.org/api/cipher_8h.html#a6678691c02cb3f1322b2179987bfffb2

关于c - 如何使用 mbedtls 以 aes 方式加密字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47689591/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com