-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdemo.py
More file actions
268 lines (207 loc) · 9.1 KB
/
Copy pathdemo.py
File metadata and controls
268 lines (207 loc) · 9.1 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
"""
NONOCRYPT Interactive Demo
Demonstrates visual key verification using nonogram puzzles:
1. Generate visual fingerprints from keys
2. Compare fingerprints visually
3. Interactive puzzle-solving verification ceremony
4. Text-based custom key images
5. Tamper detection
"""
import sys
import os
import time
from nonogram import compute_clues, solve, verify_solution
from nonocrypt import (
KeyFingerprint, compare_fingerprints,
keygen_from_text, keygen_from_image, keygen_random,
encrypt, decrypt, nono_hash,
)
from visual import (
text_to_image, render_grid, render_puzzle,
render_progressive, print_key_info,
)
def _input(prompt, default=""):
try:
val = input(prompt).strip()
except EOFError:
val = ""
return val if val else default
def banner():
print(r"""
╔═══════════════════════════════════════════════════════════╗
║ ║
║ ███╗ ██╗ ██████╗ ███╗ ██╗ ██████╗ ║
║ ████╗ ██║██╔═══██╗████╗ ██║██╔═══██╗ ║
║ ██╔██╗ ██║██║ ██║██╔██╗ ██║██║ ██║ ║
║ ██║╚██╗██║██║ ██║██║╚██╗██║██║ ██║ ║
║ ██║ ╚████║╚██████╔╝██║ ╚████║╚██████╔╝ ║
║ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ║
║ CRYPT ║
║ ║
║ Visual Key Verification via Nonogram Puzzles ║
║ Every key is a picture. Verify by solving. ║
╚═══════════════════════════════════════════════════════════╝
""")
def demo_fingerprint():
"""Demo 1: Generate visual fingerprints from public key bytes."""
print("\n" + "=" * 60)
print(" DEMO 1: Visual Key Fingerprints")
print("=" * 60)
print("""
Any public key can be turned into a visual nonogram fingerprint.
Same key bytes always produce the same image.
""")
# Simulate two parties with the same public key
alice_key = b"ML-KEM-768-public-key-" + os.urandom(32)
print(f" Alice's public key: {alice_key[:20].hex()}...")
fp_alice = KeyFingerprint.from_bytes(alice_key, grid_size=10)
print(f" Fingerprint ID: {fp_alice.fingerprint_id}")
print(f"\n Alice sees this image:")
print(fp_alice.as_image())
# Bob computes fingerprint from the same key
fp_bob = KeyFingerprint.from_bytes(alice_key, grid_size=10)
print(f" Bob computes fingerprint from the same key:")
print(fp_bob.as_image())
print(f" Match: {fp_alice.matches(fp_bob)}")
print(f" Both see the same picture -- key is verified!")
return alice_key
def demo_comparison(alice_key: bytes):
"""Demo 2: Side-by-side comparison (match and mismatch)."""
print("\n" + "=" * 60)
print(" DEMO 2: Visual Comparison (Match vs Mismatch)")
print("=" * 60)
fp_real = KeyFingerprint.from_bytes(alice_key, grid_size=10)
# Tampered key (1 byte changed)
tampered = bytearray(alice_key)
tampered[10] ^= 0x01 # flip one bit
fp_tampered = KeyFingerprint.from_bytes(bytes(tampered), grid_size=10)
print(f"\n Real key vs same key (should match):")
fp_same = KeyFingerprint.from_bytes(alice_key, grid_size=10)
print(compare_fingerprints(fp_real, fp_same))
print(f"\n Real key vs tampered key (should differ):")
print(compare_fingerprints(fp_real, fp_tampered))
print(f"\n Even a single bit change produces a completely different image.")
print(f" Visual comparison makes MITM attacks immediately obvious.")
def demo_puzzle_verification():
"""Demo 3: Interactive verification by solving the puzzle."""
print("\n" + "=" * 60)
print(" DEMO 3: Puzzle-Solving Verification Ceremony")
print("=" * 60)
print("""
The verification ceremony:
1. Alice shares her fingerprint as a nonogram PUZZLE (clues only)
2. Bob SOLVES the puzzle to reveal the image
3. Bob compares the revealed image with what Alice showed him
4. If images match, the key is verified!
Solving is NP-hard, so this is also a proof of computational work.
""")
text = _input(" Enter text for key identity (e.g., 'ALICE'): ", "ALICE")
fp = KeyFingerprint.from_text(text)
print(f"\n Alice's fingerprint image (she shows Bob in person):")
print(fp.as_image())
print(f" Alice shares the PUZZLE (clues only, no image):")
print(fp.as_puzzle())
_input("\n Press Enter to watch Bob solve the puzzle...")
print()
# Progressive solving animation
render_progressive(
fp.row_clues, fp.col_clues, fp.image,
delay=0.04,
header=" Bob solving puzzle"
)
print(f"\n Bob solved it! The image matches Alice's -- key verified!")
return fp
def demo_text_keys():
"""Demo 4: Custom key identities from text."""
print("\n" + "=" * 60)
print(" DEMO 4: Text-Based Key Identities")
print("=" * 60)
print("""
Users can create memorable key identities from text.
The text is rendered as pixel art, becoming the visual fingerprint.
""")
names = ["ALICE", "BOB"]
for name in names:
fp = KeyFingerprint.from_text(name)
print(f" {name}'s key identity (fingerprint {fp.fingerprint_id}):")
print(fp.as_image())
def demo_serialization():
"""Demo 5: Sharing fingerprints as puzzles."""
print("\n" + "=" * 60)
print(" DEMO 5: Sharing & Verifying Fingerprints")
print("=" * 60)
print("""
Alice can serialize her fingerprint as a puzzle and send it.
Bob deserializes, solves, and compares with his own computation.
""")
key = os.urandom(64)
fp_alice = KeyFingerprint.from_bytes(key, grid_size=10)
# Serialize (puzzle only, no solution)
puzzle_bytes = fp_alice.serialize()
print(f" Serialized puzzle: {len(puzzle_bytes)} bytes")
print(f" (Contains only clues -- image not included)\n")
# Bob receives and deserializes
fp_received = KeyFingerprint.deserialize_puzzle(puzzle_bytes)
print(f" Bob receives puzzle {fp_received.fingerprint_id}")
print(f" Grid: {fp_received.n_rows}x{fp_received.n_cols}")
# Bob solves the puzzle
t0 = time.time()
solved_image = fp_received.verify_by_solving(timeout_sec=30)
elapsed = time.time() - t0
if solved_image:
print(f" Bob solved the puzzle in {elapsed:.3f}s")
print(f"\n Revealed image:")
print(render_grid(solved_image))
# Bob also computes his own fingerprint from the key
fp_bob = KeyFingerprint.from_bytes(key, grid_size=10)
match = solved_image == fp_bob.image
print(f" Matches Bob's own computation: {match}")
else:
print(f" Could not solve within timeout")
def demo_encryption():
"""Demo 6: Encryption (secondary feature)."""
print("\n" + "=" * 60)
print(" DEMO 6: Nonogram Encryption (Proof-of-Work Model)")
print("=" * 60)
print("""
NONOCRYPT can also encrypt messages. The sender must solve the
recipient's nonogram puzzle (NP-hard work), while the recipient
decrypts instantly (already knows the solution).
""")
text = _input(" Enter key text (e.g., 'KEY'): ", "KEY")
pk, sk = keygen_from_text(text)
message = _input(" Enter message: ", "Hello, visual crypto!")
plaintext = message.encode('utf-8')
print(f"\n Encrypting (solving {pk.n_rows}x{pk.n_cols} puzzle)...")
t0 = time.time()
ct, _, solve_time = encrypt(pk, plaintext, timeout_sec=120)
total = time.time() - t0
print(f" Encrypt time: {total:.3f}s (puzzle solve: {solve_time:.3f}s)")
t0 = time.time()
recovered = decrypt(sk, ct)
dec_time = time.time() - t0
print(f" Decrypt time: {dec_time*1000:.3f}ms")
print(f" Recovered: {recovered.decode('utf-8')}")
if solve_time > 0:
ratio = total / max(dec_time, 1e-9)
print(f" Asymmetry: encrypt is ~{ratio:.0f}x slower")
def main():
banner()
# Primary demos: visual verification
alice_key = demo_fingerprint()
demo_comparison(alice_key)
fp = demo_puzzle_verification()
demo_text_keys()
demo_serialization()
# Secondary demo: encryption
demo_encryption()
print(f"\n{'=' * 60}")
print(f" NONOCRYPT Demo Complete")
print(f"")
print(f" Primary feature: Visual key verification via nonograms")
print(f" Every key becomes a picture. Verify by solving the puzzle.")
print(f" Use alongside ML-KEM/ML-DSA for post-quantum security.")
print(f"{'=' * 60}\n")
if __name__ == "__main__":
main()