【问题标题】:RegCreateKeyEx succeeding, but no key addedRegCreateKeyEx 成功,但未添加密钥
【发布时间】:2021-03-05 10:40:44
【问题描述】:

我正在尝试在 Windows 上进行 C++ 编程以进行逆向工程,但我一直在尝试拥有 Windows 注册表项。 RegCreateKey 和 RegSetValueEx 函数返回 ERROR_SUCCESS,但检查注册表时缺少键。

代码如下:

void AddRunKey() {
    wchar_t subkey[512];
    wchar_t cmd[512];
    wcscpy_s(subkey, L"Test");
    wcscpy_s(cmd, L"%windir%\system32\cmd.exe");

    HKEY runKey;
    long res;
    res = RegCreateKeyEx(HKEY_CURRENT_USER, L"SOFTWARE\\Microsoft\\Windows\\CurentVersion\\Run", 0, NULL, 0, KEY_ALL_ACCESS, NULL, &runKey, NULL);
    if (res != ERROR_SUCCESS) {
        std::cout << "fail\n";
    }


    res = RegSetValueEx(runKey, subkey, 0, REG_EXPAND_SZ, (BYTE*)cmd, wcslen(cmd) + 1);
    if (res != ERROR_SUCCESS) {
        std::cout << "fail\n";
    }

    RegCloseKey(runKey);

}
    
int _tmain() {
    AddRunKey();
          
}

我在 Windows 10 - 64 位虚拟机上的 Visual Studio、发布模式、64 位上编译它。运行代码时不返回错误。

打开 Windows 注册表编辑器时,在 HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run 下找不到键

是什么导致了这种行为?我该如何解决?

EDIT(更新密钥路径):RegCloseKey 返回 0

【问题讨论】:

  • reg 关闭键的返回值是?
  • RegCloseKey的返回值为0 完整路径为“Ordinateur\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run”
  • 在发布的代码中,您不会刷新您写入std::cout 的内容。您可能需要添加std::flushstd::endl。但是,如果您的程序确实在您调用 AddRunKey 后立即退出(您发布的代码表明),则不需要刷新。
  • 一个明显的错误是RegSetValueEx的最后一个参数是字节,所以应该是(wcslen(cmd) + 1) * sizeof(wchar_t)
  • 您在Run 键下创建一个值,而不是一个键(即使您将其误称为subkey)。

标签: c++ windows registry


【解决方案1】:

我发现您的代码中有几个错误。

您需要转义文件路径中的\ 字符。

您在密钥路径中拼错了CurentVersion。它需要改为CurrentVersion

无论RegCreateKeyEx() 成功还是失败,您都在无条件地调用RegSetValueEx()RegCloseKey()

您需要在RegSetValueEx()的最后一个参数中以字节而不是字符来指定值大小。

试试这个:

void AddRunKey() {
    wchar_t subkey[512];
    wchar_t cmd[512];
    wcscpy_s(subkey, L"Test");
    wcscpy_s(cmd, L"%windir%\\system32\\cmd.exe");

    HKEY runKey;
    long res = RegCreateKeyEx(HKEY_CURRENT_USER, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", 0, NULL, 0, KEY_SET_VALUE, NULL, &runKey, NULL);
    if (res != ERROR_SUCCESS) {
        std::cout << "fail\n";
    }
    else
    {
        res = RegSetValueEx(runKey, subkey, 0, REG_EXPAND_SZ, (BYTE*)cmd, (wcslen(cmd) + 1) * sizeof(cmd[0]));
        if (res != ERROR_SUCCESS) {
            std::cout << "fail\n";
        }

        RegCloseKey(runKey);
    }
}
    
int _tmain() {
    AddRunKey();
}

【讨论】:

    猜你喜欢
    • 2013-01-13
    • 1970-01-01
    • 1970-01-01
    • 2019-04-06
    • 1970-01-01
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多