从 C# 调用 CryptAcquireContext
Calling CryptAcquireContext from C#
我想在 C# 中使用 'CryptAcquireContext' WinAPI 函数。
我有 using System.Runtime.InteropServices
,我按以下方式导入 DLL:
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool CryptAcquireContext(ref IntPtr hProv, string pszContainer, string pszProvider, uint dwProvType, uint dwFlags);
要调用该函数,我使用以下代码:
IntPtr handelTest = new IntPtr();
uint CRYPt_VERIFYCONTEXT = 0xF0000000;
uint PROV_RsA_FULL = 1;
bool res = CryptAcquireContext(ref handelTest, null, "MS_ENHANCED_PROV", PROV_RsA_FULL, CRYPt_VERIFYCONTEXT);
if (!res)
{
int a = Marshal.GetLastWin32Error();
Console.WriteLine("Error in Acqired, CryptAcquireContext function\n");
return;
}
Console.WriteLine("Key Context Acquired\n");
但是,出现错误res==false
。
我的代码有什么问题?
这不是 P/Invoke 问题。参数不好,GetLastError(a)是NTE_KEYSET_NOT_DEF / 0x80090019,也就是"The requested provider does not exist.".
将 null
作为提供商名称参数传递,或使用有效的提供商名称。
但是,请注意我会这样定义函数(确保 unicode,第一个参数是 out
,而不是 ref
):
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static extern bool CryptAcquireContext(out IntPtr hProv, string pszContainer, string pszProvider, uint dwProvType, uint dwFlags);
我想在 C# 中使用 'CryptAcquireContext' WinAPI 函数。
我有 using System.Runtime.InteropServices
,我按以下方式导入 DLL:
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool CryptAcquireContext(ref IntPtr hProv, string pszContainer, string pszProvider, uint dwProvType, uint dwFlags);
要调用该函数,我使用以下代码:
IntPtr handelTest = new IntPtr();
uint CRYPt_VERIFYCONTEXT = 0xF0000000;
uint PROV_RsA_FULL = 1;
bool res = CryptAcquireContext(ref handelTest, null, "MS_ENHANCED_PROV", PROV_RsA_FULL, CRYPt_VERIFYCONTEXT);
if (!res)
{
int a = Marshal.GetLastWin32Error();
Console.WriteLine("Error in Acqired, CryptAcquireContext function\n");
return;
}
Console.WriteLine("Key Context Acquired\n");
但是,出现错误res==false
。
我的代码有什么问题?
这不是 P/Invoke 问题。参数不好,GetLastError(a)是NTE_KEYSET_NOT_DEF / 0x80090019,也就是"The requested provider does not exist.".
将 null
作为提供商名称参数传递,或使用有效的提供商名称。
但是,请注意我会这样定义函数(确保 unicode,第一个参数是 out
,而不是 ref
):
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static extern bool CryptAcquireContext(out IntPtr hProv, string pszContainer, string pszProvider, uint dwProvType, uint dwFlags);