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

784 views Asked by At

Using this code in c#:

WindowsIdentity.GetCurrent().User.Value;

And getting output:

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

How to get same output in c++?

1

There are 1 answers

0
Andy On BEST ANSWER

Here is some code on how you can get the SID for an account name on the local computer using LookupAccountName (Link to API):

#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;
}