|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CryptHelper.cs" company="Catel development team">
// Copyright (c) 2008 - 2011 Catel development team. All rights reserved.
// </copyright>
// <summary>
// Cryptography class which handles most encryptions easily.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace Catel.Security.Cryptography
{
/// <summary>
/// Cryptography class which handles most encryptions easily.
/// </summary>
public static class CryptHelper
{
#region Methods
/// <summary>
/// Calculates the MD5 hash of a file.
/// </summary>
/// <param name="fileName">Path of the file to hash.</param>
/// <returns>Hash of the file.</returns>
public static string CalculateMD5FileHash(string fileName)
{
string result;
string hashData;
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
try
{
using (FileStream fileStream = GetFileStream(fileName))
{
byte[] arrbytHashValue = md5Hasher.ComputeHash(fileStream);
hashData = BitConverter.ToString(arrbytHashValue);
hashData = hashData.Replace("-", string.Empty);
result = hashData;
}
}
catch (Exception)
{
return string.Empty;
}
return result;
}
/// <summary>
/// Calculates the MD5 hash of content.
/// </summary>
/// <param name="content">Content to hash.</param>
/// <returns>Hash of the content.</returns>
public static string CalculateMD5ContentHash(string content)
{
string result;
string hashData;
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
try
{
byte[] arrbytHashValue = md5Hasher.ComputeHash(ASCIIEncoding.UTF8.GetBytes(content));
hashData = BitConverter.ToString(arrbytHashValue);
hashData = hashData.Replace("-", string.Empty);
result = hashData;
}
catch (Exception)
{
return string.Empty;
}
return result;
}
/// <summary>
/// Reads the contents of a file so it can easily be hashes.
/// </summary>
/// <param name="pathName">Path of the file to hash.</param>
/// <returns>Filestream of the file.</returns>
private static FileStream GetFileStream(string pathName)
{
return IO.File.OpenRead(pathName);
}
#endregion
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.