开发者

ASP.NET RSACryptoServiceProvider throws Invalid flags specified exception

I got problem when try to generate keys using ASP.NET (.NET 4) for RSA, the RSACryptoServiceProvider throws invalid flags specified exception.

[CryptographicException: Invalid flags specified. ] 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

I initialize the RSA using this code:

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

        var rsaProvider = new RSACryptoServiceProvider(bitStrength, _cpsParameter);

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

Any idea how to solve this ?


One possible explanation might be that you already have a non-exportable key in the key-container with the name "" (in that case .NET will just use the existing key instead of overwriting it with a new key).

Try this code instead and see if that makes a difference:

    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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