Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import secrets
- import os
- import sys
- # Constants
- KEY_LENGTH = 8192
- NUM_KEYS = 1024
- TOTAL_KEY_SIZE = KEY_LENGTH * NUM_KEYS
- DEFAULT_KEY_FILE = "aotpkc.key"
- def generate_big_key():
- """Generate secure giant key using cryptographic RNG with progress display"""
- print(f"Generating secure key ({NUM_KEYS} keys of {KEY_LENGTH} bytes each)...")
- print(f"Total size: {TOTAL_KEY_SIZE/1024/1024:.2f} MB")
- # Generate directly to file to avoid huge memory usage
- filename = "temp_generation.key"
- try:
- with open(filename, "wb") as f:
- for i in range(NUM_KEYS):
- f.write(secrets.token_bytes(KEY_LENGTH))
- if (i + 1) % 128 == 0:
- print(f"Generated {i+1}/{NUM_KEYS} key segments...")
- return filename
- except Exception as e:
- print(f"Key generation failed: {e}")
- return None
- def save_big_key(source_file, filename=DEFAULT_KEY_FILE):
- """Rename the generated key file to final name"""
- try:
- if os.path.exists(filename):
- os.remove(filename)
- os.rename(source_file, filename)
- print(f"Secure big key saved to {filename}")
- print(f"Key size: {os.path.getsize(filename)/1024/1024:.2f} MB")
- return True
- except Exception as e:
- print(f"Error saving key file: {e}")
- return False
- def get_key_segment(filename, seed):
- """Read only the needed key segment from disk (memory efficient)"""
- if seed < 1 or seed > NUM_KEYS:
- print(f"Error: Seed must be between 1 and {NUM_KEYS}")
- return None
- try:
- # Calculate file position
- offset = (seed - 1) * KEY_LENGTH
- with open(filename, "rb") as f:
- f.seek(offset)
- segment = f.read(KEY_LENGTH)
- if len(segment) != KEY_LENGTH:
- print(f"Error: Key segment incomplete ({len(segment)} bytes, expected {KEY_LENGTH})")
- return None
- return segment
- except FileNotFoundError:
- print(f"Error: Key file '{filename}' not found")
- except Exception as e:
- print(f"Error reading key segment: {e}")
- return None
- def otp_encrypt_bytes(plaintext, key):
- """Perform byte-level OTP encryption"""
- return bytes(p ^ k for p, k in zip(plaintext, key))
- def encrypt_interface():
- """Console interface for encryption"""
- try:
- plaintext = input("Enter plaintext to encrypt: ")
- key_file = input(f"Enter key filename (default: {DEFAULT_KEY_FILE}): ") or DEFAULT_KEY_FILE
- seed = int(input(f"Enter seed (1-{NUM_KEYS}): "))
- if not plaintext:
- print("Error: Plaintext cannot be empty")
- return
- # Only load the needed key segment (8KB instead of 8MB)
- key = get_key_segment(key_file, seed)
- if not key:
- return
- plaintext_bytes = plaintext.encode('utf-8')
- # Check if plaintext exceeds key length
- if len(plaintext_bytes) > KEY_LENGTH:
- print(f"Warning: Plaintext ({len(plaintext_bytes)} bytes) exceeds key segment length ({KEY_LENGTH} bytes)")
- print("Only the first part will be encrypted. Consider splitting your message.")
- plaintext_bytes = plaintext_bytes[:KEY_LENGTH]
- ciphertext_bytes = otp_encrypt_bytes(plaintext_bytes, key[:len(plaintext_bytes)])
- print("\n=== Encryption Results ===")
- print(f"Seed used: {seed}")
- print(f"Key file: {key_file}")
- print(f"Plaintext length: {len(plaintext_bytes)} bytes")
- print(f"Hex ciphertext: {ciphertext_bytes.hex()}")
- except ValueError:
- print("Error: Invalid seed value. Must be an integer.")
- except Exception as e:
- print(f"Unexpected error: {e}")
- def decrypt_interface():
- """Console interface for decryption"""
- try:
- ciphertext_hex = input("Enter ciphertext in HEX format: ").strip()
- key_file = input(f"Enter key filename (default: {DEFAULT_KEY_FILE}): ") or DEFAULT_KEY_FILE
- seed = int(input(f"Enter seed (1-{NUM_KEYS}): "))
- if not ciphertext_hex:
- print("Error: Ciphertext cannot be empty")
- return
- try:
- ciphertext_bytes = bytes.fromhex(ciphertext_hex)
- except ValueError:
- print("Error: Invalid HEX format. Must contain only hexadecimal characters (0-9, a-f)")
- return
- # Only load the needed key segment
- key = get_key_segment(key_file, seed)
- if not key:
- return
- # Check if ciphertext exceeds key length
- if len(ciphertext_bytes) > KEY_LENGTH:
- print(f"Warning: Ciphertext ({len(ciphertext_bytes)} bytes) exceeds key segment length ({KEY_LENGTH} bytes)")
- print("Only the first part will be decrypted. The result may be incomplete.")
- ciphertext_bytes = ciphertext_bytes[:KEY_LENGTH]
- plaintext_bytes = otp_encrypt_bytes(ciphertext_bytes, key[:len(ciphertext_bytes)])
- try:
- plaintext = plaintext_bytes.decode('utf-8')
- except UnicodeDecodeError:
- print("Error: Decryption produced invalid UTF-8 sequence. Possible causes:")
- print("- Incorrect seed or key file")
- print("- Corrupted ciphertext")
- print("- Key mismatch")
- return
- print("\n=== Decryption Results ===")
- print(f"Seed used: {seed}")
- print(f"Key file: {key_file}")
- print(f"Ciphertext length: {len(ciphertext_bytes)} bytes")
- print(f"Plaintext: {plaintext}")
- except ValueError:
- print("Error: Invalid seed value. Must be an integer.")
- except Exception as e:
- print(f"Unexpected error: {e}")
- def generate_key_interface():
- """Console interface for key generation"""
- try:
- print(f"Generating new AOTPKC[{KEY_LENGTH}-{NUM_KEYS}] big key...")
- print("This will generate a secure key using cryptographic random bytes.")
- print(f"Total key size: {TOTAL_KEY_SIZE/1024/1024:.2f} MB")
- filename = input(f"Enter filename to save key (default: {DEFAULT_KEY_FILE}): ") or DEFAULT_KEY_FILE
- if os.path.exists(filename):
- overwrite = input(f"File '{filename}' already exists. Overwrite? (y/n): ").lower()
- if overwrite != 'y':
- print("Key generation canceled")
- return
- # Generate directly to temporary file
- temp_file = generate_big_key()
- if temp_file:
- if save_big_key(temp_file, filename):
- print("Key generation successful!")
- try:
- os.remove(temp_file)
- except:
- pass
- except Exception as e:
- print(f"Error during key generation: {e}")
- def main_menu():
- """Main console menu"""
- print(f"\n{'='*50}")
- print(f"AOTPKC[{KEY_LENGTH}-{NUM_KEYS}] Encryption System (Memory Optimized)")
- print(f"{'='*50}")
- while True:
- print("\nMain Menu:")
- print("1. Generate new big key")
- print("2. Encrypt text")
- print("3. Decrypt text")
- print("4. Exit")
- choice = input("Select option (1-4): ")
- if choice == '1':
- generate_key_interface()
- elif choice == '2':
- encrypt_interface()
- elif choice == '3':
- decrypt_interface()
- elif choice == '4':
- print("Exiting...")
- break
- else:
- print("Invalid choice, please try again")
- if __name__ == "__main__":
- print(f"Automated One Time Pad Key Changer [{KEY_LENGTH}-{NUM_KEYS}]")
- try:
- main_menu()
- except KeyboardInterrupt:
- print("\n\nOperation canceled by user. Exiting...")
- sys.exit(0)
Advertisement
Add Comment
Please, Sign In to add comment