如何在类似于 C# 的 C++ 中获取 HWID

How to get HWID in c++ simular to c#

在 c# 中使用此代码:

WindowsIdentity.GetCurrent().User.Value;

并获得输出:

S-1-5-21-3050176684-2277112922-4090480026-1001

如何在 C++ 中获得相同的输出?

下面是一些代码,说明如何使用 LookupAccountName (Link to API) 在本地计算机上获取帐户名的 SID:

#include <windows.h>
#include <iostream>
#include <sddl.h>

LPCWSTR GetSid(LPCWSTR szAccountName)
{
    LPWSTR pszRet = NULL;

    DWORD dwDomainSize = 32, dwSidSize = 32;
    LPWSTR pszDomainName = new WCHAR[dwDomainSize];
    unsigned char* pSid = new unsigned char[dwSidSize];

    while (true)
    {
        SID_NAME_USE sidType;
        DWORD dwDomainSizeTmp = dwDomainSize, dwSidSizeTmp = dwSidSize;
        if (LookupAccountNameW(NULL, szAccountName, (PSID)pSid,
            &dwSidSizeTmp, pszDomainName, &dwDomainSizeTmp, &sidType))
        {
            LPWSTR pszTmp;
            if (ConvertSidToStringSidW(pSid, &pszTmp))
            {
                const int buffLen = wcslen(pszTmp) + 1;
                pszRet = new WCHAR[buffLen];
                wcscpy_s(pszRet, buffLen, pszTmp);
                LocalFree(pszTmp);
            }
            break;
        }
        else
        {
            if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
            {
                if (dwDomainSizeTmp > dwDomainSize)
                {
                    delete[] pszDomainName;
                    pszDomainName = new WCHAR[dwDomainSizeTmp];
                    dwDomainSize = dwDomainSizeTmp;
                }
                if (dwSidSizeTmp > dwSidSize)
                {
                    delete[] pSid;
                    pSid = new unsigned char[dwSidSizeTmp];
                    dwSidSize = dwSidSizeTmp;
                }
            }
            else
            {
                break;
            }
        }
    }

    delete[] pszDomainName;
    delete[] pSid;

    return pszRet;
}

int main()
{
    LPCWSTR ret = GetSid(L"andy");
    if (ret)
    {
        std::wcout << L"SID for \"andy\" is: " << ret << std::endl;
        delete[] ret;
    }
    else
    {
        std::wcout << L"Failed to get SID for \"andy\"" << std::endl;
    }
    return 0;
}