How to import PKCS#8 RSA privateKey (created by OpenSSL) in C#

大兔子大兔子 提交于 2019-11-27 14:53:47

The easiest way to do this with an external library, is using the (free) Chillkat Public / Private Key Component: using that, importing the key can be done using just a few lines of code and if you're willing to pay the $149 or so for the rest of the library, it will make dealing with general crypto concepts a lot easier as well.

And unlike the regular Microsoft .NET Framework, the Mono project does seem to have a PKCS8 implementation for which the full C# source is available. This may be suitable as a starting point in case you absolutely cannot rely on external libraries, assuming the (LGPL 2.0) license associated with the Mono code works for you...

Finally, the PKCS #8 format is not too difficult to parse, and the RSA/DSA key pair objects are as per PKCS #11 and relatively easy to convert to a .NET X509Certificate once you figure out where all the bits go -- I actually did this in VB.NET a while ago, but unfortunately am not able to share that code.

Makah

Thanks for your answer.

My script to create RSA key i used OpenSSL whit:

(Linux Script)

openssl genrsa -out ${NAME}_openssl.key 2048
openssl pkcs8 -topk8 -in ${NAME}_openssl.key -nocrypt > ${NAME}.key
openssl req -new -x509 -key ${NAME}.key -out ${NAME}.crt -outform DER

In C# we need privateKey in XML format. I used this parser to do this.

To decrypt de challenge we need to use:

  byte[] challange = server.getChallenge();

  RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider();

  rsaProvider.FromXmlString(Demo.Properties.Resources.XmlPrivateKey);

  byte[] plaintext = rsaProvider.Decrypt(challange, false);

To encrypt whit server certificate we need to use:

  RSACryptoServiceProvider rsaProvider = x509.PublicKey.Key as RSACryptoServiceProvider;

  byte[] answer = RsaProvider.Encrypt(plaintext, false);

Thanks for JavaScience Consulting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!