diff --git a/X10D/src/StreamExtensions.cs b/X10D/src/StreamExtensions.cs deleted file mode 100644 index 19405e5..0000000 --- a/X10D/src/StreamExtensions.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System; -using System.IO; -using System.Security.Cryptography; - -namespace X10D -{ - /// - /// Extension methods for . - /// - public static class StreamExtensions - { - /// - /// Returns the hash of a stream using the specified hashing algorithm. - /// - /// A derived type. - /// The stream whose hash is to be computed. - /// Returns a array representing the hash of the stream. - /// is . - public static byte[] GetHash(this Stream stream) - where T : HashAlgorithm - { - if (stream is null) - { - throw new ArgumentNullException(nameof(stream)); - } - - var create = typeof(T).GetMethod("Create", Array.Empty()); - using var crypt = (T)create?.Invoke(null, null); - return crypt?.ComputeHash(stream); - } - } -} diff --git a/X10D/src/StreamExtensions/StreamExtensions.cs b/X10D/src/StreamExtensions/StreamExtensions.cs new file mode 100644 index 0000000..18dc5ad --- /dev/null +++ b/X10D/src/StreamExtensions/StreamExtensions.cs @@ -0,0 +1,53 @@ +using System; +using System.IO; +using System.Security.Cryptography; + +namespace X10D.StreamExtensions +{ + /// + /// Extension methods for . + /// + public static class StreamExtensions + { + /// + /// Returns the hash of a stream using the specified hash algorithm. + /// + /// A derived type. + /// The stream whose hash is to be computed. + /// A array representing the hash of the stream. + /// is . + /// + /// does not offer a static Create method. + /// -or- + /// An invocation to the static Create method defined in returned + /// . + /// + /// The stream has already been disposed. + /// This method consumes the stream from its current position!. + public static byte[] GetHash(this Stream stream) + where T : HashAlgorithm + { + if (stream is null) + { + throw new ArgumentNullException(nameof(stream)); + } + + var type = typeof(T); + var create = type.GetMethod("Create", Array.Empty()); + if (create is null) + { + throw new TypeInitializationException(type.FullName, + new ArgumentException(ExceptionMessages.HashAlgorithmNoCreateMethod)); + } + + using var crypt = create.Invoke(null, null) as T; + if (crypt is null) + { + throw new TypeInitializationException(type.FullName, + new ArgumentException(ExceptionMessages.HashAlgorithmCreateReturnedNull)); + } + + return crypt.ComputeHash(stream); + } + } +}