在c中以ecb模式用mcrypt加密

时间:2012-10-23 14:41:37

标签: c encryption arrays

我正在尝试使用c中的libmcrypt加密长char数组。我将加密功能调用超过5次后出现问题。我看不出错误,但我得到了奇怪的输出。如果我有64个字符的明文加密前32个字符,那么对于最后32个字符我得到两个相同的16个字符。我希望你得到我所看到的。这是我的代码:

char *Encrypt( char *key, char *message, int buff_len){

    unsigned char *Res;
    MCRYPT mfd; 
    char *IV;
    int i, blocks, key_size=16, block_size;




    mfd = mcrypt_module_open(MCRYPT_RIJNDAEL_128, NULL, "ecb", NULL);
    block_size = mcrypt_enc_get_block_size(mfd);
    blocks = ceil((double)buff_len/block_size);

    mcrypt_generic_init(mfd, key, key_size, IV);
    Res = calloc(1, (blocks *block_size)+1);

    strncpy(Res, message, buff_len);
    //memset(message,'\0',blocks *block_size);
    mcrypt_generic(mfd,Res,(blocks *block_size));
    //printf("the encrypted in function(Encrypt) %s len %d\n",Res, strlen(Res));



    mcrypt_generic_deinit(mfd);
    mcrypt_module_close(mfd);

     return (Res);

}

主要是我打电话:

    char seed[] = "thesecretmessage which I really want to check if if works", key1[]="abcdefghijklmnop";
int buff_len = strlen(seed), i;

char *encrypted = Encrypt(key1, seed, buff_len), *encrypted_pr=Encrypt(key1, encrypted, buff_len);
printf("the encrypted %s, %d\n", encrypted, strlen(encrypted));
printf("the encrypted_pr %s, %d\n", encrypted_pr, strlen(encrypted_pr));
for(i=0;i<15;i++){
    memcpy(encrypted2, Encrypt(key1, encrypted2, buff_len),64);
    printf("the encrypted_pr[%d] %s\n",i, encrypted_pr);
}

我真的对此感到疯狂。如果我有一个只有16字节的明文,那就完美了。谢谢你的帮助!

0 个答案:

没有答案