CSharp examples for System.Security.Cryptography:MD5
Computes the MD5 hash of a file using the data array
using System.Net; using System.Security.Cryptography; using System.Text; using System.IO;/*from w w w . j a v a 2 s . c o m*/ using System.Configuration; using System.Data; using System; public class Main{ /// <summary> /// Computes the MD5 hash of a file using the data array /// </summary> /// <param name="data">the array of data</param> /// <returns>the string form of the calculated MD5 hash</returns> public static string ComputeMD5(byte[] data) { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); StringBuilder buff = new StringBuilder(); try { byte[] md5Hash = md5.ComputeHash(data); foreach (byte hashByte in md5Hash) { buff.Append(String.Format("{0:X1}", hashByte)); } return buff.ToString(); } catch (Exception ex) { throw new Exception("Exception thrown computing MD5 hash using the data array", ex); } } /// <summary> /// Computes the MD5 hash of a file using the file path /// </summary> /// <param name="filePath">the physical path of the file on the ESS</param> /// <returns>the string form of the calculated MD5 hash</returns> public static string ComputeMD5(string filePath) { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); StringBuilder buff = new StringBuilder(); FileStream fs = null; try { fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); byte[] md5Hash = md5.ComputeHash(fs); foreach (byte hashByte in md5Hash) { buff.Append(String.Format("{0:X1}", hashByte)); } return buff.ToString(); } catch (Exception ex) { throw new Exception("Exception thrown computing MD5 hash using the file path", ex); } finally { fs.Close(); } } }