Koray ÜSTÜNDAĞ

KORAY ÜSTÜNDAĞ

C++ Win32 Rastgele Parola Üretici

Merhaba, Bugün sizlerle C++ ve Win32 API kullanarak basit bir rastgele parola üretici uygulaması oluşturmanın nasıl yapılabileceğini paylaşmak istiyorum. Bu yazıda, C++ programlama dilini kullanarak Windows işletim sisteminde çalışacak bir uygulama geliştireceğiz.

Şimdi ilk önce GUI ile başlamak istiyorum. Basit bir kullanıcı arayüzü tasarlayacağız. 

Görsel Arayüz

Arayüz Kodları:

main.cpp dosyamızı oluşturalım. Projenin tamamında kullanacağımız kütüphaneleri ekleyelim.

				
					#include <Windows.h>
#include <locale>
#include <string>
#include <codecvt>
#include <iomanip>
#include <sstream>
#include <random>
				
			

Şimdi tasarım için id tanımlaması yapalım.

				
					#define WINDOW_WIDTH 588    // Pencere genişliği
#define WINDOW_HEIGHT 110   // pencere yüksekliği
#define EDIT_BOX_ID 101     // Parolaların yazacağı textbox
#define BUTTON_ONE_ID 102   // Generate butonu
#define BUTTON_TWO_ID 103   // Copy butonu
#define EDIT_BOX_TWO_ID 104 // Uzunluk textbox
#define LABEL_ONE_ID 105    // Uzunluk label
LRESULT CALLBACK WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
				
			

Şimdi Font oluşturucu bir metot yazalım.

				
					HFONT CreateFontNow(int fontSize, const char* fontName)
{
    return CreateFontA(fontSize, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, ANSI_CHARSET,
        OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
        DEFAULT_PITCH | FF_SWISS, fontName);
}
				
			

Şimdi rastgele üretim için olan kodları yazıyoruz.

				
					std::random_device rd;
std::mt19937 rng(rd());
				
			

Şimdi WinMain metotunu yazabiliriz.

				
					int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    WNDCLASSEX wc;
    wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = 0;
    wc.lpfnWndProc = WndProc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = hInstance;
    wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
    wc.lpszMenuName = NULL;
    wc.lpszClassName = L"PasswordGeneratorCLASS";
    wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);

    if (!RegisterClassEx(&wc))
    {
        MessageBox(NULL, L"Failed to register window class!", L"Error", MB_ICONERROR | MB_OK);
        return 0;
    }

    HWND hwnd = CreateWindowEx(
        0,
        L"PasswordGeneratorCLASS",
        L"Password Generator",
        WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX,
        CW_USEDEFAULT, CW_USEDEFAULT,
        WINDOW_WIDTH, WINDOW_HEIGHT,
        NULL, NULL, hInstance, NULL
    );

    if (hwnd == NULL)
    {
        MessageBox(NULL, L"Could not create window!", L"Error", MB_ICONERROR | MB_OK);
        return 0;
    }

    ShowWindow(hwnd, nCmdShow);
    UpdateWindow(hwnd);

    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return 0;
}
				
			

Şimdi hata mesajlarını ekrana yazdıracak bir metot yazalım.

				
					void ShowErrorMessage(const wchar_t* msg, const wchar_t* head)
{
    MessageBox(NULL, msg, head, MB_ICONERROR | MB_OK);
}
				
			

Şimdi uzunluk textbox içindeki yazıyı int olarak alalım.

				
					int GetIntFromTextbox(HWND hwndTextbox)
{
    const int MAX_TEXT_LEN = 10;

    WCHAR text[MAX_TEXT_LEN + 1] = {};

    int len = GetWindowText(hwndTextbox, text, MAX_TEXT_LEN);

    int value = 0;
    
    try
    {
        value = std::stoi(text);
    }
    catch (const std::exception&)
    {
        value = 0;
    }

    return value;
}
				
			

