# --- On your server-side (or a script you run manually) for license generation ---
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding, rsa
from cryptography.hazmat.primitives import serialization
import datetime
import json
# Generate private/public key pair ONCE and keep private_key SECURE
# private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
# with open("private_key.pem", "wb") as f:
# f.write(private_key.private_bytes(
# encoding=serialization.Encoding.PEM,
# format=serialization.PrivateFormat.PKCS8,
# encryption_algorithm=serialization.NoEncryption() # Or use a password
# ))
# with open("public_key.pem", "wb") as f:
# f.write(private_key.public_key().public_bytes(
# encoding=serialization.Encoding.PEM,
# format=serialization.PublicFormat.SubjectPublicKeyInfo
# ))
# --- Function to generate a license file ---
def generate_license(user_id: str, validity_days: int, private_key_path: str = "private_key.pem"):
with open(private_key_path, "rb") as key_file:
private_key = serialization.load_pem_private_key(
key_file.read(),
password=None, # If you encrypted it
)
expiration_date = (datetime.date.today() + datetime.timedelta(days=validity_days)).isoformat()
license_data = {
"user_id": user_id,
"expires_on": expiration_date,
# "machine_id": "some_machine_fingerprint" # Optional
}
message = json.dumps(license_data, sort_keys=True).encode('utf-8')
signature = private_key.sign(
message,
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
full_license = {
"data": license_data,
"signature": signature.hex() # Store signature as hex
}
with open(f"license_{user_id}.lic", "w") as f:
json.dump(full_license, f, indent=2)
print(f"License generated for {user_id}, expires on {expiration_date}")
# Example: generate_license("user123", 30)
# --- In your packaged Python application (EXE) ---
# You would bundle 'public_key.pem' with your application
import json
import datetime
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import serialization
from cryptography.exceptions import InvalidSignature
import os
import sys # For sys.exit()
PUBLIC_KEY_FILE = "public_key.pem" # Path relative to executable if bundled
LICENSE_FILE = "license.lic" # User places this next to the EXE
def get_bundled_file_path(filename):
""" Get path to file bundled with PyInstaller """
if getattr(sys, 'frozen', False): # Running in a bundle
base_path = sys._MEIPASS # PyInstaller's temp folder
else: # Running in normal Python environment
base_path = os.path.dirname(os.path.abspath(__file__))
return os.path.join(base_path, filename)
def verify_license():
try:
with open(get_bundled_file_path(PUBLIC_KEY_FILE), "rb") as key_file:
public_key = serialization.load_pem_public_key(key_file.read())
if not os.path.exists(LICENSE_FILE):
print("Error: License file (license.lic) not found.")
return False
with open(LICENSE_FILE, "r") as f:
full_license = json.load(f)
license_data = full_license.get("data")
signature_hex = full_license.get("signature")
if not license_data or not signature_hex:
print("Error: Invalid license file format.")
return False
message = json.dumps(license_data, sort_keys=True).encode('utf-8')
signature = bytes.fromhex(signature_hex)
try:
public_key.verify(
signature,
message,
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
# Signature is valid, now check date
expires_on_str = license_data.get("expires_on")
if not expires_on_str:
print("Error: Expiration date missing from license.")
return False
expiration_date = datetime.date.fromisoformat(expires_on_str)
today = datetime.date.today()
# Optional: Check for clock tampering (basic)
# last_run_file = ".last_run_ts"
# try:
# with open(last_run_file, "r") as lrf:
# last_run_date = datetime.date.fromisoformat(lrf.read().strip())
# if today < last_run_date:
# print("Error: System clock appears to have been set back. Please correct your system time.")
# return False
# except FileNotFoundError:
# pass # First run
# except Exception:
# print("Warning: Could not verify last run time.") # Be lenient or strict
if today > expiration_date:
print(f"Error: Your license expired on {expiration_date}. Please renew your subscription.")
return False
# License is valid and not expired!
# # Update last run time (basic anti-clock tampering)
# with open(last_run_file, "w") as lrf:
# lrf.write(today.isoformat())
print("License verified successfully.")
return True
except InvalidSignature:
print("Error: License signature is invalid. The license file may have been tampered with.")
return False
except Exception as e:
print(f"Error verifying license: {e}")
return False
except FileNotFoundError:
print(f"Error: Public key file '{PUBLIC_KEY_FILE}' not found. Application cannot start.")
return False
except Exception as e:
print(f"A critical error occurred during license verification: {e}")
return False
# --- Main application ---
# if __name__ == "__main__":
# if not verify_license():
# input("Press Enter to exit.") # Keep window open to show message
# sys.exit(1)
#
# print("Application is running...")
# # ... your application's main logic here ...
# input("Application finished. Press Enter to exit.")