【发布时间】:2017-02-08 22:40:31
【问题描述】:
我正在尝试“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;
}
【问题讨论】:
-
仅供参考,您的
iv可能会在加密过程中被更新,或者我应该说,它会被更新。但是你从只读的 const 数据中强制转换了一个非常量指针。当加密器尝试执行该更新时,它不会很好地结束。强制转换很少能修复任何东西,通常情况下,将其用作“修复”会忽略代码中的潜在缺陷。 -
fd以只读方式打开,这就是您正在mmaping 的文件,然后您尝试将memcpy放入您的memblock.. 也许您有论据memcpy的顺序错误?无论如何,不要相信你可以将memcpy变成FILE*,试试fwrite。 -
iv 只是 AES 第一轮使用的初始化向量,并且只使用了一次。我编辑了代码以 fwrite 替换 memcpy 并且仍然出现分段错误,我认为问题来自 mmap 函数参数
-
请添加所有必要的includes,有很多,一般都是这样编译的(例如
ciphertext是什么?)打开警告,通常是-Wall,并修复所有这些,特别是在密码代码中。然后看看你是否还有问题。