将X509Certificate2.PrivateKey解析为RSACryptoServiceProvider时出错

时间:2018-10-04 03:53:50

标签: c# azure certificate x509certificate

基本上,如果我在本地主机中的计算机上运行它,一切都会很好,但是当我尝试从Azure使用它时,出现此错误:

System.Security.Cryptography.CryptographicException: Invalid provider type specified.

发生这种情况的代码是这样的:

X509Certificate2 certificate = new X509Certificate2(pBytes, "1234");
if (!certificate.HasPrivateKey)
{
    //Here happens the Error
    RSACryptoServiceProvider key = (RSACryptoServiceProvider)certificate.PrivateKey; 
}

有任何线索吗?

顺便说一句,我正在使用的项目是https://github.com/ctt-gob-es/FirmaXadesNet

那部分的整个代码是,也许这会提供更好的背景:

X509Certificate2 certificate = new X509Certificate2(pBytes, "1234");
var key = (RSACryptoServiceProvider)certificate.PrivateKey;

        if (key.CspKeyContainerInfo.ProviderName == CryptoConst.MS_STRONG_PROV ||
            key.CspKeyContainerInfo.ProviderName == CryptoConst.MS_ENHANCED_PROV ||
            key.CspKeyContainerInfo.ProviderName == CryptoConst.MS_DEF_PROV ||
            key.CspKeyContainerInfo.ProviderName == CryptoConst.MS_DEF_RSA_SCHANNEL_PROV)
        {
            Type CspKeyContainerInfo_Type = typeof(CspKeyContainerInfo);

            FieldInfo CspKeyContainerInfo_m_parameters = CspKeyContainerInfo_Type.GetField("m_parameters", BindingFlags.NonPublic | BindingFlags.Instance);
            CspParameters parameters = (CspParameters)CspKeyContainerInfo_m_parameters.GetValue(key.CspKeyContainerInfo);

            var cspparams = new CspParameters(CryptoConst.PROV_RSA_AES, CryptoConst.MS_ENH_RSA_AES_PROV, key.CspKeyContainerInfo.KeyContainerName);
            cspparams.KeyNumber = parameters.KeyNumber;
            cspparams.Flags = parameters.Flags;
            _signingKey = new RSACryptoServiceProvider(cspparams);

            _disposeCryptoProvider = true;
        }
        else
        {
            _signingKey = key;
            _disposeCryptoProvider = false;
        }

0 个答案:

没有答案