LP on .NET

October 28, 2010

Public Key Extraction

Filed under: .NET,C#,Software Development — Larry Parker @ 9:34 am

Sometimes it’s necessary to obtain the public key of a signed assembly.  A good example is when using the InternalsVisibleTo attribute to make a signed assembly friends with another.  For example:

[assembly: InternalsVisibleTo("MyUnitTestAssembly, PublicKey=00240000 ... be0b6719c")]

Note that we need the full public key and not the shortened public key token.

But how do we get the public key that we need?  There are a couple of ways.

One way is to write some code that uses reflection to extract the public key from your assembly.  Here’s an example:

Assembly assembly = Assembly.LoadFrom(@"MyAssembly.dll");
AssemblyName assemblyName = assembly.GetName();
Byte[] key = assemblyName.GetPublicKey();
String keyString = BitConverter.ToString(key).Replace("-", "").ToLower();

This results in a string of lower-case hex digits that can be inserted into the above InternalsVisibleTo example (to the right of “PublicKey=”).

If you don’t feel like coding, you can use Microsoft’s sn.exe utility to get it for you.

The first step is to open up a Visual Studio command prompt and navigate to the directory containing your assembly.  Then enter the following:

sn –Tp <assembly>

For example:

image

Note that this displays both the full public key as well as the shortened public key token.  You’ll need to copy the public key from the console and format it accordingly.

Another approach is to use sn.exe to extract it from the strong name key file.  This requires that you first extract it to another file that will just contain the public key:

sn –p <infile> <outfile>

For example:

image

Now that the public key has been extracted to a file, we can display it on the screen:

sn –tp <infile>

image

So you have your choice on how to get at the public key.  Pick whichever works best for you.

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: