0
#include <mhash.h>
#include <stdio.h>
#include <stdlib.h>

int main(void)
 {
        int i;
        MHASH td;
        unsigned char buffer;
        unsigned char *hash;

        td = mhash_init(MHASH_WHIRLPOOL);

        if (td == MHASH_FAILED) exit(1);

        while (fread(&buffer, 1, 1, stdin) == 1) {
             mhash(td, &buffer, 1);
        }

        hash = mhash_end(td);

        for (i = 0; i < mhash_get_block_size(MHASH_WHIRLPOOL); i++) {
            printf("%.2x", hash[i]);
        }
        printf("\n");

        exit(0);
 }

嗨,我有来自 mhash 示例页面的上述代码。我需要更改它,所以它将继续从 读取stdin,并逐行计算哈希,而不是等待EOF

cat textfile | whirlpool_line_hash

我的理解是,我保留 while 循环(等待EOF)并在收到 10(0x0a)后进行哈希计算和打印。打印 mhash 后需要重新设置,对吗?我根本不喜欢C,但我需要一个快速的程序,所以我想用C来做。我已经无法将指针与整数进行比较;-)有人可以帮忙吗?

4

2 回答 2

1

搞定了;-)

#include <mhash.h> //mhash
#include <stdio.h>
#include <stdlib.h> //exit
#include <unistd.h> //getopt


int main(void)
 {

        int i;
        MHASH td;
        unsigned char buffer;
        unsigned char *hash;

        td = mhash_init(MHASH_WHIRLPOOL);

        if (td == MHASH_FAILED) exit(1);

        while (fread(&buffer, 1, 1, stdin) == 1) { // read from stdin until receive EOF

        if ( buffer != '\n' ) { mhash(td, &buffer, 1); } //dont calculate line break
        if ( buffer == '\n' ) {  //received line break
        hash = mhash_end(td);

        for (i = 0; i < mhash_get_block_size(MHASH_WHIRLPOOL); i++) { printf("%.2x", hash[i]); }
        printf("\n");
        td = mhash_init(MHASH_WHIRLPOOL);

}
}
        exit(0);
 }
于 2016-05-09T10:25:24.423 回答
1

它可以工作,除了一个小警告,hash返回的缓冲区mhash_end是一个动态分配的缓冲区,所以free当你完成使用它时它会更好:

free(hash);

您可以使用fgetswhich 最多读取一行。就性能而言,每次读取并输入哈希一个字符可能不是最好的做法,相反,您可以读取整行并将块输入哈希函数进行更新。试试这个:

char line[4096];
int len;
while (fgets(line, sizeof line, stdin) != NULL) { // read a line each time
    len = strlen(line);
    char *p = strrchr(line, '\n');
    if (p != NULL)
        mhash(td, line, len - 1);  // strip the new line
    else
        mhash(td, line, len);
}

hash = mhash_end(td);
for (i = 0; i < mhash_get_block_size(MHASH_WHIRLPOOL); i++) {
    printf("%.2x", hash[i]);
}
free(hash);
于 2016-05-09T10:30:59.087 回答