如何使用C存储加密文件,以便我可以读取文件并解密它?

时间:2014-04-08 21:08:17

标签: c unix encryption fuse

我正在尝试创建一个FUSE文件系统,在文件进入时对其进行加密,然后在文件出来时对其进行解密。我开始使用一个模板,该模板只调用大多数文件操作的相应系统调用,然后更改read()和write()方法以调用我的加密和解密方法。当我写一个文件(使用echo "readme" > /debug)时,我得到以下输出:

  

加密缓冲区:??????} x?
  写到:/ debug
  本地解密:readme

"本地解密"值只是为了证明解密方法正常工作。接下来,我使用cat /debug尝试读取文件,然后返回废话。以下是我得到的调试语句:

  

刚看完:??????}   来自:/ debug
  解密为:;?N?" Cs?
  所以你应该看到:;?N?" Cs?

在我看来,当我将加密缓冲区写入文件或者当我尝试从文件中读取加密缓冲区时,会发生一些事情。它可能与EOF或每个方法接受的大小参数有关吗?以下是我的FUSE文件中的读写方法:

    static int pv_read(const char *path, char *buf, size_t size, off_t offset,  
                struct fuse_file_info *fi)  
    {  
      int fd;  
      int res;
      (void) fi;
      fd = open(dir_path(path), O_RDONLY);
      if (fd == -1)
            return -errno;
      char *decrypt_buf = (char *) malloc(size);
      char *raw_buf = (char *) malloc(size);
      res = pread(fd, raw_buf, size, offset);

      FILE *f = fopen("debug_read.txt", "w");

      fprintf(f, "Just read: %s\nFrom: %s\n\n", raw_buf, path);
      file_decrypt((byte *)raw_buf, size, (byte *)decrypt_buf);

      fprintf(f, "Decrypted to: %s\n",decrypt_buf);

      memcpy(buf, decrypt_buf, size);

      fprintf(f, "So you should see: %s\n", buf);
      fclose(f);

      if (res == -1)
            res = -errno;
      close(fd);
      return res;
    }
    static int pv_write(const char *path, const char *buf, size_t size,
                 off_t offset, struct fuse_file_info *fi)
    {
      int fd;
      int res;
      (void) fi;
      fd = open(dir_path(path), O_WRONLY);
      if (fd == -1)
            return -errno;
      unsigned char *encrypt_buf = (unsigned char *) malloc(size);
      unsigned char *d_buf = (unsigned char *) malloc(size);
      file_encrypt((byte *)buf, size, (byte *)encrypt_buf);

      file_decrypt((byte *) encrypt_buf, size, (byte *) d_buf);
      FILE *f = fopen("debug_write.txt", "w");

      fprintf(f, "Encrypted Buffer: %s\nBeing written to: %s\nLocally Decrypted to: %s\n",   encrypt_buf, path,d_buf);
      fclose(f);


      res = pwrite(fd, encrypt_buf, size, offset);

      if (res == -1)
          res = -errno;
      close(fd);
      return res;
    }

非常感谢!

0 个答案:

没有答案