【问题标题】:CryptoAPI AcquireContext fails to retrieve key containerCryptoAPI AcquireContext 无法检索密钥容器
【发布时间】:2013-04-11 09:27:14
【问题描述】:

我正在将一个旧的 VB6 应用程序移植到 .NET,但从昨天下午开始,我遇到了一些 CryptoAPI 调用的问题。

特别是我无法检索已定义的密钥容器。我使用CryptAcquireContext() 函数。我在创建容器的地方使用了一些测试代码。然后,如果我转到C:\Users...\Roaming\Microsoft\Crypto\RSA\Machine Keys\,我可以看到一个使用我定义的容器名称创建的文件,所以我认为它已成功创建。

尝试创建相同容器的后续调用验证了该假设,因为我收到了键集已定义的 win32 错误。

无论如何,在我的下一个代码调用中,我尝试检索我已经创建的容器,我得到了未定义键集的 Windows 错误。

错误:-2146893799 (80090019) 未定义键集。

有什么想法吗?

这是一个代码示例:

public const uint PROV_RSA_FULL = 1;
public const uint CRYPT_NEWKEYSET = 0x00000008;
public const uint CRYPT_MACHINE_KEYSET = 0x00000020;
const string MS_DEF_PROV = "Microsoft Base Cryptographic Provider v1.0";

[DllImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CryptAcquireContext(out IntPtr phProv, string pszContainer, string pszProvider, uint dwProvType, uint dwFlags);

public static void CreateContainer()
{
        IntPtr hCryptProv;
        int error;
        if (!CryptAcquireContext(out hCryptProv, "new", MS_DEF_PROV, PROV_RSA_FULL, CRYPT_NEWKEYSET))
        {
            error = Marshal.GetLastWin32Error();
        }

        if (!CryptAcquireContext(out hCryptProv, "new", MS_DEF_PROV, PROV_RSA_FULL, CRYPT_MACHINE_KEYSET))
        {
            error = Marshal.GetLastWin32Error();
        }
}

【问题讨论】:

标签: c# .net cryptoapi


【解决方案1】:

您正在为该用户创建密钥容器,但试图从基于机器的存储中获取它。要解决此问题,您需要将 CRYPT_MACHINE_KEYSET 更改为 0,或者在创建密钥集时根据您的需要使用 CRYPT_NEWKEYSET | CRYPT_MACHINE_KEYSET

默认情况下,密钥和密钥容器存储为用户密钥。对于 Base Providers,这意味着用户密钥容器存储在用户的配置文件中。管理员创建的没有此标志的密钥容器只能由创建密钥容器的用户和具有管理权限的用户访问。

详情请查看以下链接。

CryptAcquireContext() use and troubleshooting

CryptAcquireContext function

【讨论】:

  • 非常感谢。虽然我不太明白这个概念:(
猜你喜欢
  • 1970-01-01
  • 2019-06-21
  • 2011-01-11
  • 2011-02-24
  • 1970-01-01
  • 2012-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多