Saturday, January 22, 2011

Getting a Public Key Blob From 3rd Party Assemblies

The Return of Code Access Security

Working with SharePoint sometimes takes you to some pretty weird places. Code Access SecurityThere’s a lot of .NET’s surface area that I’m pretty sure I’d never have explored on my own if I hadn’t been tasked to do so via some SharePoint engagement.

One of these explorations has involved authoring custom CAS policies, the reasons for which I’ve blogged about in the past. Granted with the advent of SharePoint 2010 and sandboxed solutions it’s not as common a task these days, but it still comes up.

When authoring a custom CAS policy you’re taxed with obtaining the Public Key Blob from a Strong Name Key. This helps the .NET runtime identify assemblies (via their Strong Name) that you’d like to run with a particular code access security profile.

Now obtaining a public key blob is pretty straight forward if you have the .snk, but it gets a little more awkward if all you have is some 3rd party assembly. This is often the case when you want 3rd parties assembly (for us it was a bunch of Telerik Controls) to run in full trust. After all you don’t have their key and they’re super unlikely to give it to you.

Getting a Public Key Blob from a 3rd Party Assembly

1) First open up the Visual Studio Command Prompt (or optionally any command prompt, but have access to sn.exe which is typically found in Visual Studio’s SDK->BIN folder).

2) Run the following command:

sn -e [ThirdPartyAssembly.dll] publicKey.snk

This extracts the public key (and public key blob) into a file.

3) Then run:

sn -tp publicKey.snk

Which should display the public key blob and public key token (the blob is the long one).

Public Key Blob

At this point you can throw it in your own custom CAS file or resume whatever would make you seek out these awkward little strings in the first place.

Hope that helps. Had stare at the sn.exe docs for a good 10 minutes to find this and the web wasn’t all that helpful.

Happy CASing,