Cannot export RSA private key parameters, the requested operation is not supported

前端 未结 1 1517
梦谈多话
梦谈多话 2021-01-22 12:08

I have a certificate file provided by another party which I\'m loading in my application and cannot export its private key parameters. It looks like the certificate is using CNG

相关标签:
1条回答
  • 2021-01-22 13:12

    Unfortunately, the only way to export the key in that state is to P/Invoke into NCryptExportKey to set up an encrypted export; then import that into a new key via NCryptImportKey, and then set the export policy to AllowPlaintextExport.

    Starting in .NET Core 3.0 this will be easier:

    using (RSA exportRewriter = RSA.Create())
    {
        // Only one KDF iteration is being used here since it's immediately being
        // imported again.  Use more if you're actually exporting encrypted keys.
        exportRewriter.ImportEncryptedPkcs8(
            "password",
            rsa.ExportEncryptedPkcs8(
                "password",
                new PbeParameters(
                    PbeEncryptionAlgorithm.Aes128Cbc,
                    HashAlgorithmName.SHA256,
                    1)),
            out _);
    
        return exportRewriter.ExportParameters(true);
    }
    

    The .NET Core code for exporting encrypted is at https://github.com/dotnet/corefx/blob/64477348da1ff57a43deb65a4b12d32986ed00bd/src/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.Export.cs#L126-L237, it's not a very nice API to have to call from C#.

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