Capybara_ele

AOTPKC[8192-1024]

Jul 27th, 2025
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.93 KB | None | 0 0
  1. import secrets
  2. import os
  3. import sys
  4.  
  5. # Constants
  6. KEY_LENGTH = 8192
  7. NUM_KEYS = 1024
  8. TOTAL_KEY_SIZE = KEY_LENGTH * NUM_KEYS
  9. DEFAULT_KEY_FILE = "aotpkc.key"
  10.  
  11. def generate_big_key():
  12.     """Generate secure giant key using cryptographic RNG with progress display"""
  13.     print(f"Generating secure key ({NUM_KEYS} keys of {KEY_LENGTH} bytes each)...")
  14.     print(f"Total size: {TOTAL_KEY_SIZE/1024/1024:.2f} MB")
  15.    
  16.     # Generate directly to file to avoid huge memory usage
  17.     filename = "temp_generation.key"
  18.     try:
  19.         with open(filename, "wb") as f:
  20.             for i in range(NUM_KEYS):
  21.                 f.write(secrets.token_bytes(KEY_LENGTH))
  22.                 if (i + 1) % 128 == 0:
  23.                     print(f"Generated {i+1}/{NUM_KEYS} key segments...")
  24.         return filename
  25.     except Exception as e:
  26.         print(f"Key generation failed: {e}")
  27.         return None
  28.  
  29. def save_big_key(source_file, filename=DEFAULT_KEY_FILE):
  30.     """Rename the generated key file to final name"""
  31.     try:
  32.         if os.path.exists(filename):
  33.             os.remove(filename)
  34.         os.rename(source_file, filename)
  35.         print(f"Secure big key saved to {filename}")
  36.         print(f"Key size: {os.path.getsize(filename)/1024/1024:.2f} MB")
  37.         return True
  38.     except Exception as e:
  39.         print(f"Error saving key file: {e}")
  40.         return False
  41.  
  42. def get_key_segment(filename, seed):
  43.     """Read only the needed key segment from disk (memory efficient)"""
  44.     if seed < 1 or seed > NUM_KEYS:
  45.         print(f"Error: Seed must be between 1 and {NUM_KEYS}")
  46.         return None
  47.    
  48.     try:
  49.         # Calculate file position
  50.         offset = (seed - 1) * KEY_LENGTH
  51.        
  52.         with open(filename, "rb") as f:
  53.             f.seek(offset)
  54.             segment = f.read(KEY_LENGTH)
  55.            
  56.         if len(segment) != KEY_LENGTH:
  57.             print(f"Error: Key segment incomplete ({len(segment)} bytes, expected {KEY_LENGTH})")
  58.             return None
  59.            
  60.         return segment
  61.     except FileNotFoundError:
  62.         print(f"Error: Key file '{filename}' not found")
  63.     except Exception as e:
  64.         print(f"Error reading key segment: {e}")
  65.     return None
  66.  
  67. def otp_encrypt_bytes(plaintext, key):
  68.     """Perform byte-level OTP encryption"""
  69.     return bytes(p ^ k for p, k in zip(plaintext, key))
  70.  
  71. def encrypt_interface():
  72.     """Console interface for encryption"""
  73.     try:
  74.         plaintext = input("Enter plaintext to encrypt: ")
  75.         key_file = input(f"Enter key filename (default: {DEFAULT_KEY_FILE}): ") or DEFAULT_KEY_FILE
  76.         seed = int(input(f"Enter seed (1-{NUM_KEYS}): "))
  77.        
  78.         if not plaintext:
  79.             print("Error: Plaintext cannot be empty")
  80.             return
  81.        
  82.         # Only load the needed key segment (8KB instead of 8MB)
  83.         key = get_key_segment(key_file, seed)
  84.         if not key:
  85.             return
  86.        
  87.         plaintext_bytes = plaintext.encode('utf-8')
  88.        
  89.         # Check if plaintext exceeds key length
  90.         if len(plaintext_bytes) > KEY_LENGTH:
  91.             print(f"Warning: Plaintext ({len(plaintext_bytes)} bytes) exceeds key segment length ({KEY_LENGTH} bytes)")
  92.             print("Only the first part will be encrypted. Consider splitting your message.")
  93.             plaintext_bytes = plaintext_bytes[:KEY_LENGTH]
  94.        
  95.         ciphertext_bytes = otp_encrypt_bytes(plaintext_bytes, key[:len(plaintext_bytes)])
  96.        
  97.         print("\n=== Encryption Results ===")
  98.         print(f"Seed used: {seed}")
  99.         print(f"Key file: {key_file}")
  100.         print(f"Plaintext length: {len(plaintext_bytes)} bytes")
  101.         print(f"Hex ciphertext: {ciphertext_bytes.hex()}")
  102.     except ValueError:
  103.         print("Error: Invalid seed value. Must be an integer.")
  104.     except Exception as e:
  105.         print(f"Unexpected error: {e}")
  106.  
  107. def decrypt_interface():
  108.     """Console interface for decryption"""
  109.     try:
  110.         ciphertext_hex = input("Enter ciphertext in HEX format: ").strip()
  111.         key_file = input(f"Enter key filename (default: {DEFAULT_KEY_FILE}): ") or DEFAULT_KEY_FILE
  112.         seed = int(input(f"Enter seed (1-{NUM_KEYS}): "))
  113.        
  114.         if not ciphertext_hex:
  115.             print("Error: Ciphertext cannot be empty")
  116.             return
  117.        
  118.         try:
  119.             ciphertext_bytes = bytes.fromhex(ciphertext_hex)
  120.         except ValueError:
  121.             print("Error: Invalid HEX format. Must contain only hexadecimal characters (0-9, a-f)")
  122.             return
  123.        
  124.         # Only load the needed key segment
  125.         key = get_key_segment(key_file, seed)
  126.         if not key:
  127.             return
  128.        
  129.         # Check if ciphertext exceeds key length
  130.         if len(ciphertext_bytes) > KEY_LENGTH:
  131.             print(f"Warning: Ciphertext ({len(ciphertext_bytes)} bytes) exceeds key segment length ({KEY_LENGTH} bytes)")
  132.             print("Only the first part will be decrypted. The result may be incomplete.")
  133.             ciphertext_bytes = ciphertext_bytes[:KEY_LENGTH]
  134.        
  135.         plaintext_bytes = otp_encrypt_bytes(ciphertext_bytes, key[:len(ciphertext_bytes)])
  136.        
  137.         try:
  138.             plaintext = plaintext_bytes.decode('utf-8')
  139.         except UnicodeDecodeError:
  140.             print("Error: Decryption produced invalid UTF-8 sequence. Possible causes:")
  141.             print("- Incorrect seed or key file")
  142.             print("- Corrupted ciphertext")
  143.             print("- Key mismatch")
  144.             return
  145.        
  146.         print("\n=== Decryption Results ===")
  147.         print(f"Seed used: {seed}")
  148.         print(f"Key file: {key_file}")
  149.         print(f"Ciphertext length: {len(ciphertext_bytes)} bytes")
  150.         print(f"Plaintext: {plaintext}")
  151.     except ValueError:
  152.         print("Error: Invalid seed value. Must be an integer.")
  153.     except Exception as e:
  154.         print(f"Unexpected error: {e}")
  155.  
  156. def generate_key_interface():
  157.     """Console interface for key generation"""
  158.     try:
  159.         print(f"Generating new AOTPKC[{KEY_LENGTH}-{NUM_KEYS}] big key...")
  160.         print("This will generate a secure key using cryptographic random bytes.")
  161.         print(f"Total key size: {TOTAL_KEY_SIZE/1024/1024:.2f} MB")
  162.        
  163.         filename = input(f"Enter filename to save key (default: {DEFAULT_KEY_FILE}): ") or DEFAULT_KEY_FILE
  164.        
  165.         if os.path.exists(filename):
  166.             overwrite = input(f"File '{filename}' already exists. Overwrite? (y/n): ").lower()
  167.             if overwrite != 'y':
  168.                 print("Key generation canceled")
  169.                 return
  170.        
  171.         # Generate directly to temporary file
  172.         temp_file = generate_big_key()
  173.         if temp_file:
  174.             if save_big_key(temp_file, filename):
  175.                 print("Key generation successful!")
  176.                 try:
  177.                     os.remove(temp_file)
  178.                 except:
  179.                     pass
  180.     except Exception as e:
  181.         print(f"Error during key generation: {e}")
  182.  
  183. def main_menu():
  184.     """Main console menu"""
  185.     print(f"\n{'='*50}")
  186.     print(f"AOTPKC[{KEY_LENGTH}-{NUM_KEYS}] Encryption System (Memory Optimized)")
  187.     print(f"{'='*50}")
  188.    
  189.     while True:
  190.         print("\nMain Menu:")
  191.         print("1. Generate new big key")
  192.         print("2. Encrypt text")
  193.         print("3. Decrypt text")
  194.         print("4. Exit")
  195.        
  196.         choice = input("Select option (1-4): ")
  197.        
  198.         if choice == '1':
  199.             generate_key_interface()
  200.         elif choice == '2':
  201.             encrypt_interface()
  202.         elif choice == '3':
  203.             decrypt_interface()
  204.         elif choice == '4':
  205.             print("Exiting...")
  206.             break
  207.         else:
  208.             print("Invalid choice, please try again")
  209.  
  210. if __name__ == "__main__":
  211.     print(f"Automated One Time Pad Key Changer [{KEY_LENGTH}-{NUM_KEYS}]")
  212.     try:
  213.         main_menu()
  214.     except KeyboardInterrupt:
  215.         print("\n\nOperation canceled by user. Exiting...")
  216.         sys.exit(0)
Advertisement
Add Comment
Please, Sign In to add comment