我只想用这 3 种模式从 openSSL 测试 AES:密钥长度为 128,192 和 256,但我的解密文本与我的输入不同,我不知道为什么。此外,当我传递一个巨大的输入长度(比如说 1024 字节)时,我的程序显示core dumped
......我的输入总是相同的,但没关系,至少现在是这样。继承人的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/aes.h>
int main(int argc, char **argv)
{
int i;
int keylength;
printf("Give a key length [only 128 or 192 or 256!]:\n");
scanf("%d", &keylength);
/* generate a key with a given length */
unsigned char aes_key[keylength];
memset(aes_key, 0, sizeof(aes_key));
if (!RAND_bytes(aes_key, keylength))
{
exit(-1);
}
aes_key[keylength-1] = '\0';
int inputslength;
printf("Give an input's length:\n");
scanf("%d", &inputslength);
/* generate input with a given length */
unsigned char aes_input[inputslength+1];
memset(aes_input, '0', sizeof(aes_input));
aes_input[inputslength] = '\0';
/*printf("original:\t");
for(i=0; i<inputslength; i++)
{
printf("%c ", aes_input[i]);
}
printf("\n");*/
/* init vector */
unsigned char iv[AES_BLOCK_SIZE];
if (!RAND_bytes(iv, AES_BLOCK_SIZE))
{
exit(-1);
}
//printf("AES_BLOCK_SIZE = %d\n", AES_BLOCK_SIZE); // aes block size is 16 bytes = 128 bits
AES_KEY enc_key, dec_key;
unsigned char enc_out[AES_BLOCK_SIZE];
unsigned char dec_out[AES_BLOCK_SIZE];
// so i can do with this aes-cbc-128 aes-cbc-192 aes-cbc-256
AES_set_encrypt_key(aes_key, keylength, &enc_key);
AES_cbc_encrypt(aes_input, enc_out, inputslength, &enc_key, iv, AES_ENCRYPT);
AES_set_decrypt_key(aes_key, keylength, &dec_key);
AES_decrypt(enc_out, dec_out, &dec_key);
printf("original:\t");
for(i=0;*(aes_input+i)!=0x00;i++)
printf("%X ",*(aes_input+i));
printf("\nencrypted:\t");
for(i=0;*(enc_out+i)!=0x00;i++)
printf("%X ",*(enc_out+i));
printf("\ndecrypted:\t");
for(i=0;*(dec_out+i)!=0x00;i++)
printf("%X ",*(dec_out+i));
printf("\n");
/*printf("\n\noriginal:\t");
for(i=0; i<inputslength; i++)
{
printf("%x ", dec_out[i]);
}
printf("\n");*/
return 0;
}
编辑:
当我将输出大小更改为inputslength
而不是AES_BLOCK_SIZE
我得到结果时:
Give a key length [only 128 or 192 or 256!]:
128
Give an input's length:
5
original: 30 30 30 30 30
encrypted: 94 56 50 7E 19 B2 1C CE 20 23 4A E7 10 AF DB E3 30 30 30 30 30
decrypted: E1 5F F4 3D E8 8D 91 19 CD 3E 22 1E AF 1C 8F 5A 94 56 50 7E 19 B2 1C CE 20 23 4A E7 10 AF DB E3 30 30 30 30 30
那么是否有可能存在输出大小和 iv 大小的问题?它们应该有什么尺寸(对于 AES-CBC-128、AES-CBC-192、AES-CBC-256)?