-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxor_encryptor.py
More file actions
268 lines (215 loc) · 8.43 KB
/
Copy pathxor_encryptor.py
File metadata and controls
268 lines (215 loc) · 8.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
#!/usr/bin/env python3
"""
Educational XOR-based encryption/decryption tool (standard library only).
IMPORTANT: This is for learning purposes only. Do NOT use for real security.
It uses:
- Random 32-byte encryption key and 32-byte MAC key (total 64 bytes)
- XOR with HMAC-SHA256-based keystream (counter mode) for confidentiality
- HMAC-SHA256 tag for integrity/authentication
Key handling:
- On ENCRYPT: a random 64-byte key is generated and printed (Base64). Save it!
- On DECRYPT: you must paste the same Base64 key.
Ciphertext format (before Base64): NONCE(12) || TAG(32) || CIPHERTEXT
Usage:
python xor_encryptor.py
# Follow interactive prompts to Encrypt or Decrypt
Requires: Python 3.8+
"""
from __future__ import annotations
import base64
import hashlib
import hmac
import os
import sys
import time
from typing import Tuple
# Parameters
NONCE_LEN = 12
BLOCK_LEN = 32 # SHA-256 output size
TAG_LEN = 32 # HMAC-SHA256 tag length
KEY_TOTAL_LEN = 64 # 32 bytes enc_key + 32 bytes mac_key
def generate_keys() -> Tuple[bytes, bytes]:
"""Return (enc_key, mac_key) where each is 32 random bytes."""
return os.urandom(32), os.urandom(32)
def pack_key(enc_key: bytes, mac_key: bytes) -> str:
"""Return Base64 string for enc_key||mac_key."""
if len(enc_key) != 32 or len(mac_key) != 32:
raise ValueError("Keys must be 32 bytes each")
key_bytes = enc_key + mac_key
return base64.b64encode(key_bytes).decode("ascii")
def unpack_key(b64_key: str) -> Tuple[bytes, bytes]:
"""Parse Base64 key string into (enc_key, mac_key)."""
try:
key_bytes = base64.b64decode(b64_key, validate=True)
except Exception as e:
raise ValueError("Invalid Base64 key") from e
if len(key_bytes) != KEY_TOTAL_LEN:
raise ValueError("Key must decode to 64 bytes (enc_key||mac_key)")
return key_bytes[:32], key_bytes[32:]
def keystream(enc_key: bytes, nonce: bytes, length: int) -> bytes:
"""Generate a keystream of the requested length using HMAC-SHA256 in counter mode."""
if len(nonce) != NONCE_LEN:
raise ValueError("nonce must be 12 bytes")
out = bytearray()
counter = 0
while len(out) < length:
# HMAC(enc_key, nonce || counter32)
block = hmac.new(enc_key, nonce + counter.to_bytes(4, "big"), hashlib.sha256).digest()
out.extend(block)
counter += 1
return bytes(out[:length])
def xor_bytes(a: bytes, b: bytes) -> bytes:
"""XOR two byte strings of equal length."""
if len(a) != len(b):
raise ValueError("Inputs to xor_bytes must have the same length")
return bytes(x ^ y for x, y in zip(a, b))
def encrypt(plaintext: bytes) -> Tuple[str, str]:
"""Encrypt bytes; return (ciphertext_base64, key_base64)."""
if not isinstance(plaintext, (bytes, bytearray)):
raise TypeError("plaintext must be bytes")
enc_key, mac_key = generate_keys()
nonce = os.urandom(NONCE_LEN)
ks = keystream(enc_key, nonce, len(plaintext))
ciphertext = xor_bytes(plaintext, ks)
# Compute authentication tag over nonce||ciphertext
tag = hmac.new(mac_key, nonce + ciphertext, hashlib.sha256).digest()
combined = nonce + tag + ciphertext
b64_ct = base64.b64encode(combined).decode("ascii")
b64_key = pack_key(enc_key, mac_key)
return b64_ct, b64_key
# Message on key safety: the Base64 key printed during encryption must be saved to decrypt.
def decrypt(b64_data: str, b64_key: str) -> bytes:
"""Decrypt Base64 ciphertext string using Base64 key. Returns plaintext bytes."""
try:
data = base64.b64decode(b64_data, validate=True)
except Exception as e:
raise ValueError("Invalid Base64 ciphertext") from e
if len(data) < NONCE_LEN + TAG_LEN:
raise ValueError("Ciphertext too short")
nonce = data[:NONCE_LEN]
tag = data[NONCE_LEN:NONCE_LEN + TAG_LEN]
ciphertext = data[NONCE_LEN + TAG_LEN:]
enc_key, mac_key = unpack_key(b64_key)
expected_tag = hmac.new(mac_key, nonce + ciphertext, hashlib.sha256).digest()
if not hmac.compare_digest(tag, expected_tag):
raise ValueError("Authentication failed: wrong key or corrupted data")
ks = keystream(enc_key, nonce, len(ciphertext))
return xor_bytes(ciphertext, ks)
def enable_ansi_on_windows() -> None:
"""Enable ANSI escape codes on Windows 10+ terminals (no-op elsewhere)."""
if os.name == "nt":
try:
import ctypes
kernel32 = ctypes.windll.kernel32
handle = kernel32.GetStdHandle(-11) # STD_OUTPUT_HANDLE
mode = ctypes.c_uint()
if kernel32.GetConsoleMode(handle, ctypes.byref(mode)):
kernel32.SetConsoleMode(handle, mode.value | 0x0004) # ENABLE_VIRTUAL_TERMINAL_PROCESSING
except Exception:
pass
def clear_screen() -> None:
"""Clear terminal screen and move cursor to home."""
sys.stdout.write("\x1b[2J\x1b[H")
sys.stdout.flush()
def intro_animation(duration: float = 1.8, fps: int = 15) -> None:
"""Spinner intro animation shown before the banner (Windows-friendly)."""
enable_ansi_on_windows()
frames = ["|", "/", "-", "\\"]
GREEN = "\x1b[92m"
RESET = "\x1b[0m"
start = time.perf_counter()
i = 0
# Hide cursor
sys.stdout.write("\x1b[?25l")
sys.stdout.flush()
try:
while time.perf_counter() - start < duration:
frame = frames[i % len(frames)]
sys.stdout.write(f"\r{GREEN}[ {frame} ] Initializing CryptiX...{RESET}")
sys.stdout.flush()
time.sleep(1.0 / fps)
i += 1
sys.stdout.write(f"\r{GREEN}[ \u2713 ] Ready {RESET}\n")
sys.stdout.flush()
finally:
# Show cursor back
sys.stdout.write("\x1b[?25h")
sys.stdout.flush()
def print_banner() -> None:
"""Prints a hacking/security themed startup banner (green matrix vibes)."""
enable_ansi_on_windows()
RESET = "\x1b[0m"
DIM = "\x1b[2m"
BOLD = "\x1b[1m"
GREEN = "\x1b[32m"
BRIGHT_GREEN = "\x1b[92m"
RED = "\x1b[31m"
ascii_lock = r"""
______ _ _ _
/ _____) | | (_) |
| / ___ _ _ ____ | |_ _| |_
| | (___) | | |/ ___)| _) | _)
| \____/| |_| ( (___ | |__| | |__
\_____/ \____|\____) \___)_|\___)
_ _
____| |__ _ _ ___| | _____
/ ___) _ \| | | |/___) || ___ |
( (___| | | | |_| |___ | || ____|
\____)_| |_|\____(___/ \_)_____)
"""
title = f"{BOLD}{BRIGHT_GREEN}CryptiX{RESET}"
subtitle = f"{DIM}{GREEN}for training/testing only — not real security{RESET}"
line = f"{GREEN}{'═' * 60}{RESET}"
print(line)
# tint ascii art
for ln in ascii_lock.splitlines():
print(f"{GREEN}{ln}{RESET}")
print(line)
print(title)
print(subtitle)
print(line)
print(f"{BRIGHT_GREEN}> Encrypt{RESET}{DIM}: Generates a Base64 key — SAVE IT to decrypt later.{RESET}")
print(f"{BRIGHT_GREEN}> Decrypt{RESET}{DIM}: Requires the exact Base64 key printed during encryption.{RESET}")
print(f"{RED}{BOLD}! WARNING{RESET}{DIM}: This is educational only. Do not protect real data with it.{RESET}")
print(line)
print()
def prompt_choice() -> str:
print("Select an option:")
print(" [E] Encrypt")
print(" [D] Decrypt")
choice = input("Enter E or D: ").strip().lower()
return choice
def main() -> int:
# Spinner intro, then clear and show banner
intro_animation(duration=1.8, fps=15)
clear_screen()
print_banner()
choice = prompt_choice()
if choice not in {"e", "d"}:
print("Invalid choice. Please run again and enter E or D.")
return 1
if choice == "e":
text = input("Enter text to encrypt: ")
ct_b64, key_b64 = encrypt(text.encode("utf-8"))
print("\nCiphertext (Base64):")
print(ct_b64)
print("\nKey (Base64) — save this to decrypt:")
print(key_b64)
return 0
else:
ct_b64 = input("Enter Base64 ciphertext: ").strip()
key_b64 = input("Enter Base64 key: ").strip()
try:
pt = decrypt(ct_b64, key_b64)
except Exception as e:
print(f"Decryption failed: {e}")
return 1
try:
text = pt.decode("utf-8")
except UnicodeDecodeError:
text = pt.decode("latin-1") # Fallback
print("\nPlaintext:")
print(text)
return 0
if __name__ == "__main__":
sys.exit(main())