BlowFish加密:无法解密密码到原始明文

时间:2014-10-27 04:52:27

标签: c encryption cryptography openssl blowfish

我使用OpenSSL BlowFish并遇到一些非常奇怪的事情。我的职能如下:

char* BFEncrypt(char* key, char* text)
{
     char ivec[EVP_MAX_IV_LENGTH] = {0};
     int len = strlen(text);
     char *cipher = (char*)malloc(sizeof(char)*(len+1));
     int *num = (int*)malloc(sizeof(int));
     *num = 0;
     BF_KEY *bfkey = (BF_KEY*)malloc(sizeof(BF_KEY));
     BF_set_key(bfkey, strlen(key), key);
     BF_cfb64_encrypt(text, cipher, len, bfkey, ivec, num, BF_ENCRYPT);
     cipher[len] = '\0';
     free(num);
     free(bfkey);
     return cipher; 
}

char* BFDecrypt(char* key, char* cipher)
{
     char ivec[EVP_MAX_IV_LENGTH] = {0};
     int len = strlen(cipher);
     char *text = (char*)malloc(sizeof(char)*(len+1));
     int *num = (int*)malloc(sizeof(int));
     *num = 0;
     BF_KEY *bfkey = (BF_KEY*)malloc(sizeof(BF_KEY));
     BF_set_key(bfkey, strlen(key), key);
     BF_cfb64_encrypt(cipher, text, len, bfkey, ivec, num, BF_DECRYPT);
     text[len] = '\0';
     free(num);
     free(bfkey);
     return text; 
}

如果我在函数中做了如下的事情,我可以从解密中获得正确的明文:

char *plainText1;
char *key1;
//initialize those pointers
char *cipher1 = BFEncrypt(key1, plainText1);
char *temp = BFDecrypt(key1, cipher1); //here I test that temp is equal to plainText1

但是,在不同的函数中,如果我只调用BFDecrypt,我将无法在之前获得相同的明文:

//somehow I stored the cipher1 above in my disk and read it 
char *cipher2; //store cipher1
char *key2;// key2 is equal to key1
char *plaintext2 = BFDecrypct(key2, cipher2); //Here is the problem!!!!! plaintext2 is not equal to plaintext1 

令人困惑的部分是,即使key2和cipher2与key1和cipher1完全相同,plaintext2也与plaintext1完全不同。任何人都可以给我一个提示,我坚持了很久。

提前致谢!

0 个答案:

没有答案