哈希函数在删除和替换文件后返回不同的结果

问题描述 投票:0回答:1

我的问题是,当我运行程序并删除所述目录中的文件时,当它(同一文件)被放回时,它返回一个不同的值。我想知道下面的代码是否是问题?

int main (int argc, char *argv[])
{
        int fd;
        int wd;
        unsigned char c[SHA512_DIGEST_LENGTH];
        int i;
        SHA512_CTX mdContext;
        int bytes;
        unsigned char data[1024];
        const int event_size = sizeof(struct inotify_event);
        const int buf_len = 1024 * (event_size + FILENAME_MAX);
        char *directory = "/home/joe/Documents/";
        char *hashDirectory = "/home/joe/Documents/_Hash/";
        char hashInBuf[500];
        char hashOutBuf[500];
        fd = inotify_init();

        if (fd < 0) {
          perror("inotify_init");
        }

        wd = inotify_add_watch(fd, "/home/joe/Documents", IN_CREATE);

        while (1) {
          char buff[buf_len];
          int no_of_events, count = 0;
          //SEARCH FOR NEW FILES WITHIN DIRECTORY
          no_of_events = read (fd, buff, buf_len);
          while (count < no_of_events) {
            struct inotify_event *event = (struct inotify_event *)&buff[count];
            if (event->len) {
              if ((event->mask & IN_CREATE))
              if(!(event->mask & IN_ISDIR)) {
                    snprintf(hashInBuf, sizeof(hashInBuf), "%s/%s", directory, event->name);
                    snprintf(hashOutBuf, sizeof(hashOutBuf), "%s/%s.txt", hashDirectory, event->name);
                    //OPEN FILES
                    FILE *ftest=fopen(hashInBuf, "rb");    //ORIGINAL FILE
                    FILE *ftest2=fopen(hashOutBuf, "wt");  //HASH FILE (stored in separate directory)
                    //HASH FUNCTION
                    SHA512_Init (&mdContext);
                    while ((bytes = fread (data, 1, 1024, ftest)) != 0)
                        SHA512_Update (&mdContext, data, bytes);
                    SHA512_Final (c,&mdContext);
                    for(i = 0; i < SHA512_DIGEST_LENGTH; i++){
                      fprintf(ftest2, "%02x", c[i]);
                      printf("%02x", c[i]);
                    }
                    fclose (ftest);
                    fclose (ftest2);
                    fflush (stdout);
                  }}
                  count += event_size + event->len;
                 }}
                 return 0;
         } //CLOSES INT MAIN

我可以向你保证,变量是正确定义的,因为它确实有用,但是没有正确...

c loops while-loop openssl sha
1个回答
1
投票

你永远不会设置hashInBuf或hashOutBuf所以内容是未定义的,当你这样做

               FILE *ftest=fopen(hashInBuf, "rb");    //ORIGINAL FILE
               FILE *ftest2=fopen(hashOutBuf, "wt");  //HASH FILE (stored in separate directory)

你试图打开名字从未设置的文件,不幸的是你没有检查打开失败,所以

while ((bytes = fread (data, 1, 1024, ftest)) != 0)

什么都不读,因为ftest值为NULL,所以从不调用SHA512_Update (&mdContext, data, bytes);

从未使用过几个变量:

  • file512
  • hashDirectory
  • 目录
  • WD
  • ARGC
  • ARGV
© www.soinside.com 2019 - 2024. All rights reserved.