ASP.NET RSACryptoServiceProvider抛出指定异常的无效标志

时间:2011-01-16 16:30:55

标签: asp.net cryptography

尝试使用ASP.NET(.NET 4)为RSA生成密钥时遇到问题,RSACryptoServiceProvider抛出指定异常的无效标志。

  

[CryptographicException:指定了无效的标志。   ]      System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)+33      System.Security.Cryptography.Utils._GenerateKey(SafeProvHandle hProv,Int32 algid,CspProviderFlags flags,Int32 keySize,SafeKeyHandle& hKey)+0      System.Security.Cryptography.Utils.GetKeyPairHelper(CspAlgorithmType keyType,CspParameters parameters,Boolean randomKeyContainer,Int32 dwKeySize,SafeProvHandle& safeProvHandle,SafeKeyHandle& safeKeyHandle)+9719339      System.Security.Cryptography.RSACryptoServiceProvider.GetKeyPair()+89      System.Security.Cryptography.RSACryptoServiceProvider.ExportParameters(Boolean includePrivateParameters)+38      System.Security.Cryptography.RSA.ToXmlString(Boolean includePrivateParameters)+45

我使用以下代码初始化RSA:

            var _cpsParameter = new CspParameters();
        _cpsParameter.Flags = CspProviderFlags.UseMachineKeyStore;

        var rsaProvider = new RSACryptoServiceProvider(bitStrength, _cpsParameter);

        string publicAndPrivateKeys = rsaProvider.ToXmlString(true);
        string justPublicKey = rsaProvider.ToXmlString(false);

知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

一种可能的解释可能是您在密钥容器中已经有一个名为“”的不可导出密钥(在这种情况下,.NET只使用现有密钥而不是用新密钥覆盖它。) / p>

请尝试使用此代码,看看是否会产生影响:

    var cspParameters = new CspParameters();
    cspParameters.Flags = CspProviderFlags.UseMachineKeyStore;
    cspParameters.KeyContainerName = Guid.NewGuid().ToString();

    var rsaProvider = new RSACryptoServiceProvider(bitStrength, cspParameters);

    string publicAndPrivateKeys = rsaProvider.ToXmlString(true);
    string justPublicKey = rsaProvider.ToXmlString(false);
相关问题