如何使用c解密内存中的大文件

时间:2014-04-17 06:21:14

标签: c encryption cryptography

基于C的应用程序使用密钥大小为256的aes。数据以二进制形式提供,它是加密的并且写在二进制文件中。要求是在RAM中解密这个二进制文件(即动态/实时加密)。问题是如何以高效的方式实现即时加密?需要任何良好的Web链接或代码参考来理解即时加密。

更简单的方法是如何使用c(Linux)解密内存中的大文件?就像在truecrypt中一样。请指导。 问候

1 个答案:

答案 0 :(得分:0)

在文件上使用mmap;然后将该文件作为内存中的数据流打开。例如,一个简单的内存更改函数,它对大型(例如,400Gb)文件中的文件中的每个字节进行异或运行:

// The encryption function
void xor_ram  (unsigned char *buffer, long len) {
     while (len--) *buffer ^= *buffer++;
}

// The file we want to encrypt
int fd = open ("/path/to/file", O_RDWR);

// Figure out the file length
FILE *tmpf = fdopen (fd, "r");
fseek (tmpf, 0, SEEK_END);
long length = ftell (tmpf);

// Memory map the file using the fd
unsigned char *mapped_file = mmap (NULL, length, 
                                   PROT_READ | PROT_WRITE, MAP_PRIVATE,
                                   fd, 0); 
// Call the encryption function
xor_ram (mapped_file, length);

// All done now
munmap (mapped_file, length);
close (fd);

您可以在此处阅读mmap的联机帮助页:http://unixhelp.ed.ac.uk/CGI/man-cgi?mmap 虽然你真的应该在你的特定平台上找到mmap的文档(man mmap,如果你是某种类型的unix系统,或者如果没有那么搜索平台库)。