//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop
#include "Unit1.h"

#include <System.SysUtils.hpp>
#include <System.StrUtils.hpp>
#include <System.Classes.hpp>

//---------------------------------------------------------------------------
#pragma package(smart_init)

#pragma resource "*.dfm"

TForm1 *Form1;

TIniFile *ini;

String StrExePath1;

static const wchar_t* kEntropy = L"KeyTool_20260414_1";

//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
	: TForm(Owner)
{

	StrExePath1 = ExtractFilePath(Application->ExeName);

	try{

	}
	catch(const Exception&){
	}

}

// ---- 文字列→DPAPI暗号→Base64文字列
static bool ProtectToBase64(const UnicodeString& plain, UnicodeString& outB64, bool machineScope = false)
{
    DATA_BLOB in   { (DWORD)(plain.Length() * sizeof(wchar_t)), (BYTE*)plain.c_str() };
    DATA_BLOB ent  { (DWORD)(wcslen(kEntropy) * sizeof(wchar_t)), (BYTE*)kEntropy };
    DATA_BLOB enc  { 0, nullptr };

    DWORD flags = CRYPTPROTECT_UI_FORBIDDEN;                // UIを出さない
    if (machineScope) flags |= CRYPTPROTECT_LOCAL_MACHINE;  // 共有PCで全ユーザー共通にしたい時のみ

    if (!CryptProtectData(&in, L"MailPass", &ent, nullptr, nullptr, flags, &enc)) {
        return false;
    }

    // Base64にする（改行なし）
    DWORD cch = 0;
    CryptBinaryToStringW(enc.pbData, enc.cbData, CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, nullptr, &cch);
    std::unique_ptr<wchar_t[]> buf(new wchar_t[cch]);
    if (!CryptBinaryToStringW(enc.pbData, enc.cbData, CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, buf.get(), &cch)) {
        LocalFree(enc.pbData);
        return false;
    }
    outB64 = UnicodeString(buf.get());
    LocalFree(enc.pbData);
    return true;
}

void __fastcall TForm1::btnSaveClick(TObject *Sender)
{

	try{

        UnicodeString b64;
		if (!ProtectToBase64(Edit1->Text, b64)) return;

		ini = new TIniFile(StrExePath1 + "config.ini");

		ini->WriteString("Mail", "Pass", b64);

		delete ini;

        ShowMessage("Mail Password を保存しました");

		Edit1->Text = "";

        Close();

		return;

	}
	catch (const Exception&) {

		return;
	}

}

//---------------------------------------------------------------------------


void __fastcall TForm1::Edit1Enter(TObject *Sender)
{
    Edit1->Text = "";
}
//---------------------------------------------------------------------------


