简体   繁体   中英

How do I create/export to a .PVK file using C#?

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

Mono project has an open source implementation of the PVK format,

https://github.com/mono/mono/blob/master/mcs/class/Mono.Security/Mono.Security.Authenticode/PrivateKey.cs

Note the Mono.Security NuGet package is not official.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM