Wednesday, November 18, 2015

InternalsVisibleTo PublicKey

I had to write some tests which accessed internal members of an assembly. You just have to put this in the app project being tested:

[assembly: InternalsVisibleTo("TestAssemblyName, PublicKey=XXXXXXXX...")]

But after a couple of years I couldn't remember how to get the PublicKey value. After bumbling around for 15 minutes I suddenly remembered you do this with the sn.exe utility from a Visual Studio Tools command prompt.

sn -Tp TestAssemblyFileName

Then you'll get output like the following. Paste the public key hex digits into the attribute and correct the formatting.

Public key (hash algorithm: sha1):
0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67
871e773a8fde8938c81dd402ba65b9301d60593e96c492651e889cc13f1415ebb53fac1131ae0b
d333c5ee6021672d9718ea31a844bd0db0072f25d87dba6fc90ffd598ed4da35e44c398c454307
13e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c3
08055da9

Public key token is 39af3856bd364e35

If you want to get the hex digits in code you can do this:

var asm = Assembly.Loadfile("Path to assembly file");
var sn = asm.Evidence.OfType<System.Security.Policy.StrongName>().FirstOrDefault();
if (sn != null)
{
  Trace(sn.PublicKey.ToString());
}