Home > Mobile >  how can i compare if a loaded dll is the same as on disc
how can i compare if a loaded dll is the same as on disc

Time:02-01

I have an application that loads a copy of X.dll. How can I check if the original X.dll is different from the X.dll that is loaded.

This is as far as I've gotten:

static void Check()
{   
    Assembly assembly = Assembly.GetAssembly(typeof(X.Y));

    assembly.GetManifestResourceNames().Dump();

    byte[] loadedDllHash = GetAssemblyHash(assembly);

    byte[] fileOnDiskHash = GetFileHash(@"C:\foo\X.dll");
}


static byte[] GetAssemblyHash(Assembly assembly)
{
    //this returns null. How can I calculate the hash of the assembly?
    using (Stream stream = assembly.GetManifestResourceStream("X.dll").Dump())
    {
        return CalculateHash(stream);
    }
}

static byte[] GetFileHash(string filePath)
{
    using (FileStream stream = File.OpenRead(filePath))
    {
        return CalculateHash(stream);
    }
}

static byte[] CalculateHash(Stream stream)
{
    using (SHA256 sha256 = SHA256.Create())
    {
        return sha256.ComputeHash(stream);
    }
}

static bool CompareByteArrays(byte[] a, byte[] b)
{
    if (a.Length != b.Length)
    {
        return false;
    }

    for (int i = 0; i < a.Length; i  )
    {
        if (a[i] != b[i])
        {
            return false;
        }
    }

    return true;
}

CodePudding user response:

You can compare the file hashes of the original X.dll and the loaded X.dll to determine if they are different

using System.IO;
using System.Security.Cryptography;

...

private string ComputeHash(string filePath)
{
    using (var stream = File.OpenRead(filePath))
    {
        var sha = SHA256.Create();
        var hash = sha.ComputeHash(stream);
        return BitConverter.ToString(hash).Replace("-", string.Empty);
    }
}

...

// Compute the hash of the original X.dll
string originalHash = ComputeHash("path/to/original/X.dll");

// Load the copy of X.dll into your application
Assembly assembly = Assembly.LoadFrom("path/to/loaded/X.dll");

// Compute the hash of the loaded X.dll
string loadedHash = ComputeHash(assembly.Location);

// Compare the hashes
if (originalHash == loadedHash)
{
    Console.WriteLine("The original X.dll and the loaded X.dll are the same.");
}
else
{
    Console.WriteLine("The original X.dll and the loaded X.dll are different.");
}
  • Related