Skip to content

Commit 0cfa91d

Browse files
committed
code up
1 parent 50ff06f commit 0cfa91d

36 files changed

Lines changed: 10672 additions & 0 deletions
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>WinExe</OutputType>
5+
<TargetFramework>net8.0-windows</TargetFramework>
6+
<UseWindowsForms>true</UseWindowsForms>
7+
<ImplicitUsings>enable</ImplicitUsings>
8+
<Nullable>enable</Nullable>
9+
</PropertyGroup>
10+
11+
</Project>

code/KeyGenerator/MainForm.Designer.cs

Lines changed: 141 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

code/KeyGenerator/MainForm.cs

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
using System;
2+
using System.IO;
3+
using System.Security.Cryptography;
4+
using System.Text;
5+
using System.Windows.Forms;
6+
7+
namespace KeyGenerator
8+
{
9+
public partial class MainForm : Form
10+
{
11+
public MainForm()
12+
{
13+
InitializeComponent();
14+
this.generateButton.Click += new System.EventHandler(this.generateButton_Click);
15+
this.copyPublicKeyButton.Click += new System.EventHandler(this.copyPublicKeyButton_Click);
16+
17+
try
18+
{
19+
// Display the public key for the admin to copy into the main application
20+
this.publicKeyTextBox.Text = LicenseGenerator.GetPublicKey();
21+
}
22+
catch (Exception ex)
23+
{
24+
MessageBox.Show($"A critical error occurred during key generation: {ex.Message}\n\nThe application will now close.", "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
25+
// Close the form immediately if key generation fails.
26+
// Using Load event to close because constructor is too early.
27+
this.Load += (s, e) => this.Close();
28+
}
29+
}
30+
31+
private void generateButton_Click(object? sender, EventArgs e)
32+
{
33+
string encryptedMachineId = this.machineIdTextBox.Text.Trim();
34+
if (string.IsNullOrWhiteSpace(encryptedMachineId))
35+
{
36+
MessageBox.Show("Please enter the user's Encrypted Machine ID.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
37+
return;
38+
}
39+
40+
try
41+
{
42+
this.licenseKeyTextBox.Text = LicenseGenerator.GenerateLicenseKey(encryptedMachineId);
43+
}
44+
catch (Exception ex)
45+
{
46+
MessageBox.Show($"An error occurred: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
47+
}
48+
}
49+
50+
private void copyPublicKeyButton_Click(object? sender, EventArgs e)
51+
{
52+
Clipboard.SetText(this.publicKeyTextBox.Text);
53+
MessageBox.Show("Public key copied to clipboard.", "Copied", MessageBoxButtons.OK, MessageBoxIcon.Information);
54+
}
55+
}
56+
57+
public static class LicenseGenerator
58+
{
59+
private const string PrivateKeyFileName = "private_key.b64";
60+
private static readonly RSA _privateKey;
61+
62+
static LicenseGenerator()
63+
{
64+
// This static constructor is called once when the class is first accessed.
65+
if (File.Exists(PrivateKeyFileName))
66+
{
67+
// If a key file exists, load it.
68+
string privateKeyBase64 = File.ReadAllText(PrivateKeyFileName);
69+
_privateKey = RSA.Create();
70+
_privateKey.ImportRSAPrivateKey(Convert.FromBase64String(privateKeyBase64), out _);
71+
}
72+
else
73+
{
74+
// If no key file exists, generate a new one and save it.
75+
_privateKey = RSA.Create(2048); // Generate a new 2048-bit RSA key.
76+
byte[] privateKeyBytes = _privateKey.ExportRSAPrivateKey();
77+
string privateKeyBase64 = Convert.ToBase64String(privateKeyBytes);
78+
File.WriteAllText(PrivateKeyFileName, privateKeyBase64);
79+
}
80+
}
81+
82+
public static string GetPublicKey()
83+
{
84+
// Export the public part of the key in Base64 format.
85+
byte[] publicKeyBytes = _privateKey.ExportRSAPublicKey();
86+
return Convert.ToBase64String(publicKeyBytes);
87+
}
88+
89+
public static string GenerateLicenseKey(string encryptedMachineId)
90+
{
91+
// Decrypt the user's machine ID.
92+
byte[] encryptedBytes = Convert.FromBase64String(encryptedMachineId);
93+
byte[] decryptedBytes = _privateKey.Decrypt(encryptedBytes, RSAEncryptionPadding.OaepSHA256);
94+
string machineId = Encoding.UTF8.GetString(decryptedBytes);
95+
96+
// Sign the decrypted machine ID to create the license key.
97+
byte[] machineIdBytes = Encoding.UTF8.GetBytes(machineId);
98+
byte[] signature = _privateKey.SignData(machineIdBytes, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
99+
return Convert.ToBase64String(signature);
100+
}
101+
}
102+
}

code/KeyGenerator/Program.cs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
using System;
2+
using System.Windows.Forms;
3+
4+
namespace KeyGenerator
5+
{
6+
internal static class Program
7+
{
8+
/// <summary>
9+
/// The main entry point for the application.
10+
/// </summary>
11+
[STAThread]
12+
static void Main()
13+
{
14+
Application.SetHighDpiMode(HighDpiMode.SystemAware);
15+
Application.EnableVisualStyles();
16+
Application.SetCompatibleTextRenderingDefault(false);
17+
Application.Run(new MainForm());
18+
}
19+
}
20+
}

code/bot_license/bot.py

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
import logging
2+
from telegram import Update, BotCommand
3+
from telegram.ext import Application, CommandHandler, ContextTypes
4+
5+
from license_generator import generate_license_key, get_public_key_base64
6+
7+
# --- Configuration ---
8+
TELEGRAM_API_KEY = "apikey"
9+
10+
# Enable logging
11+
logging.basicConfig(
12+
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
13+
)
14+
logger = logging.getLogger(__name__)
15+
16+
17+
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
18+
welcome_text = (
19+
"Welcome to the License Key Generator Bot!\n\n"
20+
"Commands available:\n"
21+
"• /generate <EncryptedMachineID> → Generate a license key\n"
22+
"• /publickey → Show the Public Key for app compilation\n\n"
23+
"Example:\n"
24+
"/generate ABCDE12345..."
25+
)
26+
await update.message.reply_text(welcome_text)
27+
28+
29+
async def generate(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
30+
if not context.args:
31+
await update.message.reply_text(
32+
"Please provide an Encrypted Machine ID after the command.\n"
33+
"Example: /generate ABCDE12345..."
34+
)
35+
return
36+
37+
encrypted_machine_id = context.args[0]
38+
user = update.effective_user
39+
logger.info(f"User {user.username} ({user.id}) requested a key for machine ID: {encrypted_machine_id}")
40+
41+
try:
42+
license_key = generate_license_key(encrypted_machine_id)
43+
response_text = f"License Key Generated Successfully:\n\n`{license_key}`"
44+
await update.message.reply_text(response_text, parse_mode='MarkdownV2')
45+
logger.info(f"Successfully generated key for machine ID: {encrypted_machine_id}")
46+
except Exception as e:
47+
logger.error(f"Failed to generate key for machine ID: {encrypted_machine_id}. Error: {e}")
48+
await update.message.reply_text(
49+
"An error occurred while generating the license key. "
50+
"Please ensure the Encrypted Machine ID is correct and try again."
51+
)
52+
53+
54+
async def publickey(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
55+
"""Sends the public key in Base64 for app compilation."""
56+
try:
57+
public_key = get_public_key_base64()
58+
response_text = (
59+
"Public Key (Base64, ready for C#):\n\n"
60+
f"{public_key}"
61+
)
62+
# Use HTML format to avoid MarkdownV2 escaping issues
63+
await update.message.reply_text(response_text)
64+
logger.info("Public key sent successfully.")
65+
except Exception as e:
66+
logger.error(f"Error retrieving public key: {e}", exc_info=True)
67+
await update.message.reply_text("An error occurred while retrieving the public key.")
68+
69+
70+
async def post_init(application: Application) -> None:
71+
commands = [
72+
BotCommand("start", "Show welcome message and instructions"),
73+
BotCommand("generate", "Generate a new license key from a machine ID"),
74+
BotCommand("publickey", "Show the public key for app compilation"),
75+
]
76+
await application.bot.set_my_commands(commands)
77+
78+
79+
def main() -> None:
80+
application = Application.builder().token(TELEGRAM_API_KEY).post_init(post_init).build()
81+
82+
application.add_handler(CommandHandler("start", start))
83+
application.add_handler(CommandHandler("generate", generate))
84+
application.add_handler(CommandHandler("publickey", publickey))
85+
86+
logger.info("Starting bot...")
87+
application.run_polling()
88+
89+
90+
if __name__ == "__main__":
91+
main()

0 commit comments

Comments
 (0)