Advertisement
EmilySamantha80

MD5 hash generator from files

Dec 8th, 2016
459
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 6.74 KB | None | 0 0
  1. // Title:  MD5 hash generator from files
  2. // Author: Emily Heiner
  3. // Date:   2016-12-08
  4. // This code is licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported license.
  5. // You are free to share and adapt this code for any purposes, commerical and non-commercial,
  6. // as long as appropriate credit is given, you indicate if changes were made, and you share your
  7. // modified code. License details can be found at https://creativecommons.org/licenses/by-sa/3.0/
  8.  
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Text;
  12. using System.IO;
  13.  
  14. namespace ESH.Utility
  15. {
  16.     /// <summary>
  17.     /// Generates MD5 hashes with the ability to save/load the results to/from a file.
  18.     /// </summary>
  19.     public class FileHash
  20.     {
  21.         /// <summary>
  22.         /// FileInfo object containing details of the hashed file
  23.         /// </summary>
  24.         public FileInfo FileDetails { get; set; }
  25.  
  26.         /// <summary>
  27.         /// MD5 Hash of the file
  28.         /// </summary>
  29.         public string MD5Hash { get; set; }
  30.  
  31.         /// <summary>
  32.         /// Computes the MD5 hash of a byte array.
  33.         /// </summary>
  34.         /// <param name="inputBytes">Byte array to hash</param>
  35.         /// <returns>The MD5 hash of the byte array</returns>
  36.         public static string ComputeMD5Hash(byte[] inputBytes)
  37.         {
  38.             System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
  39.             byte[] hash = md5.ComputeHash(inputBytes);
  40.             return BitConverter.ToString(md5.Hash).Replace("-", "");
  41.  
  42.         }
  43.  
  44.         /// <summary>
  45.         /// Computes the hash of a file.
  46.         /// </summary>
  47.         /// <param name="file">Path and filename of the file to hash</param>
  48.         /// <returns>A FileHash object containing the results</returns>
  49.         public static FileHash GetHash(string file)
  50.         {
  51.             var fileHash = new FileHash();
  52.  
  53.             byte[] inputBytes = File.ReadAllBytes(file);
  54.             fileHash.FileDetails = new FileInfo(file);
  55.             fileHash.MD5Hash = ComputeMD5Hash(inputBytes);
  56.  
  57.             return fileHash;
  58.         }
  59.  
  60.         /// <summary>
  61.         /// Computes the hash of multiple files in a directory.
  62.         /// </summary>
  63.         /// <param name="directory">Path of the files to hash</param>
  64.         /// <param name="searchPattern">Search pattern to filter the file list on</param>
  65.         /// <returns>A list of FileHash objects for all matching files</returns>
  66.         public static List<FileHash> GetHashes(string directory, string searchPattern = "*")
  67.         {
  68.             var fileHashes = new List<FileHash>();
  69.  
  70.             foreach (var file in new DirectoryInfo(directory).GetFiles(searchPattern))
  71.             {
  72.                 fileHashes.Add(Hash.FileHash.GetHash(file.FullName));
  73.             }
  74.  
  75.             return fileHashes;
  76.         }
  77.  
  78.         /// <summary>
  79.         /// Recomputes the hashes in a hash list from their respective files.
  80.         /// </summary>
  81.         /// <param name="fileHashes"></param>
  82.         /// <returns>An updated list of FileHash objects</returns>
  83.         public static List<FileHash> RefreshHashes(List<FileHash> fileHashes)
  84.         {
  85.             var newHashes = new List<FileHash>();
  86.  
  87.             foreach (var fileHash in fileHashes)
  88.             {
  89.                 try
  90.                 {
  91.                     newHashes.Add(GetHash(fileHash.FileDetails.FullName));
  92.                 }
  93.                 catch { }
  94.             }
  95.  
  96.             return newHashes;
  97.         }
  98.  
  99.         /// <summary>
  100.         /// Saves a list of hashes to a file.
  101.         /// </summary>
  102.         /// <param name="fileHashes">List of FileHash objects to save</param>
  103.         /// <param name="hashFile">File to save hashes to</param>
  104.         public static void SaveHashes(List<FileHash> fileHashes, string hashFile)
  105.         {
  106.             if (fileHashes == null)
  107.             {
  108.                 throw new ArgumentException("hashList must not be null!");
  109.             }
  110.             if (hashFile == null)
  111.             {
  112.                 throw new ArgumentException("hashFile must not be null");
  113.             }
  114.  
  115.             using (System.IO.FileStream fs = File.Open(hashFile, System.IO.FileMode.Create))
  116.             {
  117.                 using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fs))
  118.                 {
  119.                     foreach (var fileHash in fileHashes)
  120.                     {
  121.                         var line = fileHash.MD5Hash + "  " + fileHash.FileDetails.Name;
  122.                         //Console.WriteLine(line);
  123.                         sw.WriteLine(line);
  124.                     }
  125.                 }
  126.             }
  127.         }
  128.  
  129.         /// <summary>
  130.         /// Loads a list of hashes from a file
  131.         /// </summary>
  132.         /// <param name="hashFile">File to load hashes from</param>
  133.         /// <returns></returns>
  134.         public static List<FileHash> LoadHashes(string hashFile)
  135.         {
  136.             var fileHashes = new List<FileHash>();
  137.             int count = 0;
  138.             using (System.IO.FileStream fs = File.Open(hashFile, System.IO.FileMode.Open))
  139.             {
  140.                 using (System.IO.StreamReader sw = new System.IO.StreamReader(fs))
  141.                 {
  142.                     string line;
  143.                     while((line = sw.ReadLine()) != null)
  144.                     {
  145.                         count++;
  146.  
  147.                         if (String.IsNullOrWhiteSpace(line))
  148.                             continue;
  149.  
  150.                         var split = line.IndexOf("  ");
  151.                         if (split <= 0 || split == line.Length - 2) // Catch lines with no split or no text after the split.
  152.                         {
  153.                             throw new FileFormatException("Malformed hash in line " + count.ToString());
  154.                         }
  155.  
  156.                         //Console.WriteLine("Length: " + line.Length);
  157.                         //Console.WriteLine("Split: " + split);
  158.                         var lineParts = new string[] { line.Substring(0, split), line.Substring(split + 2, (line.Length - split - 2)) };
  159.                            
  160.                         var fileHash = new FileHash();
  161.  
  162.                         try
  163.                         {
  164.                             fileHash.MD5Hash = lineParts[0];
  165.                             fileHash.FileDetails = new FileInfo(Path.Combine(new FileInfo(hashFile).Directory.FullName, lineParts[1]));
  166.                         }
  167.                         catch (Exception ex)
  168.                         {
  169.                             throw new Exception("Malformed has file!", ex);
  170.                         }
  171.  
  172.                         fileHashes.Add(fileHash);
  173.                     }
  174.                 }
  175.             }
  176.  
  177.             return fileHashes;
  178.         }
  179.     }
  180. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement