I'm trying to find a way to read a privateKey created using OpenSSL PKCS#8 RSA in C# w开发者_运维技巧ithout use external library.
Does Someone know how i can do this?
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.
As of .Net Core 3:
using System.Security.Cryptography;
// ...
// I had my PK in base64
var pkBase64 = "MIIEvQI...";
var rsa = RSA.Create();
rsa.ImportPkcs8PrivateKey(Convert.FromBase64String(pkBase64), out _);
For reference: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.rsa.importpkcs8privatekey?view=net-5.0
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
精彩评论