/// <summary> /// Gets the alogrithm. /// </summary> /// <param name="method">The method.</param> /// <param name="hashName">Name of the hash algorithm.</param> /// <returns></returns> /// <exception cref="System.NotSupportedException"> /// </exception> private static HashAlgorithm GetHashAlogrithm(HashMethod method, string hashName = null) { if (hashName == null) { switch (method) { case HashMethod.MD5: return(MD5CryptoServiceProvider.Create()); case HashMethod.SHA1: return(SHA1CryptoServiceProvider.Create()); case HashMethod.SHA256: return(SHA256CryptoServiceProvider.Create()); case HashMethod.SHA384: return(SHA384CryptoServiceProvider.Create()); case HashMethod.SHA512: return(SHA512CryptoServiceProvider.Create()); case HashMethod.CRC32: return(new CRC32()); default: throw new NotSupportedException( string.Format("Method [{0}] is not supported.", method.ToString())); } } else { switch (method) { case HashMethod.MD5: return(MD5CryptoServiceProvider.Create(hashName)); case HashMethod.SHA1: return(SHA1CryptoServiceProvider.Create(hashName)); case HashMethod.SHA256: return(SHA256CryptoServiceProvider.Create(hashName)); case HashMethod.SHA384: return(SHA384CryptoServiceProvider.Create(hashName)); case HashMethod.SHA512: return(SHA512CryptoServiceProvider.Create(hashName)); default: throw new NotSupportedException( string.Format("Method [{0}] is not supported.", method.ToString())); } } }
/// <summary> /// Create a hash value from a byte array's content. /// </summary> /// <param name="content">the literal content to evaluate for the hash.</param> /// <param name="method">The HashMethod enumeration for the evaluation</param> /// <returns>A hex-encoded value of the hash value</returns> public static string GetHash(byte[] content, HashMethod method) { HashAlgorithm hashString = new SHA1Managed(); switch (method) { case HashMethod.SHA1: break; case HashMethod.SHA256: hashString = new SHA256Managed(); break; case HashMethod.SHA384: hashString = new SHA384Managed(); break; case HashMethod.SHA512: hashString = new SHA512Managed(); break; case HashMethod.MD5: hashString = new MD5CryptoServiceProvider(); break; case HashMethod.RIPEMD: hashString = new RIPEMD160Managed(); break; default: throw new ArgumentException("Unrecognized hash encoding: " + method.ToString()); } return(ByteArrayToHex(hashString.ComputeHash(content))); }
/// <summary> /// Hash string with selected hash method. The string will contain method name that was used for hashing. /// </summary> /// <param name="target">String to hash.</param> /// <param name="method">Method to use to hash.</param> /// <returns>Hashed string.</returns> public static string Hash(string target, HashMethod method) { Guard.IsNotNull(target, nameof(target)); return(method.ToString().ToUpperInvariant() + PasswordMethodHashSeparator + ConvertBytesToString(hashMethodsMap[method](target))); }