0

Was recently working for a client and need to read a value from registry. So I wanted to start off by trying something simple, reading the system Guid from the registry. This is the code that I'm using and I'm having trouble figuring out how to read certain data properly. I found out how to read DWORD's from here but that doesn't work with reading the system Guid from registry. Also, I'm compiling for 64-bit. Here is the code that I've been using

#include <iostream>
#include <string>
#include <Windows.h>
#include <processthreadsapi.h>
#include <tchar.h>
#include <cstring>
int main()
{
    DWORD val;
    DWORD dataSize = sizeof(val);
    if (ERROR_SUCCESS == RegGetValueA(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Cryptography", "MachineGuid", RRF_RT_ANY, nullptr, &val, &dataSize))
    {
        printf("Value is %i\n", val);
    }
    else
    {
        printf("Read Error");
    };
    system("pause");
    return 1;
};

It seems like no matter what I try, I keep getting the Read Error. I've been trying new things and reading articles online for the past hour and 15 minutes-ish. Decided to make a post and see if anyone could help me out. Any help is appreciated! (Also, I used Visual Studio, should you need to know for any reason). Thanks in advance!

Zero03
  • 27
  • 6
  • Try storing the error code and printing that. Isn't it `ERROR_MORE_DATA` (234)? The specified value is a string longer than 4 characters in my environment. – MikeCAT Feb 23 '21 at 07:32
  • 1
    Reference: [RegGetValueA function (winreg.h) - Win32 apps | Microsoft Docs](https://learn.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-reggetvaluea) – MikeCAT Feb 23 '21 at 07:32
  • Yeah, I'm getting the same error code now. Not entirely sure how to go about fixing it though. Do you think it's a problem with my dataSize variable? – Zero03 Feb 23 '21 at 07:37
  • No. It should be a problem with the `val` variable. It should have enough size. – MikeCAT Feb 23 '21 at 07:37

1 Answers1

2

The value MachineGuid in the key SOFTWARE\Microsoft\Cryptography in my environment is a string longer than 4 characters, not a DWORD value.

You have to allocate enough resion to read the value. Otherwise, ERROR_MORE_DATA will be returned as documented.

#include <cstdio>
#include <cstdlib>
#include <Windows.h>
int main()
{
    char val[128];
    DWORD dataSize = sizeof(val);
    if (ERROR_SUCCESS == RegGetValueA(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Cryptography", "MachineGuid", RRF_RT_ANY, nullptr, &val, &dataSize))
    {
        printf("Value is %.*s\n", (int)dataSize, val);
    }
    else
    {
        printf("Read Error");
    };
    system("pause");
    return 1;
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70