MenüHomeBlogMagic

Windos C++ Username und Passwort ändern

Für eine Applikation musste ich mit C++ den Benutzernamen und das Passwort für den aktuellen Benutzer ändern. Das habe ich mit den folgenden Zeilen Code erledigt:

#pragma comment(lib, "netapi32.lib")

#include <string>
#include <windows.h> 
#include <lm.h>

const std::wstring PasswordToShort(L"The password is shorter than required");
const std::wstring PasswordBad(L"The password is invalid");
const std::wstring PasswordFailed(L"Setting password failed");
const std::wstring PasswordFailedAutologin(L"Passowrd set, but setting autologin failed");

bool setUserPassword(const std::wstring& sUsername, const std::wstring& sPassword, std::wstring& sResultMessage)
{
  bool bSuccess = false;
  USER_INFO_1003 oPassword;
  oPassword.usri1003_password = const_cast<LPWSTR>(sPassword.c_str());
  DWORD dwError;
  NET_API_STATUS uStatus = NetUserSetInfo(nullptr, sUsername.c_str(), 1003, static_cast<LPBYTE>(static_cast<void*>(&oPassword)), &dwError);
  if (uStatus == NERR_Success)
  {
    bSuccess = true;
  }
  else
  {
    bSuccess = false;
    switch (uStatus)
    {
      case NERR_PasswordTooShort:
        sResultMessage = PasswordToShort;
        break;
      case NERR_BadPassword:
        sResultMessage = PasswordToShort;
        break;
      default:
        sResultMessage = PasswordFailed;
    }
  }
  return bSuccess;
}

bool setAutologin(const std::string& sUsername, const std::wstring& sPassword)
{
  bool bSuccess = false;
  HKEY hKeyReg;
  LSTATUS state = RegCreateKeyExW(
    HKEY_LOCAL_MACHINE,
    L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon",
    0,
    NULL,
    REG_OPTION_NON_VOLATILE,
    KEY_ALL_ACCESS | KEY_WOW64_64KEY,
    NULL,
    &hKeyReg,
    NULL
  );
  if (state == ERROR_SUCCESS)
  {
    state = RegSetValueExW(hKeyReg, L"DefaultUsername", 0, REG_SZ, (BYTE*) sUsername.c_str(), (sUsername.length()) * sizeof(wchar_t));
    if (state == ERROR_SUCCESS)
    {
      state = RegSetValueExW(hKeyReg, L"DefaultPassword", 0, REG_SZ, (BYTE*) sPassword.c_str(), (sPassword.length()) * sizeof(wchar_t));
      if (state == ERROR_SUCCESS)
      {
        bSuccess = true;
      }
    }
    RegCloseKey(hKeyReg);
  }
  return bSuccess;
}

Die Methode um den Autologin zu ändern habe ich auch gleich noch mit angefügt.

Permalink: https://adirmeier.de/Blog/ID_336
Tags: Blog, C/C++, password, user, Windowsvon am 2020-08-25