// MIT license // Copyright 2005-2008 Ken Egozi // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Text; using System.Security.Cryptography; using System.Collections; namespace KenEgozi.CryptographicServices { public static class Hashing { private static Hashtable hashAlgorithms = Hashtable.Synchronized(new Hashtable()); /// /// Hashing a given string with SHA2. /// /// Data to hash /// Hashed data public static string HashData(string data) { return HashData(data, HashType.SHA256); } /// /// Hashing a given string with any of the supported hash algorithms. /// /// Data to hash /// Hashing algorithm to use /// Hashed data public static string HashData(string data, HashType hashType) { HashAlgorithm hash = GetHash(hashType); byte[] bytes = (new UnicodeEncoding()).GetBytes(data); byte[] hashed = hash.ComputeHash(bytes); StringBuilder sb = new StringBuilder(64); foreach (byte b in hashed) sb.AppendFormat("{0:x2}", b); return sb.ToString(); } private static HashAlgorithm GetHash(HashType hashType) { if (!hashAlgorithms.ContainsKey(hashType)) hashAlgorithms.Add(hashType, CreateaHashAlgorithm(hashType)); return hashAlgorithms[hashType] as HashAlgorithm; } private static HashAlgorithm CreateaHashAlgorithm(HashType hashType) { switch (hashType) { case HashType.MD5: return new MD5CryptoServiceProvider(); case HashType.SHA1: return new SHA1Managed(); case HashType.SHA256: return new SHA256Managed(); case HashType.SHA384: return new SHA384Managed(); case HashType.SHA512: return new SHA512Managed(); default: throw new NotImplementedException(); } } } public enum HashType { MD5, SHA1, SHA256, SHA384, SHA512 } }