【发布时间】:2014-05-28 08:48:49
【问题描述】:
我正在使用以下代码在 windows 中使用 openssl 加密和解密二进制数据。如您所见,在这两个函数中,我都知道纯文本的大小。有什么方法可以在不知道纯文本大小的情况下解密消息?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/des.h>
char * Encrypt(char *Key, char *Msg, int size)
{
static char* Res;
int n = 0;
DES_cblock Key2;
DES_key_schedule schedule;
Res = (char *)malloc(size);
/* Prepare the key for use with DES_cfb64_encrypt */
memcpy(Key2, Key, 8);
DES_set_odd_parity(&Key2);
DES_set_key_checked(&Key2, &schedule);
/* Encryption occurs here */
DES_cfb64_encrypt((unsigned char *)Msg, (unsigned char *)Res,size, &schedule, &Key2, &n, DES_ENCRYPT);
return (Res);
}
char * Decrypt(char *Key, char *Msg, int size)
{
static char* Res;
int n = 0;
DES_cblock Key2;
DES_key_schedule schedule;
Res = (char *)malloc(size);
/* Prepare the key for use with DES_cfb64_encrypt */
memcpy(Key2, Key, 8);
DES_set_odd_parity(&Key2);
DES_set_key_checked(&Key2, &schedule);
/* Decryption occurs here */
DES_cfb64_encrypt((unsigned char *)Msg, (unsigned char *)Res,size, &schedule, &Key2, &n, DES_DECRYPT);
return (Res);
}
int _tmain(int argc, _TCHAR* argv[])
{
char key[] = "password";
char clear[] = "This is a secret message";
char *decrypted;
char *encrypted;
encrypted = (char *)malloc(sizeof(clear));
decrypted = (char *)malloc(sizeof(clear));
printf("Clear text\t : %s : sizeof: %i\n", clear, strlen (clear));
memcpy(encrypted, Encrypt(key, clear, sizeof(clear)), sizeof(clear));
printf("Encrypted text\t : %s sizeof: %i\n", encrypted, strlen(encrypted));
memcpy(decrypted, Decrypt(key, encrypted, sizeof(clear)), sizeof(clear));
printf("Decrypted text\t : %s sizeof: %i\n", decrypted, strlen(decrypted));
return 0;
}
【问题讨论】:
-
为什么要问是否可以轻松尝试?
-
我认为 mjan635 要求知道要分配多少内存。答案是您通常以小于总大小的“块”进行加密和解密。在这种情况下,每次你解密一个块时,你都会将它附加到你的缓冲区中。如果您没有空间,您将
realloc缓冲区以使其更大。你会这样做,直到你没有更多的数据可供阅读。您仍然必须以某种方式知道加密数据流的长度,或者有一个标记(如果您从文件中读取它,则像 EOF)告诉您要读取多少数据。
标签: c encryption openssl encryption-symmetric