Casting private key to RSACryptoServiceProvider not working

爷,独闯天下 提交于 2019-12-10 11:24:31

问题


I have a X509Certificate2 variable and I'm trying to cast the private key of the variable to a RSACryptoServiceProvider

RSACryptoServiceProvider pkey = (RSACryptoServiceProvider)cert.PrivateKey;

However I get this exception.

System.InvalidCastException: 'Unable to cast object of type 'System.Security.Cryptography.RSACng' to type 'System.Security.Cryptography.RSACryptoServiceProvider'.'

It's weird that this happens because other answers in SO suggested the same procedure as mine but I get an exception. Any solutions to this?


回答1:


So after a few tries and discussions in the comments I came up with the following solution.

            RSA rsa = (RSA)cert.PrivateKey;
        (cert.PrivateKey as RSACng).Key.SetProperty(
            new CngProperty(
                "Export Policy",
                BitConverter.GetBytes((int)CngExportPolicies.AllowPlaintextExport),
                CngPropertyOptions.Persist));

        RSAParameters RSAParameters = rsa.ExportParameters(true);                      

        AsymmetricCipherKeyPair keypair = DotNetUtilities.GetRsaKeyPair(RSAParameters);

The problem was that the variable rsa wasn't exportable. To change this I set a new CngProperty for the export policy. Works perfectly now



来源:https://stackoverflow.com/questions/55949510/casting-private-key-to-rsacryptoserviceprovider-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!