InternalsVisibleTo for a dynamically created assembly, but with a strong name

I have a project that uses dynamic code generation to create a proxy class. This proxy class uses the internal classes of the project (so implementation details are not displayed), so I use InternalsVisibleTo with the name of my dynamically generated assembly. This worked until recently, when my client made a requirement that all submitted assemblies be strongly named.

The problem arises because in order to use InternalsVisibleTo with a node with a strong name, the assemblies that it refers to must also be strong, and you must provide a public key. Where I am looping, how to provide a strong name for a dynamically created assembly. Here is what I have done so far:

  • I created a new key pair for dynamic assemblies so that .snk can be sent along with the product (obviously we do not want to send .snk to sign the rest of the project assembly.)
  • I extracted PublicKey and updated myInternalsVisibleTo to use the new dynamic PublicKey for dynamically linked assemblies.
  • I tried to sign dynamically generated assemblies as follows:

        var name = new AssemblyName("ProxyBuilderAssembly");
        var attributes = new CustomAttributeBuilder[1];
        attributes[0] =
            new CustomAttributeBuilder(typeof(AssemblyKeyFileAttribute).GetConstructor(new[] {typeof(string)}),
                                       new object[] {"Dynamic.snk"});
        _assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndSave, attributes);
        _module = _assembly.DefineDynamicModule("ProxyBuilderAssembly", "ProxyBuilderAssembly.dll");
    

Unfortunately, this does not work, and it is very difficult for me to find documentation on how this should work. Does anyone know how to sign a dynamically generated assembly to access through InternalsVisibleTo? I can simply make the necessary classes publicly available, but this will lead to leakage of implementation details that are best encapsulated.

+3
source
1

" " MSDN, , Reflection.Emit.

StrongNameKeyPair kp;
// Getting this from a resource would be a good idea.
using(stream = GetStreamForKeyPair())
{
    kp = new StrongNameKeyPair(fs);
}
AssemblyName an = new AssemblyName();
an.KeyPair = kp;
AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.RunAndSave);
+4

Source: https://habr.com/ru/post/1790779/


All Articles