Şimdi ise Win32 API kullanarak CSP bağlantısı kuralım ve rastgele parola üretelim.

				
					void GeneratePassword(HWND textBox, HWND passwordBox)
{
    HCRYPTPROV hProvider;
    if (!CryptAcquireContext(&hProvider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
    {
        ShowErrorMessage(L"Failed to connect to CSP!", L"Cryptographic Service Provider");
        return;
    }
    const int PASSWORD_LENGTH = GetIntFromTextbox(passwordBox);
    const char CHARACTERS[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+-=[]{};:'\",./<>?\\|";
    std::uniform_int_distribution<> characterDist(0, sizeof(CHARACTERS) - 2);
    std::string passwordData(PASSWORD_LENGTH, '\0');
    for (int i = 0; i < PASSWORD_LENGTH; i++)
    {
        char character;
        if (!CryptGenRandom(hProvider, sizeof(char), reinterpret_cast<BYTE*>(static_cast<void*>(&character))))
        {
            ShowErrorMessage(L"Random character could not be selected!", L"Error");
            CryptReleaseContext(hProvider, 0);
            return;
        }
        passwordData[i] = CHARACTERS[characterDist(rng)];
    }
    SetWindowTextA(textBox, passwordData.c_str());
    CryptReleaseContext(hProvider, 0);
}
				
			

Parola üretimi bitti. Şimdi de oluşturulan parolayı kopyalayan bir metot yazalım.

				
					void CopyToClipboard(HWND textBox)
{
    int length = GetWindowTextLength(textBox) + 1;
    char* buffer = new char[length];
    GetWindowTextA(textBox, buffer, length);

    if (OpenClipboard(NULL))
    {
        EmptyClipboard();
        HGLOBAL clipData = GlobalAlloc(GMEM_MOVEABLE, length);
        if (clipData != NULL) {
            char* data = (char*)GlobalLock(clipData);
            if (data != NULL)
            {
                if (strncpy_s(data, length, buffer, length - 1) == 0)
                {
                    GlobalUnlock(clipData);
                    SetClipboardData(CF_TEXT, clipData);
                }
            }
        }
        CloseClipboard();
    }
    delete[] buffer;
}
				
			

Son olarak CALLBACK metotumuzu yazıyoruz.

				
					LRESULT CALLBACK WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
    case WM_CREATE:
    {
        HWND hwndEditBox = CreateWindowEx(
            WS_EX_CLIENTEDGE,
            L"EDIT",
            L"",
            WS_VISIBLE | WS_CHILD | ES_AUTOHSCROLL,
            12, 12, 548, 20,
            hwnd,
            (HMENU)EDIT_BOX_ID,
            (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE),
            NULL
        );

        HWND hwndEditBoxTwo = CreateWindowEx(
            WS_EX_CLIENTEDGE,
            L"EDIT",
            L"16",
            WS_VISIBLE | WS_CHILD | ES_AUTOHSCROLL | ES_NUMBER,
            110, 40, 71, 20,
            hwnd,
            (HMENU)EDIT_BOX_TWO_ID,
            (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE),
            NULL
        );

        HWND hwndLabel = CreateWindowEx(
            0,          // Genişletilmiş stil (burada kullanılmamıştır)
            L"STATIC",  // Sınıf adı
            L"Password Length:", // Etiket metni
            WS_VISIBLE | WS_CHILD, // Stiller
            12, 43, 92, 13, // Konum ve boyut
            hwnd, // Üst öğe HWND'si
            (HMENU)LABEL_ONE_ID, // Öğe menüsü (burada kullanılmamıştır)
            (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE),  // Uygulama tanıtıcısı
            NULL        // Ek veri (burada kullanılmamıştır)
        );
        SetLayeredWindowAttributes(hwndLabel, RGB(255, 255, 255), 128, LWA_COLORKEY);
        SendMessage(hwndEditBox, WM_SETFONT, (WPARAM)CreateFontNow(16, "Microsoft Sans Serif"), TRUE);
        SendMessage(hwndEditBoxTwo, WM_SETFONT, (WPARAM)CreateFontNow(16, "Microsoft Sans Serif"), TRUE);
        SendMessage(hwndLabel, WM_SETFONT, (WPARAM)CreateFontNow(14, "Microsoft Sans Serif"), TRUE);


        HWND hwndButtonOne = CreateWindowEx(
            0,
            L"BUTTON",
            L"Generate",
            WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_FLAT,
            404, 38, 75, 23,
            hwnd,
            (HMENU)BUTTON_ONE_ID,
            (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE),
            NULL
        );

        HWND hwndButtonTwo = CreateWindowEx(
            0,
            L"BUTTON",
            L"Copy",
            WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_FLAT,
            485, 38, 75, 23,
            hwnd,
            (HMENU)BUTTON_TWO_ID,
            (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE),
            NULL
        );
        break;
    }

    case WM_CHAR: {
        // Sadece sayısal karakterlerin kabul edilmesi
        if (wParam >= '0' && wParam <= '9') {
            // Karakter kabul edildi
        }
        else {
            // Karakter kabul edilmedi, işlenmesi engellendi
            return 0;
        }
        break;
    }
    case WM_KEYDOWN: {
        if (wParam == VK_RETURN) {
            // Enter tuşu kabul edildi
        }
        else {
            // Diğer tuşların girişi engellendi
            return 0;
        }
        break;
    }

    case WM_COMMAND:
    {
        if (LOWORD(wParam) == BUTTON_ONE_ID)
        {
            HWND hwndEditBox = GetDlgItem(hwnd, EDIT_BOX_ID);
            HWND hwndEditBoxTwo = GetDlgItem(hwnd, EDIT_BOX_TWO_ID);
            GeneratePassword(hwndEditBox, hwndEditBoxTwo);
        }
        else if (LOWORD(wParam) == BUTTON_TWO_ID)
        {
            HWND hwndEditBox = GetDlgItem(hwnd, EDIT_BOX_ID);
            CopyToClipboard(hwndEditBox);
        }
        break;
    }
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hwnd, uMsg, wParam, lParam);
    }
    return 0;
}

				
			

