I have an RSA private key loaded in an RSACryptoServiceProvider
object. I need to export this to a .pvk file for use with SQL Server.
Is there a way to do this from within c#? I see it's possible using openssl... https://stackoverflow.com/a/51207929/5924962
This is the only documentation I could find on the pvk file format: https://web.archive.org/web/20141117214716/http://www.drh-consultancy.demon.co.uk/pvk.html
If you look at the output of RSACryptoServiceProvider.ExportCspBlob you'll see that it starts with the same sequence of bytes as offset 24 of an unencrypted PVK file. So a PVK file is just the CSP blob with a header:
using (var output = new BinaryWriter(File.Create("rsa.pvk")))
{
output.Write(0xB0B5F11Eu); // PVK magic number
output.Write(0u);
output.Write(1u); // KEYTYPE_KEYX for RSA
output.Write(0u); // not encrypted
output.Write(0u); // encryption salt length
var cspBlob = rsaCSP.ExportCspBlob(true);
output.Write((uint)cspBlob.Length);
output.Write(cspBlob);
}
I've verified that OpenSSL will read this
openssl rsa -in rsa.pvk -inform PVK
and will generate the same PEM private key export as the code in this answer that generates the PEM private key directly from the RSACryptoServiceProvider.