Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 669021
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T00:06:20+00:00 2026-05-14T00:06:20+00:00

I’m hashing a file with one or more hash algorithms. When I tried to

  • 0

I’m hashing a file with one or more hash algorithms. When I tried to parametrize which hash types I want, it got a lot messier than I was hoping.

I think I’m missing a chance to make better use of generics or LINQ. I also don’t like that I have to use a Type[] as the parameter instead of limiting it to a more specific set of type (HashAlgorithm descendants), I’d like to specify types as the parameter and let this method do the constructing, but maybe this would look better if I had the caller new-up instances of HashAlgorithm to pass in?

public List<string> ComputeMultipleHashesOnFile(string filename, Type[] hashClassTypes)
        {
            var hashClassInstances = new List<HashAlgorithm>();
            var cryptoStreams = new List<CryptoStream>();

            FileStream fs = File.OpenRead(filename);
            Stream cryptoStream = fs;

            foreach (var hashClassType in hashClassTypes)
            {
                object obj = Activator.CreateInstance(hashClassType);
                var cs = new CryptoStream(cryptoStream, (HashAlgorithm)obj, CryptoStreamMode.Read);

                hashClassInstances.Add((HashAlgorithm)obj);
                cryptoStreams.Add(cs);

                cryptoStream = cs;
            }

            CryptoStream cs1 = cryptoStreams.Last();

            byte[] scratch = new byte[1 << 16];
            int bytesRead;
            do { bytesRead = cs1.Read(scratch, 0, scratch.Length); }
            while (bytesRead > 0);

            foreach (var stream in cryptoStreams)
            {
                stream.Close();
            }

            foreach (var hashClassInstance in hashClassInstances)
            {
                Console.WriteLine("{0} hash = {1}", hashClassInstance.ToString(), HexStr(hashClassInstance.Hash).ToLower());
            }
        }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T00:06:20+00:00Added an answer on May 14, 2026 at 12:06 am

    Let’s start by breaking the problem down. Your requirement is that you need to compute several different kinds of hashes on the same file. Assume for the moment that you don’t need to actually instantiate the types. Start with a function that has them already instantiated:

    public IEnumerable<string> GetHashStrings(string fileName,
        IEnumerable<HashAlgorithm> algorithms)
    {
        byte[] fileBytes = File.ReadAllBytes(fileName);
        return algorithms
            .Select(a => a.ComputeHash(fileBytes))
            .Select(b => HexStr(b));
    }
    

    That was easy. If the files might be large and you need to stream it (keeping in mind that this will be much more expensive in terms of I/O, just cheaper for memory), you can do that too, it’s just a little more verbose:

    public IEnumerable<string> GetStreamedHashStrings(string fileName,
        IEnumerable<HashAlgorithm> algorithms)
    {
        using (Stream fileStream = File.OpenRead(fileName))
        {
            return algorithms
                .Select(a => {
                    fileStream.Position = 0;
                    return a.ComputeHash(fileStream);
                })
                .Select(b => HexStr(b));
        }
    }
    

    It’s a little gnarly and in the second case it’s highly questionable whether or not the Linq-ified version is any better than an ordinary foreach loop, but hey, we’re having fun, right?

    Now that we’ve disentangled the hash-generation code, instantiating them first isn’t really that much more difficult. Again we’ll start with code that’s clean – code that uses delegates instead of types:

    public IEnumerable<string> GetHashStrings(string fileName,
        params Func<HashAlgorithm>[] algorithmSelectors)
    {
        if (algorithmSelectors == null)
            return Enumerable.Empty<string>();
        var algorithms = algorithmSelectors.Select(s => s());
        return GetHashStrings(fileName, algorithms);
    }
    

    Now this is much nicer, and the benefit is that it allows instantiation of the algorithms within the method, but doesn’t require it. We can invoke it like so:

    var hashes = GetHashStrings(fileName,
        () => new MD5CryptoServiceProvider(),
        () => new SHA1CryptoServiceProvider());
    

    If we really, really, desperately need to start from the actual Type instances, which I’d try not to do because it breaks compile-time type checking, then we can do that as the last step:

    public IEnumerable<string> GetHashStrings(string fileName,
        params Type[] algorithmTypes)
    {
        if (algorithmTypes == null)
            return Enumerable.Empty<string>();
        var algorithmSelectors = algorithmTypes
            .Where(t => t.IsSubclassOf(typeof(HashAlgorithm)))
            .Select(t => (Func<HashAlgorithm>)(() =>
                (HashAlgorithm)Activator.CreateInstance(t)))
            .ToArray();
        return GetHashStrings(fileName, algorithmSelectors);
    }
    

    And that’s it. Now we can run this (bad) code:

    var hashes = GetHashStrings(fileName, typeof(MD5CryptoServiceProvider),
        typeof(SHA1CryptoServiceProvider));
    

    At the end of the day, this seems like more code but it’s only because we’ve composed the solution effectively in a way that’s easy to test and maintain. If we wanted to do this all in a single Linq expression, we could:

    public IEnumerable<string> GetHashStrings(string fileName,
        params Type[] algorithmTypes)
    {
        if (algorithmTypes == null)
            return Enumerable.Empty<string>();
        byte[] fileBytes = File.ReadAllBytes(fileName);
        return algorithmTypes
            .Where(t => t.IsSubclassOf(typeof(HashAlgorithm)))
            .Select(t => (HashAlgorithm)Activator.CreateInstance(t))
            .Select(a => a.ComputeHash(fileBytes))
            .Select(b => HexStr(b));
    }
    

    That’s all there really is to it. I’ve skipped the delegated “selector” step in this final version because if you’re writing this all as one function you don’t need the intermediate step; the reason for having it as a separate function earlier is to give as much flexibility as possible while still maintaining compile-time type safety. Here we’ve sort of thrown it away to get the benefit of terser code.


    Edit: I will add one thing, which is that although this code looks prettier, it actually leaks the unmanaged resources used by the HashAlgorithm descendants. You really need to do something like this instead:

    public IEnumerable<string> GetHashStrings(string fileName,
        params Type[] algorithmTypes)
    {
        if (algorithmTypes == null)
            return Enumerable.Empty<string>();
        byte[] fileBytes = File.ReadAllBytes(fileName);
        return algorithmTypes
            .Where(t => t.IsSubclassOf(typeof(HashAlgorithm)))
            .Select(t => (HashAlgorithm)Activator.CreateInstance(t))
            .Select(a => {
                byte[] result = a.ComputeHash(fileBytes);
                a.Dispose();
                return result;
            })
            .Select(b => HexStr(b));
    }
    

    And again we’re kind of losing clarity here. It might be better to just construct the instances first, then iterate through them with foreach and yield return the hash strings. But you asked for a Linq solution, so there you are. 😉

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have just tried to save a simple *.rtf file with some websites and
i want to parse a xhtml file and display in UITableView. what is the
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I want to count how many characters a certain string has in PHP, but
I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm making a simple page using Google Maps API 3. My first. One marker
We are using XSLT to translate a RIXML file to XML. Our RIXML contains
I have a text area in my form which accepts all possible characters from
I'm parsing an XML file, the creators of it stuck in a bunch social

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.