Geriye kalan tek şey programı derlemek. Aşağıdan main.cpp dosyasının tüm kodlarına ulaşabilirsiniz.

				
					#include <Windows.h>
#include <locale>
#include <string>
#include <codecvt>
#include <iomanip>
#include <sstream>
#include <random>

#define WINDOW_WIDTH 588
#define WINDOW_HEIGHT 110
#define EDIT_BOX_ID 101
#define BUTTON_ONE_ID 102
#define BUTTON_TWO_ID 103
#define EDIT_BOX_TWO_ID 104
#define LABEL_ONE_ID 105

LRESULT CALLBACK WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);

std::random_device rd;
std::mt19937 rng(rd());

HFONT CreateFontNow(int fontSize, const char* fontName)
{
    return CreateFontA(fontSize, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, ANSI_CHARSET,
        OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
        DEFAULT_PITCH | FF_SWISS, fontName);
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    WNDCLASSEX wc;
    wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = 0;
    wc.lpfnWndProc = WndProc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = hInstance;
    wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
    wc.lpszMenuName = NULL;
    wc.lpszClassName = L"PasswordGeneratorCLASS";
    wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);

    if (!RegisterClassEx(&wc))
    {
        MessageBox(NULL, L"Failed to register window class!", L"Error", MB_ICONERROR | MB_OK);
        return 0;
    }

    HWND hwnd = CreateWindowEx(
        0,
        L"PasswordGeneratorCLASS",
        L"Password Generator",
        WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX,
        CW_USEDEFAULT, CW_USEDEFAULT,
        WINDOW_WIDTH, WINDOW_HEIGHT,
        NULL, NULL, hInstance, NULL
    );

    if (hwnd == NULL)
    {
        MessageBox(NULL, L"Could not create window!", L"Error", MB_ICONERROR | MB_OK);
        return 0;
    }

    ShowWindow(hwnd, nCmdShow);
    UpdateWindow(hwnd);

    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return 0;
}

void ShowErrorMessage(const wchar_t* msg, const wchar_t* head)
{
    MessageBox(NULL, msg, head, MB_ICONERROR | MB_OK);
}

int GetIntFromTextbox(HWND hwndTextbox)
{
    const int MAX_TEXT_LEN = 10;

    WCHAR text[MAX_TEXT_LEN + 1] = {};

    int len = GetWindowText(hwndTextbox, text, MAX_TEXT_LEN);

    int value = 0;
    
    try
    {
        value = std::stoi(text);
    }
    catch (const std::exception&)
    {
        value = 0;
    }

    return value;
}

