[CRYPTO]Use RSA keyset generated by .NET sn.exe tool

 

I’ve found some public articles about how to manually extract RSA keyset from the snk file generated by .NET sdk tool “sn.exe”.

 

#Strong Name Tool (Sn.exe) 

http://msdn.microsoft.com/en-us/library/k5b5tt23(VS.80).aspx

 

And some community guys have also encountered some problems manually use the sn.exe generated snk file to get RSA keyinfo and perform encryption/signing. By doing some research on this, I found that it is really not good idea to use SN.EXE generated key file for our RSA crypto task. Here are some reasons:

 

l  Sn.exe generated key file is of an undocumented format. Microsoft doesn’t expect the developers to directly load RSA keyset from this file.

 

l  Sn.exe generated keyset is “signature” keyset, therefore, it is used for data signing and verifying

 

l  The reasonable usage of SN.exe generated keyset is for digital signing against .NET assembly(strong-name signing).

 

 

However, if you do want to use the RSA keyset generated by sn.exe(-k), you can consider the following means:

 

1.generate snk file via "sn.exe -k" command:

 

sn.exe -k MyTestRSA_SNKContainer

 

2.install the keyset into a KeyContainer via "sn.exe -i" command:

 

sn.exe -i MyTestRSA.snk MyTestRSA_SNKContainer

 

3.Read keyset from KeyContainer(instead of snk file):

 

 

 

static void Use_SNKContainer()

        {

            RSACryptoServiceProvider RSA = null;

 

            string container = "MyTestRSA_SNKContainer";

            CspParameters cp1 = new CspParameters();

 

            cp1.Flags = CspProviderFlags.UseMachineKeyStore | CspProviderFlags.UseExistingKey;

            cp1.KeyNumber = (int)KeyNumber.Signature;

            cp1.KeyContainerName = container;

            RSA = new RSACryptoServiceProvider(cp1);

 

            //perform signing or verification

           

 

 

Also, if you want to generate RSA keyset programmatically in .NET code, here are some samples:

 

#How to generate key pairs, encrypt and decrypt data with .NET (C#)

http://blogs.msdn.com/alejacma/archive/2008/10/23/how-to-generate-key-pairs-encrypt-and-decrypt-data-with-net-c.aspx

 

#Generating Keys for Encryption and Decryption 

http://msdn.microsoft.com/en-us/library/5e9ft273(VS.80).aspx