Extract public key from private key in C#

2019-09-22 12:28发布

问题:

I used sn.exe to generate a key pair (private and public key). I extract a public key from private key as follows:

sn -p keyPair.snk publicKey.snk

I read it by using C# and store it in database as binary to use for encrypting my data.

Is there any way to extract a public key from a private key in C# without using sn.exe?

NOTE : I want a public key as a byte to compare it with the one I store in my database.

回答1:

Is there any way to extract a public key from a private key in C# without using sn.exe?

It is surprisingly difficult to do that but it is possible; I have done so.

What you need to do is p/invoke to StrongNameGetPublicKey in mscorwks.dll.

I read it by using C# and store it in database as binary to use for encrypting my data

This is an extremely bad idea. The purpose of a strong name public key is not to encrypt your data! The purpose of a strong name public key is for your customers to verify that the assembly you gave them was written by you. If you are using the public key for anything other than that task you are doing something very, very wrong and you should stop doing so immediately.

Strong names use encryption, but they are not an encryption technology; they are an evidence producing technology for the purpose of code access security policy evaluation.