【发布时间】:2011-03-28 21:10:03
【问题描述】:
我正在尝试为多个文件获取 sha-1。我目前所做的是循环给定路径中的文件,分别打开和读取每个文件并将内容加载到缓冲区中,然后将其发送到 openssl 的 SHA 函数以获取哈希。代码如下所示:
void ReadHashFile(LPCTSTR name)
{
FILE * pFile;
long lSize;
char * buffer;
size_t result;
pFile = _tfopen ( name , L"rb" );
if (pFile==NULL) {fputs ("File error",stderr); return;}
// obtain file size:
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);
if(lSize == -1){fputs ("Read Error",stderr);return;}
// allocate memory to contain the whole file:
buffer = (char*) malloc (sizeof(char)*lSize);
if (buffer == NULL) {fputs ("Memory error",stderr); return;}
// copy the file into the buffer:
result = fread (buffer,1,lSize,pFile);
if (result != lSize) {fputs ("Reading error",stderr); return;}
/* the whole file is now loaded in the memory buffer. */
// terminate
fclose (pFile);
//Do what ever with buffer
unsigned char ibuf[] = "compute sha1";
unsigned char obuf[20];
SHA1((const unsigned char*)buffer, strlen((const char*)buffer), obuf);
fwprintf(stderr, L"file %s\n", name);
int i;
for (i = 0; i < 20; i++) {
printf("%02x ", obuf[i]);
}
printf("\n");
free(buffer);
}
有些文件似乎无法读取,有些文件大小为 -1,而有些文件的大小我只能读取前 2-3 个字节,这使得许多文件具有相同的 sha,即使它们不同。
如果有人可以帮助我,或者如果有人有文件散列方面的经验,我将不胜感激。哦,有没有办法在不先将整个文件加载到内存中的情况下获取文件的 sha1,我的意思是考虑到大文件,这个解决方案不起作用。
问候
【问题讨论】:
标签: c++ windows file cryptography openssl