使用 C 中的 openssl 库进行简单的 AES 加密解密 [英] Simple AES encryption decryption with openssl library in C
问题描述
我想加密一个包含少量字符串的结构然后解密它.我尝试了以下代码.原始代码是从网上找到的,它运行良好.我将它的输入更改为结构.以下是代码.
I want to encrypt a struct containing few String and then decrypt it. I tried following code. The original code is found from the web and it was working perfectly. I change the input of it to a struct. following is the code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <openssl/aes.h>
#include <openssl/rand.h>
typedef struct ticket { /* test field */
int ticketId;
char username[20];
char date[20];
} USR_TICKET;
// a simple hex-print routine. could be modified to print 16 bytes-per-line
static void hex_print(const void* pv, size_t len)
{
const unsigned char * p = (const unsigned char*)pv;
if (NULL == pv)
printf("NULL");
else
{
size_t i = 0;
for (; i<len;++i)
printf("%02X ", *p++);
}
printf("
");
}
// main entrypoint
int main(int argc, char **argv)
{
int keylength;
printf("Give a key length [only 128 or 192 or 256!]:
");
scanf("%d", &keylength);
/* generate a key with a given length */
unsigned char aes_key[keylength/8];
memset(aes_key, 0, keylength/8);
if (!RAND_bytes(aes_key, keylength/8))
exit(-1);
/* input struct creation */
size_t inputslength = sizeof(USR_TICKET);
USR_TICKET ticket;
ticket.ticketId = 1;
time_t now = time(NULL);
strftime(ticket.date, 20, "%Y-%m-%d", localtime(&now));
strcpy(ticket.username, "ravinda");
printf("Username - %s
", ticket.username);
printf("Ticket Id - %d
", ticket.ticketId);
printf("Date - %s
", ticket.date);
/* init vector */
unsigned char iv_enc[AES_BLOCK_SIZE], iv_dec[AES_BLOCK_SIZE];
RAND_bytes(iv_enc, AES_BLOCK_SIZE);
memcpy(iv_dec, iv_enc, AES_BLOCK_SIZE);
// buffers for encryption and decryption
const size_t encslength = ((inputslength + AES_BLOCK_SIZE) / AES_BLOCK_SIZE) * AES_BLOCK_SIZE;
unsigned char enc_out[encslength];
unsigned char dec_out[inputslength];
memset(enc_out, 0, sizeof(enc_out));
memset(dec_out, 0, sizeof(dec_out));
// so i can do with this aes-cbc-128 aes-cbc-192 aes-cbc-256
AES_KEY enc_key, dec_key;
AES_set_encrypt_key(aes_key, keylength, &enc_key);
AES_cbc_encrypt((unsigned char *)&ticket, enc_out, inputslength, &enc_key, iv_enc, AES_ENCRYPT);
AES_set_decrypt_key(aes_key, keylength, &dec_key);
AES_cbc_encrypt(enc_out, dec_out, encslength, &dec_key, iv_dec, AES_DECRYPT);
printf("original: ");
hex_print((unsigned char *)&ticket, inputslength);
printf("encrypt: ");
hex_print(enc_out, sizeof(enc_out));
printf("decrypt: ");
hex_print(dec_out, sizeof(dec_out));
USR_TICKET * dyc = (USR_TICKET *)dec_out;
printf("Username - %s
", dyc->username);
printf("Ticket Id - %d
", dyc->ticketId);
printf("Date - %s
", dyc->date);
return 0;
}
问题只是结构的前两个成员正确解密.之后数据被破坏.我在这里做错了什么?
The problem is only first two members of the struct is decrypting correctly. After that data get currupted. What am I doing wrong here?
推荐答案
我几乎会说这是 OpenSSL 的问题.似乎当传递给 AES_cbc_encrypt
的 length
参数是 > AES_BLOCK_SIZE
但不是其整数倍(即 length mod AES_BLOCK_SIZE !=0
),然后使用 initial IV 加密最后一个块,而不是像 CBC 模式那样使用前一个密文块.
I would almost go so far as to say this is a problem with OpenSSL. It seems that when the length
parameter passed to AES_cbc_encrypt
is > AES_BLOCK_SIZE
but not an integral multiple thereof (i.e. length mod AES_BLOCK_SIZE != 0
), then the last block is encrypted using the initial IV and not the previous block of ciphertext as should be the case for CBC mode.
您可以通过以下两种方式之一解决此问题:
You can fix this in one of two ways:
将您的结构复制到一个大小为 AES_BLOCK_SIZE
整数倍的缓冲区,或分两部分加密 - 完整块,然后是单个部分块.后者的优点是可以避免额外的内存使用,可以这样做:
Copy your struct to a buffer whose size is an integral multiple of AES_BLOCK_SIZE
, or encrypt in two parts - the full blocks, followed by a single partial block. The latter has the advantage of avoiding additional memory usage and can be done as follows:
size_t fullBlocks = inputslength - (inputslength % AES_BLOCK_SIZE);
size_t remainingBlock = inputslength - fullBlocks;
AES_cbc_encrypt((unsigned char *)&ticket, enc_out, fullBlocks, &enc_key, iv_enc, AES_ENCRYPT);
AES_cbc_encrypt((unsigned char *)&ticket + fullBlocks, enc_out + fullBlocks, remainingBlock, &enc_key, iv_enc, AES_ENCRYPT);
然后您应该能够像目前一样解密,没有问题.然而值得注意的是,您应该将 dec_out
声明为与 enc_out
相同的大小,因为您当前在解密时超出了 dec_out
缓冲区.
You should then be able to decrypt as you currently are without issue. It's worth noting however that you should declare dec_out
as the same size as enc_out
, because you're currently overrunning the dec_out
buffer when decrypting.
我将此作为 OpenSSL 中的错误提出:https://rt.openssl.org/Ticket/Display.html?id=3182&user=guest&pass=guest 虽然对于这实际上是一个错误还是只是(未记录的)未定义行为存在一些争论,但普遍的共识是应该使用 EVP
例程,而不是这些低级函数.
I raised this as a bug in OpenSSL: https://rt.openssl.org/Ticket/Display.html?id=3182&user=guest&pass=guest and whilst there is some argument over whether this is actually a bug, or just (undocumented) undefined behavior, the general consensus is that the EVP
routines should be used instead, rather than these low-level functions.
这篇关于使用 C 中的 openssl 库进行简单的 AES 加密解密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!