Mega Code Archive

 
Categories / Delphi / Algorithm Math
 

Ed2k hash

Title: ed2k hash Question: how calculate ed2k hash (for eMule, edonkey,...)? ie: 965c013e991ee246d63d45ea71954c4d ed2k://|file|The_Two_Towers-The_Purist_Edit-Trailer.avi|14997504|965c013e991ee246d63d45ea71954c4d|/ Answer: http://en.wikipedia.org/wiki/Ed2k_link The ed2k hash function is based on MD4 but differs for files in excess of approximately 9.5 MB. The file is divided into 9.28Mb (the exact value is 9,728,000 byte) chunks and the hash is calculated for each one. The resulting hash table is hashed once again, and the final value is used as a part of the ed2k link. code: // require delphi component DCPcrypt v2 Beta 3 - http://www.cityinthesky.co.uk/files/dcpcrypt2.zip uses ..., DCPmd4; Function GetEd2kHash(FN:string):string; const chunks=9728000; var Hash: TDCP_md4; Digest: array[0..15] of byte; //16 bajtni hash Source: TFileStream; ed2k:TMemoryStream; sizedc,i,k: integer; s: string; begin Result:=''; Source:= nil; try Source:= TFileStream.Create(FN,fmOpenRead); except MessageDlg('Unable to open file',mtError,[mbOK],0); end; if Source nil then begin Hash:= TDCP_md4.Create(NIL); // create the hash ed2k :=TMemoryStream.Create; sizedc:=(Source.Size div chunks)+1; if Source.Size mod chunks =0 then dec(sizedc); for i:=1 to sizedc do begin Hash.Init; // initialize it if i=sizedc then Hash.UpdateStream(Source,(Source.Size mod chunks)) else Hash.UpdateStream(Source,chunks); // hash the stream contents Hash.Final(Digest); for k:=0 to 15 do begin ed2k.WriteBuffer(Digest[k],1); end; //possible usage ProgressBar1.Position:=100*i div sizedc; end; ed2k.Seek(0,soFromBeginning); Hash.Init; Hash.UpdateStream(ed2k, ed2k.Size); // hash the stream contents Hash.Final(Digest); ed2k.Free; Hash.Free; s:= ''; for i:= 0 to 15 do s:= s +IntToHex(Digest[i],2); Result:=s; end; Source.Free; end;