C Libmcrypt无法成功加密/解密

时间:2011-10-18 15:14:01

标签: c encryption mcrypt rijndael

我正在使用c中的libmcrypt并尝试使用rijndael-256作为首选算法来实现加密和解密的简单测试。我已经将这个测试实现与rijndael的手册页示例非常接近,而不是他们选择的算法。使用字符串gcc -o encryption_test main.c -lmcrypt编译时,以下源代码生成类似于的输出: 加密的消息缓冲区包含j A 8 qj %` jh =ZЁ j 原来的字符串是 m“ C D Y G v6 s zh

显然,解密部分失败了,但由于它只是一个函数调用,因此我认为加密方案的行为也不正确。如果你能指出我正确的方向,那么对于libmcrypt大师我有几个问题。

首先,是什么导致此代码产生这个破坏的输出?

其次,当处理密钥大小和块大小等强制性固定大小时,例如256位密钥,函数需要32字节密钥+尾随空字节,31字节密钥+一个尾随的空字节,或32字节的密钥与第33字节无关?同样的问题也适用于块大小。

最后,我注意到的一个示例使用mhash生成要提供给加密调用的密钥文本的哈希值,这当然是可取的,但它被注释掉了,并且mhash中的链接似乎失败了。使用libmcrypt时,处理此类密钥转换的可接受方式是什么?我选择留下任何这样的复杂性,以防止已经破坏的代码进一步复杂化,但我想将其纳入最终设计。以下是有问题的源代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <mcrypt.h>

int main(int argc, char *argv[])
{
MCRYPT mfd;
char *key;
char *plaintext;
char *IV;
unsigned char *message, *buffered_message, *ptr;
int i, blocks, key_size = 32, block_size = 32;

message = "Test Message";

/** Buffer message for encryption */    
blocks              = (int) (strlen(message) / block_size) + 1;
buffered_message    = calloc(1, (blocks * block_size));

key = calloc(1, key_size);
strcpy(key, "&*GHLKPK7G1SD4CF%6HJ0(IV#X6f0(PK");

mfd = mcrypt_module_open(MCRYPT_RIJNDAEL_256, NULL, "cbc", NULL);

if(mfd == MCRYPT_FAILED)
{
    printf("Mcrypt module open failed.\n");
    return 1;
}

/** Generate random IV */
srand(time(0));
IV = malloc(mcrypt_enc_get_iv_size(mfd));
for(i = 0; i < mcrypt_enc_get_iv_size(mfd); i++)
{
    IV[i] = rand();
}

/** Initialize cipher with key and IV */
i = mcrypt_generic_init(mfd, key, key_size, IV);
if(i < 0)
{
    mcrypt_perror(i);
    return 1;
}

strncpy(buffered_message, message, strlen(message));    
mcrypt_generic(mfd, buffered_message, block_size);
printf("The encrypted message buffer contains %s\n", buffered_message);
mdecrypt_generic(mfd, buffered_message, block_size);
printf("The original string was %s\n", buffered_message);
mcrypt_generic_deinit(mfd);
mcrypt_module_close(mfd);
return 0;
}

1 个答案:

答案 0 :(得分:1)

您需要重新初始化描述符mfd以进行解密,不能使用相同的描述符进行加密和解密。

相关问题