c# - 帮助 CredEnumerate

标签 c# windows security winapi

作为 this 的后续行动问题 我希望有人可以帮助 CredEnumerate应用程序接口(interface)。

据我从文档中了解到,PCREDENTIALS out 参数是一个“指向凭证指针数组的指针”。我能够使用 C# 成功调用 CredEnumerate API,但我不确定如何将 PCREDENTIALS 转换为有用的东西(如凭据列表)。

编辑:这是我正在使用的代码:

        int count = 0;
        IntPtr pCredentials = IntPtr.Zero;
        bool ret = false;
        ret = CredEnumerate(null, 0, out count, out pCredentials);
        if (ret != false)
        {
            IntPtr[] credentials = new IntPtr[count];
            IntPtr p = pCredentials;
            for (int i = 0; i < count; i++)
            {
                p = new IntPtr(p.ToInt32() + i);
                credentials[i] = Marshal.ReadIntPtr(p);
            }
            List<Credential> creds = new List<Credential>(credentials.Length);
            foreach (IntPtr ptr in credentials)
            {
                creds.Add((Credential)Marshal.PtrToStructure(ptr, typeof(Credential)));
            }
        }

不幸的是,虽然这适用于数组中的第一个凭据——它被正确生成并添加到列表中——随后的数组项在 Marshal.PtrToStructure 中炸弹并出现以下错误:

试图读取或写入 protected 内存。这通常表明其他内存已损坏。

有什么想法吗?任何人?布勒?

最佳答案

您需要取消引用指向数组的指针以获取数组,然后对于数组中的每个项目您都需要取消引用该项目以获取 PCREDENTIALS 实例。

我找到了 this post with some example code执行你想做的事情:

[DllImport("advapi32", SetLastError = true, CharSet=CharSet.Unicode)]
static extern bool CredEnumerate(string filter, int flag, out int count, out IntPtr
pCredentials);

...

int count = 0;
IntPtr pCredentials = IntPtr.Zero;
IntPtr[] credentials = null;
bool ret = CredEnumerate(null, 0, out count, out pCredentials);
if (ret != false)
{
    credentials = new IntPtr[count];
    IntPtr p = pCredentials;
    for (int n = 0; n < count; n++)
    {
        credentials[n] = Marshal.ReadIntPtr(pCredentials,
           n * Marshal.SizeOf(typeof(IntPtr)));
    }
} 
else
// failed....

然后对于每个指针,您需要使用 Marshal.PtrToStructure 将指针取消引用到 PCREDENTIALS 结构实例中(抱歉,我找不到 的 typedef PCREDENTIALS 在任何地方,我假设您拥有它 - 如果您确实拥有它,那么在定义它时不要忘记正确的 MarshalAs 属性和 StructLayout 属性):

// assuming you have declared struct PCREDENTIALS
var creds = new List<PCREDENTIALS>(credentials.Length);
foreach (var ptr in credentials)
{
    creds.Add((PCREDENTIALS)Marshal.PtrToStructure(ptr, typeof(PCREDENTIALS)));
}

您显然希望结合示例和 PtrToStructure 代码以获得最佳结果,但我想保持示例的完整性。

关于c# - 帮助 CredEnumerate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/254980/

相关文章:

c# - 更改 wpf 中堆栈面板的子索引

security - RESTful API 中的 API key 、HTTP 身份验证与 OAuth

security - 什么是创建可逆哈希的好方法/功能?

c# - 如何生成一次性密码 (OTP/HOTP)?

c# - 空引用异常(从 mysql 下载 BLOB 文件)

c# - 用于黑白棋游戏的简单而有用的 AI 的想法(又名 : reversi)

c# - ValueInjecter 不同类型/属性名称

r - 我得到 'Error: '\U' used without hex digits in string starting ""C :\U"' when starting R

windows - 在运行 Excel 之前动态设置环境变量的正确方法是什么?

php - 在 Windows 上为要在 PHP 中使用的 C++ 静态库创建 .so 文件