我正在将一个旧的VB6应用程序移植到.NET上,从昨天下午开始,我就遇到了一些CryptoAPI调用的问题。
特别是,我无法检索已经定义的密钥容器。我使用CryptAcquireContext()函数。我使用一些测试代码来创建容器。然后,如果我转到C:\Users...\Roaming\Microsoft\Crypto\RSA\Machine Keys\,我可以看到一个文件,里面有我定义的容器名,所以我假设它已经成功创建了。
尝试创建同一个容器的后续调用验证了这个假设,因为我得到了键集已经定义的win32错误。
无论如何,在我的下一个代码调用中,我尝试检索我已经创建的容器,我得到了没有定义keyset的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();
}
}发布于 2013-04-11 10:39:09
您正在为该用户创建密钥容器,但试图从基于机器的存储中获取它。要解决这个问题,您需要将CRYPT_MACHINE_KEYSET更改为0,或者在创建密钥集时根据您的需要使用CRYPT_NEWKEYSET | CRYPT_MACHINE_KEYSET。
默认情况下,密钥和密钥容器作为用户密钥存储。对于Base,这意味着用户密钥容器存储在用户的配置文件中。只有创建密钥容器的用户和具有管理权限的用户才能访问没有此标志由管理员创建的密钥容器。
有关详细信息,请查看下面的链接。
CryptAcquireContext()的使用和故障排除
CryptAcquireContext函数
https://stackoverflow.com/questions/15945218
复制相似问题