【发布时间】:2017-06-03 10:10:00
【问题描述】:
我想在 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。
我的代码有什么问题?
【问题讨论】:
-
c 中的字符串通常以 byte[] 结尾,并以 '\0' 结尾。 C# 字符串/字符是两个字节,具有一个私有属性,用于确定字符是一个字节还是两个字节。在 c# 中,您使用 Encode 方法库方法将字符串转换为字节并将字节转换为字符串,这会自动执行一/两个字节的打包/解包。
-
当我的参数是字符串时,我如何将字符串更改为字节,那就是错误
-
@jdweng DllImportAttribute 的
CharSet属性负责处理。 -
a的值是多少? -
MS_ENHANCED_PROV 是 wincrypt.h 中的 #define 包含实际提供程序名称,但您将其引用为字符串 ...