0

Is there any way to compute a cryptographic hash of an assembly in .NET Standard? It's very important that this hash stays the same unless something is modified inside the assembly (eg. that it was rebuilt).

For example, assuming .NET Framework is used, we do the following

var assembly = Assembly.GetCallingAssembly();

var hash = new Hash(assembly);

var hashVal = hash.GenerateHash(new SHA512Managed());

I have tried to serialize the assembly as shown below but I get the error

Unhandled Exception: System.Runtime.Serialization.SerializationException: Type 'System.Reflection.RuntimeAssembly' in Assembly 'System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e' is not marked as serializable.

 var assembly = Assembly.GetCallingAssembly();

 BinaryFormatter formatter = new BinaryFormatter();
 MemoryStream stream = new MemoryStream();
 formatter.Serialize(stream, assembly);

 SHA512 sha = SHA512.Create();

 var hash = Convert.ToBase64String(sha.ComputeHash(stream));
Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66
Artem
  • 1,000
  • 1
  • 15
  • 30
  • Possible duplicate of [How to compute a hash of assembly, so that this hash could be used to tell if the code in the assembly has changed?](https://stackoverflow.com/questions/39737279/how-to-compute-a-hash-of-assembly-so-that-this-hash-could-be-used-to-tell-if-th) – Peter B Sep 17 '19 at 12:02
  • How about a hash of the assembly's file... `Assembly.GetCallingAssembly().Location` – phuzi Sep 17 '19 at 12:06
  • Assembly signing is already available since .NET 1.0. Using BinaryFormatter on the other hand is frowned upon for security reasons. You have no idea what `BinaryFormatter` is going to produce. It could easily be a signed *malicious* assembly – Panagiotis Kanavos Sep 17 '19 at 12:14
  • There's even a code analysis rule for this [CA2300: Do not use insecure deserializer BinaryFormatter](https://learn.microsoft.com/en-us/visualstudio/code-quality/ca2300-do-not-use-insecure-deserializer-binaryformatter?view=vs-2019) – Panagiotis Kanavos Sep 17 '19 at 12:15

0 Answers0