我正在尝试使用SubDB API但是我在计算文件的哈希时遇到了问题。哈希是通过获取视频文件的第一个和最后一个64kb组成的,将所有数据放在一起并生成md5的结果数据(128kb)。以python编写的以下函数实现了哈希算法:
def get_hash(name):
readsize = 64 * 1024
with open(name, 'rb') as f:
size = os.path.getsize(name)
data = f.read(readsize)
f.seek(-readsize, os.SEEK_END)
data += f.read(readsize)
return hashlib.md5(data).hexdigest()
我正在使用C ++ Builder XE2,我尝试将其翻译如下:
String __fastcall MD5Hash(const AnsiString filename)
{
String result;
char firstbits[60*1024], lastbits[60*1024];
char bits[120*1024];
FILE* f = fopen(filename.c_str(), "rb");
if(f ==NULL) {ShowMessage("Error!"); return "";}
TIdHashMessageDigest5 *idmd5= new TIdHashMessageDigest5();
try {
fread(firstbits, 60*1024, 1, f);
fseek(f, -(long)60*1024, SEEK_END);
fread(lastbits, 60*1024, 1, f);
strcpy(bits, firstbits);
strcpy(bits, lastbits);
result= idmd5->HashBytesAsHex(RawToBytes(bits, 120*1024));
}
__finally {
delete idmd5;
}
fclose(f);
return result;
}
测试文件是这样的:http://thesubdb.com/api/samples/dexter.mp4,它的哈希值(来自上面的算法)应该是ffd8d4aa68033dc03d1c8ef373b9028c。但是,我无法做对......
Delphi解决方案也可以。
答案 0 :(得分:4)
尝试以下代码怎么样?我只是改变了尺寸,做了适当的踩踏,并删除了strcpy。
String __fastcall MD5Hash(const AnsiString filename)
{
String result;
char bits[128*1024];
FILE* f = fopen(filename.c_str(), "rb");
if(f ==NULL) {ShowMessage("Error!"); return "";}
TIdHashMessageDigest5 *idmd5= new TIdHashMessageDigest5();
try {
fread(bits, 64*1024, 1, f);
fseek(f, -(long)64*1024, SEEK_END);
fread(&bits[64*1024], 64*1024, 1, f);
result= idmd5->HashBytesAsHex(RawToBytes(bits, 128*1024));
}
__finally {
delete idmd5;
}
fclose(f);
return result;
}