Search code examples
c#public-keystrongnamersacryptoserviceproviderstrong-named-key

Create RSACryptoServiceProvider from public key ONLY


I am using the key-pair to sign my XML (using SignedXml) and I embed the public key in my app as embedded resources.

Here how I create the key pair

sn -k Warehouse.snk
sn -p Warehouse.snk WarehousePublic.snk

When I tried to read the WarehousePublic.snk I get an exception Bad Version of provider.

Here is my code:

using (Stream stream = assembly.GetManifestResourceStream("WareApp.Resources.WarehousePublic.snk"))
{
    byte[] bytes = new byte[stream.Length];
    stream.Read(bytes, 0, bytes.Length);

    using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
    {
        rsa.ImportCspBlob(bytes);  //the exception occurred here

        ...
        ...
        ...
    }
}

Is there a way to create RSACryptoServiceProvider from public key only?

I have also tried to use X509Certificate2

X509Certificate2 cert = new X509Certificate2(bytes);  //I got exception here
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert2.PublicKey.Key;

But I get exception Cannot find the requested object.

Any idea?

Thanks


Solution

  • I think using SN to generate certificates for signing (using the RSACryptoServiceProvider at least) is unsupported. That would explain the error, I think. What you're looking for, in Windows, is a .PFX file (i.e. certificate with key) and .CER file (certificate without private key).

    SN (MSDN link) doesn't provide security, and is only used for identity. You can use IIS or makecert.exe to generate a self-signed certificate that should work with what you're trying to do (i.e. a .PFX file and / or certificate already imported into the Windows certificate store). You can then extract the .CER file from that and use it for your project.