1

我正在使用 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�</p>

显然,解密部分失败了,但由于它只是一个函数调用,它让我相信加密方案的行为也不正确。如果你能指出我正确的方向,我有几个问题要问 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;
}
4

1 回答 1

1

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

于 2011-10-18T15:21:50.303 回答