void GeneratePassword(HWND textBox, HWND passwordBox)
{
    HCRYPTPROV hProvider;
    if (!CryptAcquireContext(&hProvider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
    {
        ShowErrorMessage(L"Failed to connect to CSP!", L"Cryptographic Service Provider");
        return;
    }
    const int PASSWORD_LENGTH = GetIntFromTextbox(passwordBox);
    const char CHARACTERS[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+-=[]{};:'\",./<>?\\|";
    std::uniform_int_distribution<> characterDist(0, sizeof(CHARACTERS) - 2);
    std::string passwordData(PASSWORD_LENGTH, '\0');
    for (int i = 0; i < PASSWORD_LENGTH; i++)
    {
        char character;
        if (!CryptGenRandom(hProvider, sizeof(char), reinterpret_cast<BYTE*>(static_cast<void*>(&character))))
        {
            ShowErrorMessage(L"Random character could not be selected!", L"Error");
            CryptReleaseContext(hProvider, 0);
            return;
        }
        passwordData[i] = CHARACTERS[characterDist(rng)];
    }
    SetWindowTextA(textBox, passwordData.c_str());
    CryptReleaseContext(hProvider, 0);
}


void CopyToClipboard(HWND textBox)
{
    int length = GetWindowTextLength(textBox) + 1;
    char* buffer = new char[length];
    GetWindowTextA(textBox, buffer, length);

    if (OpenClipboard(NULL))
    {
        EmptyClipboard();
        HGLOBAL clipData = GlobalAlloc(GMEM_MOVEABLE, length);
        if (clipData != NULL) {
            char* data = (char*)GlobalLock(clipData);
            if (data != NULL)
            {
                if (strncpy_s(data, length, buffer, length - 1) == 0)
                {
                    GlobalUnlock(clipData);
                    SetClipboardData(CF_TEXT, clipData);
                }
            }
        }
        CloseClipboard();
    }
    delete[] buffer;
}

LRESULT CALLBACK WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
    case WM_CREATE:
    {
        HWND hwndEditBox = CreateWindowEx(
            WS_EX_CLIENTEDGE,
            L"EDIT",
            L"",
            WS_VISIBLE | WS_CHILD | ES_AUTOHSCROLL,
            12, 12, 548, 20,
            hwnd,
            (HMENU)EDIT_BOX_ID,
            (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE),
            NULL
        );

        HWND hwndEditBoxTwo = CreateWindowEx(
            WS_EX_CLIENTEDGE,
            L"EDIT",
            L"16",
            WS_VISIBLE | WS_CHILD | ES_AUTOHSCROLL | ES_NUMBER,
            110, 40, 71, 20,
            hwnd,
            (HMENU)EDIT_BOX_TWO_ID,
            (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE),
            NULL
        );

        HWND hwndLabel = CreateWindowEx(
            0,          // Genişletilmiş stil (burada kullanılmamıştır)
            L"STATIC",  // Sınıf adı
            L"Password Length:", // Etiket metni
            WS_VISIBLE | WS_CHILD, // Stiller
            12, 43, 92, 13, // Konum ve boyut
            hwnd, // Üst öğe HWND'si
            (HMENU)LABEL_ONE_ID, // Öğe menüsü (burada kullanılmamıştır)
            (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE),  // Uygulama tanıtıcısı
            NULL        // Ek veri (burada kullanılmamıştır)
        );
        SetLayeredWindowAttributes(hwndLabel, RGB(255, 255, 255), 128, LWA_COLORKEY);
        SendMessage(hwndEditBox, WM_SETFONT, (WPARAM)CreateFontNow(16, "Microsoft Sans Serif"), TRUE);
        SendMessage(hwndEditBoxTwo, WM_SETFONT, (WPARAM)CreateFontNow(16, "Microsoft Sans Serif"), TRUE);
        SendMessage(hwndLabel, WM_SETFONT, (WPARAM)CreateFontNow(14, "Microsoft Sans Serif"), TRUE);


        HWND hwndButtonOne = CreateWindowEx(
            0,
            L"BUTTON",
            L"Generate",
            WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_FLAT,
            404, 38, 75, 23,
            hwnd,
            (HMENU)BUTTON_ONE_ID,
            (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE),
            NULL
        );

        HWND hwndButtonTwo = CreateWindowEx(
            0,
            L"BUTTON",
            L"Copy",
            WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON | BS_FLAT,
            485, 38, 75, 23,
            hwnd,
            (HMENU)BUTTON_TWO_ID,
            (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE),
            NULL
        );
        break;
    }

    case WM_CHAR: {
        // Sadece sayısal karakterlerin kabul edilmesi
        if (wParam >= '0' && wParam <= '9') {
            // Karakter kabul edildi
        }
        else {
            // Karakter kabul edilmedi, işlenmesi engellendi
            return 0;
        }
        break;
    }
    case WM_KEYDOWN: {
        if (wParam == VK_RETURN) {
            // Enter tuşu kabul edildi
        }
        else {
            // Diğer tuşların girişi engellendi
            return 0;
        }
        break;
    }

    case WM_COMMAND:
    {
        if (LOWORD(wParam) == BUTTON_ONE_ID)
        {
            HWND hwndEditBox = GetDlgItem(hwnd, EDIT_BOX_ID);
            HWND hwndEditBoxTwo = GetDlgItem(hwnd, EDIT_BOX_TWO_ID);
            GeneratePassword(hwndEditBox, hwndEditBoxTwo);
        }
        else if (LOWORD(wParam) == BUTTON_TWO_ID)
        {
            HWND hwndEditBox = GetDlgItem(hwnd, EDIT_BOX_ID);
            CopyToClipboard(hwndEditBox);
        }
        break;
    }
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hwnd, uMsg, wParam, lParam);
    }
    return 0;
}

				
			

Okuduğunuz için teşekkür ederim. Umarım yardımcı olmuştur size.

Şimdi Paylaş

Facebook
Twitter
LinkedIn

Bir cevap yazın

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir