我正在尝试“mmap”一个二进制文件,以便使用 AES 对其进行加密,然后使用以下代码将加密数据写入另一个文件(outFile)。我尝试修改 mmap() 和 open() 函数的标志,但在运行可执行文件时总是出现段错误。
int main (void)
{
FILE *outFile; //The output file (encrypted)
/* A 256 bit key */
unsigned char *key = (unsigned char *)"01234567890123456789012345678901";
/* A 128 bit IV */
unsigned char *iv = (unsigned char *)"01234567890123456";
int fd;
struct stat sb;
void * memblock;
fd = open("result0.jpg",O_RDONLY);
outFile=fopen("result0enc.jpg","wb");
fstat(fd, &sb);
printf("Size: %lu\n", sb.st_size);
unsigned char decryptedtext[sb.st_size];
int decryptedtext_len, ciphertext_len;
/* Initialise the library */
ERR_load_crypto_strings();
OpenSSL_add_all_algorithms();
OPENSSL_config(NULL);
memblock = mmap(NULL, sb.st_size,PROT_READ, MAP_SHARED, fd, 0);
if (memblock == MAP_FAILED) {
close(fd);
perror("Error mmapping the file");
exit(EXIT_FAILURE);
}
ciphertext_len = encrypt((unsigned char *)memblock, sb.st_size,key,iv,ciphertext);
fwrite( ciphertext,1, sb.st_size,outFile);
if (munmap(memblock, sb.st_size) == -1) {
perror("Error un-mmapping the file");
/* Decide here whether to close(fd) and exit() or not. Depends... */
}
close(fd);
fclose(outFile);
EVP_cleanup();
ERR_free_strings();
return 0;
}
最佳答案
正如 yano 在评论中提到的,你的错误在这里:
memcpy(outFile, ciphertext, sb.st_size);
您正在尝试 memcpy 到 FILE *
,这是完全错误的。这根本不符合您的预期。您正在覆盖 outFile
指向的 FILE
结构的私有(private)内部结构。
您应该对缓冲区进行操作并使用 fwrite
写入文件。
我建议您在深入研究 mmap
和加密之前,先熟悉使用 f...
函数的基本文件 I/O 操作。
关于c - 将文件映射到内存后出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42125018/