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

后端 未结 2 1264
梦如初夏
梦如初夏 2020-12-03 16:30

I\'m trying to find a way to read a privateKey created using OpenSSL PKCS#8 RSA in C# without use external library.

Does Someone know how i can do this?

相关标签:
2条回答
  • 2020-12-03 17:15

    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.

    0 讨论(0)
  • 2020-12-03 17:17

    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

    0 讨论(0)
提交回复
热议问题