【问题标题】:CryptographicException: Key not valid for use in specified stateCryptographicException:密钥在指定状态下无效
【发布时间】:2017-01-31 08:12:59
【问题描述】:

我是 C# 新手。我不明白为什么它会产生问题。

            CspParameters cspParams = new CspParameters(24);
            cspParams.KeyContainerName = "XML_DISG_RSA_KEY";
            RSACryptoServiceProvider key = new RSACryptoServiceProvider(cspParams);

以下代码在我的本地设置中运行良好。但它不能在客户端工作。

他们得到了以下异常。

[CryptographicException:密钥在指定状态下无效。 ]

   System.Security.Cryptography.Utils.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer) +4644432
   System.Security.Cryptography.Utils.GetKeyPairHelper(CspAlgorithmType keyType, CspParameters parameters, Boolean randomKeyContainer, Int32 dwKeySize, SafeProvHandle& safeProvHandle, SafeKeyHandle& safeKeyHandle) +69
   System.Security.Cryptography.RSACryptoServiceProvider.GetKeyPair() +92
   System.Security.Cryptography.RSACryptoServiceProvider..ctor(Int32 dwKeySize, CspParameters parameters, Boolean useDefaultKeySize) +173
   System.Security.Cryptography.RSACryptoServiceProvider..ctor(CspParameters parameters) +14

你能帮帮我吗?

【问题讨论】:

    标签: c# rsa


    【解决方案1】:

    我们的一位客户遇到了同样的错误消息,代码相似(有或没有指定UseExistingKey 标志)。他们经历了将所有用户从旧域转移到新域的过程,并且大约在那之后似乎遇到了这个错误。我们无法确定具体原因,但我们怀疑更改密钥容器文件的所有权(或者它为仍在机器上的旧域中的旧用户身份找到匹配的密钥容器文件)可能违反了安全性在 RSACryptoServiceProvider 中(或在加密 API 或底层非托管实现中)。

    我们最终通过在另一台计算机上使用测试代码手动识别密钥容器文件名 (CspKeyContainerInfo.UniqueKeyContainerName) 来解决此问题,然后删除导致错误的坏容器文件。您在 CspParameters 中指定的 KeyContainerName 每次都映射到相同的 32 位十六进制数字文件名前缀,其余文件名(显然)特定于创建它的用户。容器文件存储在机器密钥库中(如果指定了UseMachineKeyStore 标志)或漫游应用程序数据中的用户密钥库(通常为 C:\Users\userName\AppData\Roaming\Microsoft\Crypto\ .. .).

    注意不要破坏其他关键容器文件,否则可能会破坏机器上的其他应用或服务。

    您可能还会看到在构造函数调用中指定密钥大小是否有助于创建新密钥。试试 1024,或者现在可能是 2048。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-10
      • 2012-01-04
      • 1970-01-01
      • 2017-10-03
      • 1970-01-01
      • 1970-01-01
      • 2013-09-11
      • 2014-06-24
      相关资源
      最近更新 更多