- using System;
- using System.Collections;
- using System.IO;
- using System.Security.Cryptography;
- namespace HashTest
- {
- public class ED2K
- {
- public ED2K()
- {
- }
- private String ByteArrayToString(byte[] arr)
- {
- String res = "";
- foreach (byte thisb in arr)
- {
- String hex = Convert.ToString(thisb, 16);
- res += hex;
- }
- return res;
- }
- public String ComputeHash(String filename)
- {
- String res = "";
- FileInfo fi = new FileInfo(filename);
- if (fi.Exists)
- {
- MemoryStream ed2k = new MemoryStream();
- using (FileStream stream = new FileStream(filename, FileMode.Open, FileAccess.Read))
- {
- long filesize = stream.Length;
- const int chunk = 9728000;
- double numchunks = (double)filesize / (double)chunk;
- int sizedc = (int)Math.Ceiling(numchunks) + 1;
- if (filesize % chunk == 0) sizedc--;
- for (int i = 1; i <= sizedc; i++)
- {
- int readsize;
- if (i == sizedc)
- readsize = (int)filesize % chunk;
- else
- readsize = chunk;
- byte[] tempbuffer = new byte[readsize];
- stream.Read(tempbuffer, 0, readsize);
- HashAlgorithm md4temp = MD4.Create();
- byte[] singledigest = md4temp.ComputeHash(tempbuffer);
- ed2k.Write(singledigest, 0, 16);
- String hashstr = ByteArrayToString(singledigest);
- Console.WriteLine(String.Format("Chunk[{0}]: " + hashstr, i));
- }
- stream.Close();
- }
- ed2k.Seek(0, SeekOrigin.Begin);
- HashAlgorithm hash = MD4.Create();
- byte[] digest = hash.ComputeHash(ed2k);
- res = ByteArrayToString(digest);
- Console.WriteLine("ED2K Hash: " + res);
- }
- return res;
- }
- }
- }