Assembly.LoadFrom - using Evidence overload to verify strong name signature
-
03-07-2019 - |
Question
Is it possible to use the Assembly.LoadFrom overload with the Evidence parameter to ensure the assembly is strongly named? I want to be able to specify the assembly name, culture, version, and public key token. If any of this information does not match the assembly should fail to load.
Solution 3
I found another way to do this.
var assemblyName = new AssemblyName(<fully qualified type name>);
assemblyName.CodeBase = <path to assembly>
Assembly.Load(assemblyName);
OTHER TIPS
You can get an Assembly's public key after loading it - if it loads successfully and has a public key, then it's strong-named:
Assembly assembly = Assembly.LoadFrom (...);
byte[] pk = assembly.GetName().GetPublicKey();
Better still, check the assembly's public key and version info before loading it:
AssemblyName an = AssemblyName.GetAssemblyName ("myfile.exe");
byte[] publicKey = an.GetPublicKey();
CultureInfo culture = an.CultureInfo;
Version version = an.Version;
If GetPublicKey() returns a non-null value, and then the assembly successfully loads, it has a valid strong name.
I have a way for breaking the strong-name verification for patching System.Windows.Forms.dll. If I'm using it, there's not much you can do about it. My trick requires full trust.
What I did was patch the dll, deploy the patched dll, ngen it, and patch the loader to pick up the patched ngen image instead of the original. What I could have done was clobber the stock ngened dll. (I actually tested this path and decided potentially breaking somebody else's software was a poor choice.)
I'm not saying this is a good idea to do. I'm saying that depending on verifying signatures from Assembly.Load is a bad idea.
Try the System.ReflectionAssemblyNameFlags enumeration:
bool f_public_key = ((asm.GetName().Flags & AssemblyNameFlags.PublicKey) != 0);