/// <summary> /// Computes the hash of a given InputStream. This is a wrapper over the HashAlgorithm crypto functions. /// </summary> /// <param name="stream">the source stream. Use a MemoryStream if uncertain.</param> /// <param name="hashType">the Algorithm to use to compute the hash</param> /// <returns>a byte[] representation of the hash. If the Stream is a null object /// then null will be returned. If the Stream is empty an empty byte[] {} will be returned.</returns> public static byte[] ComputeHash(this Stream stream, ChecksumAlgorithm hashType = ChecksumAlgorithm.SHA256, long?maxBodySize = null) { if (stream == null) { return(null); } using (var algorithm = HashTypeFactory.Create(hashType)) if (maxBodySize != null && maxBodySize > 0) { return(algorithm.ComputeHash(stream.ReadExactly((long)maxBodySize))); } else { return(algorithm.ComputeHash(stream)); } }
/// <summary> /// Computes the HMAC hash of a given byte[]. This is a wrapper over the Mac crypto functions. /// </summary> /// <param name="data">byte[] of content to hash</param> /// <param name="key">secret key to salt the hash. This is assumed to be UTF-8 encoded</param> /// <param name="hashType">determines which alogirthm to use. The recommendation is to use HMAC-SHA256</param> /// <returns>a byte[] presenting the HMAC hash of the source data. If the data object is null, null will be returned</returns> public static byte[] ComputeKeyedHash(this byte[] data, string key, KeyedHashAlgorithm hashType = KeyedHashAlgorithm.HMACSHA256) { if (data == null) { return(null); } if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException("key"); } using (var algorithm = HashTypeFactory.Create(hashType)) { algorithm.Key = key.ToByteArray(); return(algorithm.ComputeHash(data)); } }