/// <summary> /// Creates a new salted hash /// </summary> /// <param name="bytes">Text to hash</param> /// <param name="salt">Salt to hash with</param> /// <param name="type">Hash algorithm to use</param> /// <param name="bitSize">[ONLY IN SHA3] SHA3 algorithm bit size</param> public static byte[] Hash(byte[] bytes, byte[] salt, HashType type = HashType.SHA256, SHA3BitSize bitSize = SHA3BitSize._256) { return ComputeHash(bytes, salt, type, bitSize); }
// Creates a hash static byte[] ComputeHash(byte[] bytes, byte[] salt, HashType type, SHA3BitSize bitSize) { // Create a hash buffer with a salt if(salt != null && salt.Length > 0) { byte[] full = new byte[bytes.Length + salt.Length]; for(int i = 0; i < bytes.Length; i++) full[i] = bytes[i]; for(int i = 0; i < salt.Length; i++) full[bytes.Length + i] = salt[i]; bytes = full; } // Identify the hash algorithm type HashAlgorithm crypt; switch(type) { case HashType.SHA1: crypt = new SHA1Managed(); break; case HashType.SHA256: crypt = new SHA256Managed(); break; case HashType.SHA512: crypt = new SHA512Managed(); break; case HashType.SHA3: crypt = new SHA3.SHA3Managed((int)bitSize); break; case HashType.MD5: crypt = new MD5CryptoServiceProvider(); break; default: throw new ArgumentException("Parameter invalid", "type"); } return crypt.ComputeHash(bytes); }
/// <summary> /// Creates a new salted hash /// </summary> /// <param name="text">Text to hash</param> /// <param name="salt">Salt to hash with</param> /// <param name="e">Encoding to use</param> /// <param name="type">Hash algorithm type</param> /// <param name="bitSize">[ONLY IN SHA3] SHA3 algorithm bit size</param> public static string Hash(string text, string salt, Encoding e, HashType type = HashType.SHA256, SHA3BitSize bitSize = SHA3BitSize._256) { if(string.IsNullOrEmpty(text)) throw new ArgumentException("The parameter is null or empty.", "text"); else if(e == null) e = Encoding.Default; // Create a hexadecimal hash as a string var hash = ComputeHash(e.GetBytes(text), e.GetBytes(salt), type, bitSize); var sb = new StringBuilder(); for(int i = 0; i < hash.Length; i++) sb.Append(hash[i].ToString("X2")); return sb.ToString(); }