1
我用C寫的函數進行加密/解密。我加密一個字符串並將其保存到文件中。後來我閱讀文件並解密內容。在單獨的函數中執行第二個操作時遇到問題。任何人都可以爲此提出解決方案嗎?Openssl函數無法正常工作而不返回0
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <openssl/des.h>
#include <fcntl.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);
}
void test()
{
char key[]="1234";
//
char writeBuffer[4096];
char *decrypted;
// char *encrypted;
//
// encrypted=malloc(sizeof(writeBuffer));
decrypted=malloc(sizeof(writeBuffer));
int fp1 = open("encrypted.txt", O_RDONLY);
int bytes_read = 0;
bytes_read = read(fp1, writeBuffer, sizeof(writeBuffer)-1);
memcpy(decrypted,Decrypt(key,writeBuffer,sizeof(writeBuffer)), sizeof(writeBuffer));
printf("Decrypted text\t : %s \n",decrypted);
}
int main() {
char key[]="1234";
char writeBuffer[4096];
char *decrypted;
char *encrypted;
encrypted=malloc(sizeof(writeBuffer));
decrypted=malloc(sizeof(writeBuffer));
char clear[]="This is a secret message";
printf("Clear text\t : %s \n",clear);
memcpy(encrypted,Encrypt(key,clear,sizeof(writeBuffer)), sizeof(writeBuffer));
printf("Encrypted text\t : %s \n",encrypted);
FILE *f = fopen("encrypted.txt", "w");
fwrite(encrypted, sizeof(writeBuffer), 1, f);
fclose(f);
int i=0;
for(i=0;i < 2; i++){
// Uncommenting the section below and commenting test() works properly
// int fp1 = open("encrypted.txt", O_RDONLY);
// int bytes_read = 0;
// bytes_read = read(fp1, writeBuffer, sizeof(writeBuffer)-1);
//
// memcpy(decrypted,Decrypt(key,writeBuffer,sizeof(writeBuffer)), sizeof(writeBuffer));
// printf("Decrypted text\t : %s \n",decrypted);
test();
}
// close(fp1);
return (0);
}
感謝艾蒂安。我刪除了-1,但問題仍然存在......您在哪種環境下測試?我正在測試OS X. – user340 2014-11-09 08:26:21
我在Debian中測試過,我用我使用的代碼編輯了我的答案,可以測試它嗎? – 2014-11-09 08:36:05
問題的一部分是在'test'中''key'被定義爲'char key [] =「1234」'這是5個字節,在'Decrypt'中''做了'memcpy(key2,key,8) ',這解釋了爲什麼'test'沒有正確解密。 – TonyB 2014-11-10 06:46:08