cryptodown 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
cnslab/__init__.py ADDED
@@ -0,0 +1,49 @@
1
+ """
2
+ CNSLab - Offline Python package to generate all CNS Lab Exam practice programs.
3
+
4
+ Functions:
5
+ p1(), lab1(), caesar() -> Generates '1.py'
6
+ p2(), lab2(), transposition() -> Generates '2.py'
7
+ p3(), lab3(), stego() -> Generates '3.py'
8
+ p4(), lab4(), gcd() -> Generates '4.py'
9
+ p5(), lab5(), mod_arith() -> Generates '5.py'
10
+ p6(), lab6(), des() -> Generates '6.py'
11
+ p7a(), lab7a(), aes_ecb() -> Generates '7a.py'
12
+ p7b(), lab7b(), aes_cbc() -> Generates '7b.py'
13
+ p8(), lab8(), rsa() -> Generates '8.py'
14
+ p9(), lab9(), diffie_hellman() -> Generates '9.py'
15
+ p10(), lab10(), sha(), hmac() -> Generates '10.py'
16
+ p11(), lab11(), digital_signature()-> Generates '11.py'
17
+
18
+ Bulk & Utility:
19
+ create_all() / dump_all() / all() -> Generates all lab programs at once
20
+ list_programs() -> Displays catalog of all lab programs
21
+ get_code(program) -> Returns code as a string
22
+ create_sample_image() -> Generates minimal valid 'image.png'
23
+ """
24
+
25
+ from .programs import (
26
+ # Lab numbered functions
27
+ lab1, lab2, lab3, lab4, lab5, lab6, lab7a, lab7b, lab8, lab9, lab10, lab11,
28
+ p1, p2, p3, p4, p5, p6, p7a, p7b, p8, p9, p10, p11,
29
+ # Semantic aliases
30
+ caesar, transposition, stego, steganography, gcd, mod_arith,
31
+ des, aes_ecb, aes_cbc, rsa, diffie_hellman, sha, hmac, digital_signature,
32
+ # Utilities
33
+ create_all, dump_all, list_programs, get_code, write_program, create_sample_image,
34
+ PROGRAMS,
35
+ )
36
+
37
+ # Friendly 'all' alias
38
+ all = create_all
39
+
40
+ __version__ = "1.0.0"
41
+
42
+ __all__ = [
43
+ "lab1", "lab2", "lab3", "lab4", "lab5", "lab6", "lab7a", "lab7b", "lab8", "lab9", "lab10", "lab11",
44
+ "p1", "p2", "p3", "p4", "p5", "p6", "p7a", "p7b", "p8", "p9", "p10", "p11",
45
+ "caesar", "transposition", "stego", "steganography", "gcd", "mod_arith",
46
+ "des", "aes_ecb", "aes_cbc", "rsa", "diffie_hellman", "sha", "hmac", "digital_signature",
47
+ "create_all", "dump_all", "all", "list_programs", "get_code", "write_program",
48
+ "create_sample_image", "PROGRAMS", "__version__"
49
+ ]
cnslab/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
cnslab/cli.py ADDED
@@ -0,0 +1,106 @@
1
+ """
2
+ Command-line interface for cnslab.
3
+ Allows generating lab program files directly from the terminal without internet.
4
+ """
5
+
6
+ import argparse
7
+ import sys
8
+ from pathlib import Path
9
+ from .programs import (
10
+ PROGRAMS,
11
+ write_program,
12
+ create_all,
13
+ list_programs,
14
+ get_code,
15
+ create_sample_image,
16
+ normalize_key,
17
+ )
18
+
19
+
20
+ def main() -> None:
21
+ parser = argparse.ArgumentParser(
22
+ prog="cnslab",
23
+ description="Offline CNS Lab Program Generator for Lab Exams",
24
+ formatter_class=argparse.RawDescriptionHelpFormatter,
25
+ epilog="""
26
+ Examples:
27
+ cnslab 1 Create '1.py' (Caesar Cipher)
28
+ cnslab 7a Create '7a.py' (AES ECB)
29
+ cnslab all Generate all lab programs (1.py - 11.py)
30
+ cnslab list Show all available lab programs
31
+ cnslab 8 -o rsa.py Write RSA code to custom filename 'rsa.py'
32
+ cnslab 6 --print Print DES code to terminal stdout
33
+ cnslab image Create a dummy 'image.png' for stego testing
34
+ """,
35
+ )
36
+
37
+ parser.add_argument(
38
+ "program",
39
+ nargs="?",
40
+ default=None,
41
+ help="Lab number or alias (e.g. 1, 2, 3, 4, 5, 6, 7a, 7b, 8, 9, 10, 11, 'all', 'list', 'image')",
42
+ )
43
+ parser.add_argument(
44
+ "-o", "--output",
45
+ dest="filename",
46
+ default=None,
47
+ help="Custom output filename (e.g. -o solution.py)",
48
+ )
49
+ parser.add_argument(
50
+ "-d", "--dir",
51
+ dest="dest_dir",
52
+ default=None,
53
+ help="Target directory (defaults to current directory)",
54
+ )
55
+ parser.add_argument(
56
+ "-p", "--print",
57
+ action="store_true",
58
+ help="Print code to stdout instead of writing to a file",
59
+ )
60
+ parser.add_argument(
61
+ "-f", "--force",
62
+ action="store_true",
63
+ default=True,
64
+ help="Force overwrite existing files (default: True)",
65
+ )
66
+
67
+ args = parser.parse_args()
68
+
69
+ # If no argument given, print help or list
70
+ if not args.program:
71
+ list_programs()
72
+ return
73
+
74
+ arg_lower = args.program.strip().lower()
75
+
76
+ if arg_lower in ("list", "-l", "--list"):
77
+ list_programs()
78
+ return
79
+
80
+ if arg_lower in ("all", "*"):
81
+ create_all(dest_dir=args.dest_dir, overwrite=args.force)
82
+ return
83
+
84
+ if arg_lower in ("image", "sample_image", "img"):
85
+ out_fn = args.filename or "image.png"
86
+ create_sample_image(filename=out_fn, dest_dir=args.dest_dir)
87
+ return
88
+
89
+ try:
90
+ if args.print:
91
+ code = get_code(arg_lower)
92
+ print(code, end="")
93
+ else:
94
+ write_program(
95
+ arg_lower,
96
+ filename=args.filename,
97
+ dest_dir=args.dest_dir,
98
+ overwrite=args.force,
99
+ )
100
+ except KeyError as e:
101
+ print(f"Error: {e}", file=sys.stderr)
102
+ sys.exit(1)
103
+
104
+
105
+ if __name__ == "__main__":
106
+ main()
cnslab/programs.py ADDED
@@ -0,0 +1,549 @@
1
+ """
2
+ Offline CNS Lab Programs Repository and File Generator.
3
+ Contains all lab exam practice programs with zero external network dependencies.
4
+ """
5
+
6
+ from pathlib import Path
7
+ from typing import Dict, Optional, Union
8
+
9
+ # Exact program code strings
10
+ LAB_1_CODE = '''def encrypt(text, key):
11
+ result = ""
12
+ for c in text:
13
+ if c.isalpha():
14
+ base = ord('A') if c.isupper() else ord('a')
15
+ result += chr((ord(c) - base + key) % 26 + base)
16
+ else:
17
+ result += c
18
+
19
+ return result
20
+
21
+ def decrypt(text, key):
22
+ return encrypt(text, -key)
23
+
24
+ text = input("Enter text ")
25
+ key = int(input("Enter key "))
26
+
27
+ cipher = encrypt(text, key)
28
+ print("cipher ", cipher)
29
+
30
+ pt = decrypt(cipher, key)
31
+ print("pt ", pt)
32
+ '''
33
+
34
+ LAB_2_CODE = '''text = input("Enter pt ").upper()
35
+ key = int(input("Enter key "))
36
+
37
+ while len(text) % key != 0:
38
+ text += 'X'
39
+
40
+ cipher = ""
41
+
42
+ for i in range(key):
43
+ for j in range(i, len(text), key):
44
+ cipher += text[j]
45
+
46
+ print("cipher ", cipher)
47
+
48
+ rows = len(cipher) // key
49
+ plain = ""
50
+
51
+ for i in range(rows):
52
+ for j in range(key):
53
+ plain += cipher[j * rows + 1]
54
+ print("Decrypt:", plain.rstrip('X'))
55
+ '''
56
+
57
+ LAB_3_CODE = '''from stegano import lsb
58
+
59
+ image = input("enter image name: ")
60
+ msg = input("enter message: ")
61
+
62
+ secret = lsb.hide(image, msg)
63
+ secret.save("stego.png")
64
+ print("Message hidden")
65
+
66
+ print("Extracted message:", lsb.reveal("stego.png"))
67
+ '''
68
+
69
+ LAB_4_CODE = '''import math
70
+
71
+ a = int(input("Enter first number: "))
72
+ b = int(input("Enter second number: "))
73
+ print("GCD: ", math.gcd(a, b))
74
+
75
+ num = int(input("Enter Number: "))
76
+ mod = int(input("Enter Modulus: "))
77
+
78
+ try:
79
+ print("Modular inverse: ", pow(num, -1, mod))
80
+ except ValueError:
81
+ print("NA")
82
+ '''
83
+
84
+ LAB_5_CODE = '''def modular_exponentiation(base, exponent, modulus):
85
+ result = 1
86
+ base = base % modulus
87
+ while exponent > 0:
88
+ if exponent % 2 == 1:
89
+ result = (result * base) % modulus
90
+ exponent = exponent // 2
91
+ base = (base * base) % modulus
92
+ return result
93
+
94
+ def extended_gcd(a, b):
95
+ if a == 0:
96
+ return b, 0, 1
97
+ gcd, x1, y1 = extended_gcd(b % a, a)
98
+ x = y1 - (b // a) * x1
99
+ y = x1
100
+ return gcd, x, y
101
+
102
+ def modular_inverse(a, m):
103
+ gcd, x, y = extended_gcd(a, m)
104
+ if gcd != 1:
105
+ return None
106
+ return x % m
107
+
108
+ print("----- Modular Exponentiation -----")
109
+ base = int(input("Enter Base: "))
110
+ exponent = int(input("Enter Exponent: "))
111
+ modulus = int(input("Enter Modulus: "))
112
+ power = modular_exponentiation(base, exponent, modulus)
113
+ print("Result =", power)
114
+
115
+ print("\\n----- Modular Inverse -----")
116
+ number = int(input("Enter Number: "))
117
+ mod = int(input("Enter Modulus: "))
118
+ inverse = modular_inverse(number, mod)
119
+ if inverse is None:
120
+ print("Modular Inverse does not exist.")
121
+ else:
122
+ print("Modular Inverse =", inverse)
123
+ '''
124
+
125
+ LAB_6_CODE = '''from Crypto.Cipher import DES
126
+ from Crypto.Util.Padding import pad, unpad
127
+
128
+ key = b'12345678'
129
+ text = input("Enter pt: ")
130
+
131
+ cipher = DES.new(key, DES.MODE_ECB)
132
+ enc = cipher.encrypt(pad(text.encode(), 8))
133
+ print("Encrypted: ", enc.hex())
134
+
135
+ dec = cipher.decrypt(enc)
136
+ print("decrypted: ", unpad(dec, 8).decode())
137
+ '''
138
+
139
+ LAB_7A_CODE = '''from Crypto.Cipher import AES
140
+ from Crypto.Util.Padding import pad, unpad
141
+
142
+ key = b'1234567890abcdef'
143
+ text = input("Enter pt: ")
144
+
145
+ cipher = AES.new(key, AES.MODE_ECB)
146
+ enc = cipher.encrypt(pad(text.encode(), 16))
147
+ print("Encrypted: ", enc.hex())
148
+
149
+ dec = cipher.decrypt(enc)
150
+ print("decrypted: ", unpad(dec, 16).decode())
151
+ '''
152
+
153
+ LAB_7B_CODE = '''from Crypto.Cipher import AES
154
+ from Crypto.Util.Padding import pad, unpad
155
+ from Crypto.Random import get_random_bytes
156
+
157
+ key = b'1234567890abcdef'
158
+ iv = get_random_bytes(16)
159
+ text = input("Enter pt: ")
160
+
161
+ cipher = AES.new(key, AES.MODE_CBC, iv)
162
+ enc = cipher.encrypt(pad(text.encode(), 16))
163
+ print("Encrypted: ", enc.hex())
164
+
165
+ cipher = AES.new(key, AES.MODE_CBC, iv)
166
+ dec = cipher.decrypt(enc)
167
+ print("decrypted: ", unpad(dec, 16).decode())
168
+ '''
169
+
170
+ LAB_8_CODE = '''from math import gcd
171
+
172
+ p,q = 17, 11
173
+ n = p * q
174
+ phi = (p - 1) * (q - 1)
175
+ e = 7
176
+ d = pow(e, -1, phi)
177
+
178
+ print("Public key: ", (e, n))
179
+ print("Private key: ", (d, n))
180
+
181
+ text = input("Enter pt: ")
182
+
183
+ cipher = [pow(ord(c), e, n) for c in text]
184
+ print("Encrypted: ", cipher)
185
+
186
+ plain = ''. join(chr(pow(c, d, n)) for c in cipher)
187
+ print("pt:", plain)
188
+ '''
189
+
190
+ LAB_9_CODE = '''# Diffie-Hellman Key Exchange
191
+
192
+ p = int(input("Enter Prime Number (p): "))
193
+ g = int(input("Enter Primitive Root (g): "))
194
+
195
+ a = int(input("Enter Alice's Private Key: "))
196
+ b = int(input("Enter Bob's Private Key: "))
197
+
198
+ A = pow(g, a, p)
199
+ B = pow(g, b, p)
200
+
201
+ print("\\nAlice's Public Key:", A)
202
+ print("Bob's Public Key :", B)
203
+
204
+ Alice_secret = pow(B, a, p)
205
+ Bob_secret = pow(A, b, p)
206
+
207
+ print("\\nAlice's Shared Secret Key:", Alice_secret)
208
+ print("Bob's Shared Secret Key :", Bob_secret)
209
+
210
+ if Alice_secret == Bob_secret:
211
+ print("\\nSecure Key Exchange Successful!")
212
+ else:
213
+ print("\\nKey Exchange Failed!")
214
+ '''
215
+
216
+ LAB_10_CODE = '''import hashlib
217
+ import hmac
218
+
219
+ # Part A: SHA-256 Hash
220
+ message = input("Enter Message: ")
221
+ hash_value = hashlib.sha256(message.encode()).hexdigest()
222
+ print("\\nSHA-256 Hash:")
223
+ print(hash_value)
224
+
225
+ verify = input("\\nEnter Message Again for Verification: ")
226
+ verify_hash = hashlib.sha256(verify.encode()).hexdigest()
227
+ if hash_value == verify_hash:
228
+ print("\\nHash Verified Successfully.")
229
+ else:
230
+ print("\\nHash Verification Failed.")
231
+
232
+ # Part B: HMAC
233
+ key = input("\\nEnter Secret Key: ").encode()
234
+ message = input("Enter Message: ").encode()
235
+ mac = hmac.new(key, message, hashlib.sha256).hexdigest()
236
+ print("\\nGenerated HMAC:")
237
+ print(mac)
238
+
239
+ verify_message = input("\\nEnter Message Again for Verification: ").encode()
240
+ verify_mac = hmac.new(key, verify_message, hashlib.sha256).hexdigest()
241
+ if mac == verify_mac:
242
+ print("\\nHMAC Verified Successfully.")
243
+ else:
244
+ print("\\nHMAC Verification Failed.")
245
+ '''
246
+
247
+ LAB_11_CODE = '''from Crypto.PublicKey import RSA
248
+ from Crypto.Signature import pkcs1_15
249
+ from Crypto.Hash import SHA256
250
+
251
+ # Generate RSA Key Pair
252
+ key = RSA.generate(2048)
253
+ private_key = key
254
+ public_key = key.publickey()
255
+
256
+ message = input("Enter Message: ").encode()
257
+
258
+ # Hash the message
259
+ hash_value = SHA256.new(message)
260
+
261
+ # Generate Digital Signature
262
+ signature = pkcs1_15.new(private_key).sign(hash_value)
263
+ print("\\nDigital Signature Generated Successfully.")
264
+
265
+ # Verification
266
+ try:
267
+ pkcs1_15.new(public_key).verify(hash_value, signature)
268
+ print("Digital Signature Verified Successfully.")
269
+ except (ValueError, TypeError):
270
+ print("Digital Signature Verification Failed.")
271
+ '''
272
+
273
+ # Catalog of all programs
274
+ PROGRAMS: Dict[str, dict] = {
275
+ "1": {
276
+ "filename": "1.py",
277
+ "title": "Caesar Cipher (Encryption & Decryption)",
278
+ "code": LAB_1_CODE,
279
+ "aliases": ["1", "p1", "lab1", "caesar"],
280
+ },
281
+ "2": {
282
+ "filename": "2.py",
283
+ "title": "Transposition Cipher (Encryption & Decryption)",
284
+ "code": LAB_2_CODE,
285
+ "aliases": ["2", "p2", "lab2", "transposition"],
286
+ },
287
+ "3": {
288
+ "filename": "3.py",
289
+ "title": "Image-Based Steganography (LSB)",
290
+ "code": LAB_3_CODE,
291
+ "aliases": ["3", "p3", "lab3", "stego", "steganography"],
292
+ },
293
+ "4": {
294
+ "filename": "4.py",
295
+ "title": "GCD & Modular Inverse (Euclidean)",
296
+ "code": LAB_4_CODE,
297
+ "aliases": ["4", "p4", "lab4", "gcd"],
298
+ },
299
+ "5": {
300
+ "filename": "5.py",
301
+ "title": "Modular Exponentiation & Extended Euclidean Inverse",
302
+ "code": LAB_5_CODE,
303
+ "aliases": ["5", "p5", "lab5", "mod_arith", "modular"],
304
+ },
305
+ "6": {
306
+ "filename": "6.py",
307
+ "title": "DES Encryption & Decryption (ECB Mode)",
308
+ "code": LAB_6_CODE,
309
+ "aliases": ["6", "p6", "lab6", "des"],
310
+ },
311
+ "7a": {
312
+ "filename": "7a.py",
313
+ "title": "AES Encryption & Decryption (ECB Mode)",
314
+ "code": LAB_7A_CODE,
315
+ "aliases": ["7a", "p7a", "lab7a", "aes_ecb"],
316
+ },
317
+ "7b": {
318
+ "filename": "7b.py",
319
+ "title": "AES Encryption & Decryption (CBC Mode)",
320
+ "code": LAB_7B_CODE,
321
+ "aliases": ["7b", "p7b", "lab7b", "aes_cbc"],
322
+ },
323
+ "8": {
324
+ "filename": "8.py",
325
+ "title": "RSA Public Key Cryptosystem",
326
+ "code": LAB_8_CODE,
327
+ "aliases": ["8", "p8", "lab8", "rsa"],
328
+ },
329
+ "9": {
330
+ "filename": "9.py",
331
+ "title": "Diffie-Hellman Key Exchange",
332
+ "code": LAB_9_CODE,
333
+ "aliases": ["9", "p9", "lab9", "diffie_hellman", "dh"],
334
+ },
335
+ "10": {
336
+ "filename": "10.py",
337
+ "title": "Cryptographic Hash (SHA-256) & HMAC",
338
+ "code": LAB_10_CODE,
339
+ "aliases": ["10", "p10", "lab10", "sha", "hmac"],
340
+ },
341
+ "11": {
342
+ "filename": "11.py",
343
+ "title": "Digital Signature Generation & Verification (RSA + SHA-256)",
344
+ "code": LAB_11_CODE,
345
+ "aliases": ["11", "p11", "lab11", "signature", "digital_signature"],
346
+ },
347
+ }
348
+
349
+ # Fast alias lookup
350
+ _ALIAS_MAP: Dict[str, str] = {}
351
+ for _key, _meta in PROGRAMS.items():
352
+ for _alias in _meta["aliases"]:
353
+ _ALIAS_MAP[_alias.lower()] = _key
354
+
355
+
356
+ def normalize_key(key: Union[int, str]) -> str:
357
+ """Normalize input key (e.g. 1, 'p1', 'lab7a') to standard key ('1', '7a')."""
358
+ k = str(key).strip().lower()
359
+ if k in _ALIAS_MAP:
360
+ return _ALIAS_MAP[k]
361
+ raise KeyError(
362
+ f"Unknown lab program '{key}'. Available programs: {', '.join(PROGRAMS.keys())}"
363
+ )
364
+
365
+
366
+ def get_code(program: Union[int, str]) -> str:
367
+ """Return the code of a specific lab program as a string."""
368
+ key = normalize_key(program)
369
+ return PROGRAMS[key]["code"]
370
+
371
+
372
+ def write_program(
373
+ program: Union[int, str],
374
+ filename: Optional[str] = None,
375
+ dest_dir: Optional[Union[str, Path]] = None,
376
+ overwrite: bool = True,
377
+ quiet: bool = False,
378
+ ) -> Path:
379
+ """
380
+ Write the code for a lab program to a file.
381
+
382
+ Args:
383
+ program: Identifier for the lab (e.g. 1, '7a', 'rsa', 'lab3').
384
+ filename: Custom destination filename. Defaults to standard lab filename (e.g. '1.py').
385
+ dest_dir: Target directory (defaults to current working directory).
386
+ overwrite: Overwrite existing file if True (defaults to True).
387
+ quiet: Suppress stdout message if True.
388
+
389
+ Returns:
390
+ Path: Path object pointing to the created file.
391
+ """
392
+ key = normalize_key(program)
393
+ meta = PROGRAMS[key]
394
+ out_filename = filename or meta["filename"]
395
+ out_path = Path(dest_dir or ".").resolve() / out_filename
396
+
397
+ if out_path.exists() and not overwrite:
398
+ if not quiet:
399
+ print(f"[!] Skipped '{out_filename}': file already exists and overwrite=False.")
400
+ return out_path
401
+
402
+ out_path.parent.mkdir(parents=True, exist_ok=True)
403
+ out_path.write_text(meta["code"], encoding="utf-8")
404
+
405
+ if not quiet:
406
+ print(f"[+] Created '{out_filename}' ({meta['title']})")
407
+
408
+ return out_path
409
+
410
+
411
+ # Individual functions for each lab program
412
+ def lab1(filename: Optional[str] = None, dest_dir: Optional[Union[str, Path]] = None) -> Path:
413
+ """Create Caesar Cipher (1.py)"""
414
+ return write_program("1", filename=filename, dest_dir=dest_dir)
415
+
416
+ def lab2(filename: Optional[str] = None, dest_dir: Optional[Union[str, Path]] = None) -> Path:
417
+ """Create Transposition Cipher (2.py)"""
418
+ return write_program("2", filename=filename, dest_dir=dest_dir)
419
+
420
+ def lab3(filename: Optional[str] = None, dest_dir: Optional[Union[str, Path]] = None) -> Path:
421
+ """Create Image-Based Steganography (3.py)"""
422
+ return write_program("3", filename=filename, dest_dir=dest_dir)
423
+
424
+ def lab4(filename: Optional[str] = None, dest_dir: Optional[Union[str, Path]] = None) -> Path:
425
+ """Create GCD & Modular Inverse (4.py)"""
426
+ return write_program("4", filename=filename, dest_dir=dest_dir)
427
+
428
+ def lab5(filename: Optional[str] = None, dest_dir: Optional[Union[str, Path]] = None) -> Path:
429
+ """Create Modular Exponentiation & Inverse (5.py)"""
430
+ return write_program("5", filename=filename, dest_dir=dest_dir)
431
+
432
+ def lab6(filename: Optional[str] = None, dest_dir: Optional[Union[str, Path]] = None) -> Path:
433
+ """Create DES Cipher (6.py)"""
434
+ return write_program("6", filename=filename, dest_dir=dest_dir)
435
+
436
+ def lab7a(filename: Optional[str] = None, dest_dir: Optional[Union[str, Path]] = None) -> Path:
437
+ """Create AES ECB Mode (7a.py)"""
438
+ return write_program("7a", filename=filename, dest_dir=dest_dir)
439
+
440
+ def lab7b(filename: Optional[str] = None, dest_dir: Optional[Union[str, Path]] = None) -> Path:
441
+ """Create AES CBC Mode (7b.py)"""
442
+ return write_program("7b", filename=filename, dest_dir=dest_dir)
443
+
444
+ def lab8(filename: Optional[str] = None, dest_dir: Optional[Union[str, Path]] = None) -> Path:
445
+ """Create RSA Cryptosystem (8.py)"""
446
+ return write_program("8", filename=filename, dest_dir=dest_dir)
447
+
448
+ def lab9(filename: Optional[str] = None, dest_dir: Optional[Union[str, Path]] = None) -> Path:
449
+ """Create Diffie-Hellman Key Exchange (9.py)"""
450
+ return write_program("9", filename=filename, dest_dir=dest_dir)
451
+
452
+ def lab10(filename: Optional[str] = None, dest_dir: Optional[Union[str, Path]] = None) -> Path:
453
+ """Create SHA-256 & HMAC (10.py)"""
454
+ return write_program("10", filename=filename, dest_dir=dest_dir)
455
+
456
+ def lab11(filename: Optional[str] = None, dest_dir: Optional[Union[str, Path]] = None) -> Path:
457
+ """Create Digital Signature RSA + SHA-256 (11.py)"""
458
+ return write_program("11", filename=filename, dest_dir=dest_dir)
459
+
460
+
461
+ # Short aliases p1..p11
462
+ p1 = lab1
463
+ p2 = lab2
464
+ p3 = lab3
465
+ p4 = lab4
466
+ p5 = lab5
467
+ p6 = lab6
468
+ p7a = lab7a
469
+ p7b = lab7b
470
+ p8 = lab8
471
+ p9 = lab9
472
+ p10 = lab10
473
+ p11 = lab11
474
+
475
+ # Descriptive aliases
476
+ caesar = lab1
477
+ transposition = lab2
478
+ stego = lab3
479
+ steganography = lab3
480
+ gcd = lab4
481
+ mod_arith = lab5
482
+ des = lab6
483
+ aes_ecb = lab7a
484
+ aes_cbc = lab7b
485
+ rsa = lab8
486
+ diffie_hellman = lab9
487
+ sha = lab10
488
+ hmac = lab10
489
+ digital_signature = lab11
490
+
491
+
492
+ def create_all(dest_dir: Optional[Union[str, Path]] = None, overwrite: bool = True) -> Dict[str, Path]:
493
+ """
494
+ Generate all lab program files at once in the specified directory.
495
+
496
+ Args:
497
+ dest_dir: Target directory (default: current directory).
498
+ overwrite: Overwrite existing files (default: True).
499
+
500
+ Returns:
501
+ dict: Mapping of program key to created Path object.
502
+ """
503
+ created = {}
504
+ print("=" * 60)
505
+ print("Creating all CNS Lab practice programs (Offline)...")
506
+ print("=" * 60)
507
+ for key in PROGRAMS:
508
+ created[key] = write_program(key, dest_dir=dest_dir, overwrite=overwrite)
509
+ print("=" * 60)
510
+ print(f"Successfully generated {len(created)} lab programs.")
511
+ return created
512
+
513
+
514
+ dump_all = create_all
515
+
516
+
517
+ def list_programs() -> None:
518
+ """Print a clean table of all available lab programs and their functions."""
519
+ print("=" * 75)
520
+ print(f"{'Key':<6} {'Filename':<10} {'Function':<12} {'Description'}")
521
+ print("-" * 75)
522
+ for key, meta in PROGRAMS.items():
523
+ fn_name = f"p{key}()"
524
+ print(f"{key:<6} {meta['filename']:<10} {fn_name:<12} {meta['title']}")
525
+ print("=" * 75)
526
+ print("Usage:")
527
+ print(" import cnslab")
528
+ print(" cnslab.p1() # Creates 1.py")
529
+ print(" cnslab.p7a() # Creates 7a.py")
530
+ print(" cnslab.create_all() # Creates all files")
531
+ print("=" * 75)
532
+
533
+
534
+ def create_sample_image(filename: str = "image.png", dest_dir: Optional[Union[str, Path]] = None) -> Path:
535
+ """
536
+ Creates a minimal valid PNG image completely offline for testing Lab 3 (Steganography).
537
+ Uses a hardcoded base64/binary PNG header without needing PIL or external tools.
538
+ """
539
+ # 1x1 valid RGB PNG bytes
540
+ png_bytes = (
541
+ b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x02'
542
+ b'\x00\x00\x00\x90wS\xde\x00\x00\x00\x0cIDATx\x9cc\xf8\xcf\xc0\x00\x00\x03\x01'
543
+ b'\x01\x00\x18\xdd\x8d\xb0\x00\x00\x00\x00IEND\xaeB`\x82'
544
+ )
545
+ out_path = Path(dest_dir or ".").resolve() / filename
546
+ out_path.parent.mkdir(parents=True, exist_ok=True)
547
+ out_path.write_bytes(png_bytes)
548
+ print(f"[+] Created sample offline image '{filename}' for Steganography.")
549
+ return out_path
cryptodown/__init__.py ADDED
@@ -0,0 +1,2 @@
1
+ from cnslab import *
2
+ from cnslab import __version__, __all__, PROGRAMS
cryptodown/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from cnslab.cli import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
@@ -0,0 +1,137 @@
1
+ Metadata-Version: 2.4
2
+ Name: cryptodown
3
+ Version: 1.0.0
4
+ Summary: Offline CNS Lab Program Generator for Lab Exams
5
+ Author: namkeenbiskoot
6
+ Classifier: Programming Language :: Python :: 3
7
+ Classifier: Operating System :: OS Independent
8
+ Classifier: Topic :: Education
9
+ Classifier: Topic :: Security :: Cryptography
10
+ Requires-Python: >=3.7
11
+ Description-Content-Type: text/markdown
12
+ Dynamic: requires-python
13
+
14
+ # cryptodown (Offline CNS Lab Program Generator)
15
+
16
+ An offline Python package that generates all Cryptography and Network Security (CNS) laboratory exam programs with a single function call or CLI command.
17
+
18
+ Works **100% offline** with zero external network requests and zero non-standard runtime dependencies for the generator.
19
+
20
+ ---
21
+
22
+ ## 🚀 Quick Start & Installation
23
+
24
+ ### Option 1: Install from GitHub
25
+ ```bash
26
+ pip install git+https://github.com/namkeenbiskoot/cryptodown.git
27
+ ```
28
+
29
+ ### Option 2: Install from source folder (Offline)
30
+ In this directory, open a terminal and run:
31
+ ```bash
32
+ pip install .
33
+ ```
34
+
35
+ ### Option 3: Install from pre-built Wheel (`.whl`)
36
+ You can copy the built `.whl` from the `dist/` directory to any lab computer (even one without internet) and run:
37
+ ```bash
38
+ pip install cryptodown-1.0.0-py3-none-any.whl
39
+ ```
40
+
41
+ ---
42
+
43
+ ## 🐍 Python Usage
44
+
45
+ You can import `cryptodown` (or `cnslab`) in any Python shell or script and call the function for the lab program you need:
46
+
47
+ ```python
48
+ import cryptodown as cns
49
+
50
+ # Generates 1.py (Caesar Cipher)
51
+ cns.p1()
52
+
53
+ # Generates 7a.py (AES ECB)
54
+ cns.p7a()
55
+
56
+ # Generates 8.py (RSA)
57
+ cns.p8()
58
+
59
+ # Generate ALL lab files at once (1.py - 11.py)
60
+ cns.create_all()
61
+
62
+ # View catalog of all programs
63
+ cns.list_programs()
64
+ ```
65
+
66
+ ### Alternatively, use star import:
67
+ ```python
68
+ from cryptodown import *
69
+
70
+ p1() # creates 1.py
71
+ p2() # creates 2.py
72
+ p6() # creates 6.py
73
+ p7b() # creates 7b.py
74
+ ```
75
+
76
+ ### Custom Filenames & Output Directories
77
+ Every function accepts an optional `filename` and `dest_dir`:
78
+ ```python
79
+ cns.p1(filename="my_caesar.py")
80
+ cns.p8(dest_dir="./output_folder")
81
+ ```
82
+
83
+ ---
84
+
85
+ ## 💻 Terminal / CLI Usage
86
+
87
+ Once installed, use `cryptodown`, `cnslab`, or `cns` directly from your command prompt:
88
+
89
+ ```bash
90
+ # Generate 1.py
91
+ cryptodown 1
92
+
93
+ # Generate 7a.py
94
+ cryptodown 7a
95
+
96
+ # Generate all lab programs
97
+ cryptodown all
98
+
99
+ # List all available programs
100
+ cryptodown list
101
+
102
+ # Print code to terminal without creating a file
103
+ cryptodown 1 --print
104
+
105
+ # Generate sample 1x1 image for steganography testing
106
+ cryptodown image
107
+ ```
108
+
109
+ *(You can also invoke via python module: `python -m cryptodown 1`)*
110
+
111
+ ---
112
+
113
+ ## 📋 Available Lab Programs & Functions
114
+
115
+ | Lab | Function(s) | Default File | Algorithm / Topic |
116
+ |---|---|---|---|
117
+ | **1** | `p1()`, `lab1()`, `caesar()` | `1.py` | Caesar Cipher (Encrypt & Decrypt) |
118
+ | **2** | `p2()`, `lab2()`, `transposition()` | `2.py` | Transposition Cipher (Columnar) |
119
+ | **3** | `p3()`, `lab3()`, `stego()` | `3.py` | Image-Based Steganography (LSB) |
120
+ | **4** | `p4()`, `lab4()`, `gcd()` | `4.py` | GCD & Modular Inverse (Euclidean) |
121
+ | **5** | `p5()`, `lab5()`, `mod_arith()` | `5.py` | Modular Exponentiation & Extended GCD |
122
+ | **6** | `p6()`, `lab6()`, `des()` | `6.py` | DES Encryption & Decryption (ECB) |
123
+ | **7a**| `p7a()`, `lab7a()`, `aes_ecb()` | `7a.py` | AES Encryption & Decryption (ECB Mode) |
124
+ | **7b**| `p7b()`, `lab7b()`, `aes_cbc()` | `7b.py` | AES Encryption & Decryption (CBC Mode) |
125
+ | **8** | `p8()`, `lab8()`, `rsa()` | `8.py` | RSA Public Key Cryptosystem |
126
+ | **9** | `p9()`, `lab9()`, `diffie_hellman()` | `9.py` | Diffie-Hellman Key Exchange |
127
+ | **10**| `p10()`, `lab10()`, `sha()`, `hmac()` | `10.py` | SHA-256 Hash & HMAC Verification |
128
+ | **11**| `p11()`, `lab11()`, `digital_signature()` | `11.py` | Digital Signature (RSA + SHA-256) |
129
+
130
+ ---
131
+
132
+ ## 📦 Running the Generated Programs
133
+
134
+ The generator itself requires only the standard library. The generated lab programs use standard security libraries commonly pre-installed or required for the lab:
135
+ - `pycryptodome` (for DES, AES, RSA signatures): `pip install pycryptodome`
136
+ - `stegano` (for Lab 3 steganography): `pip install stegano`
137
+ - `math`, `hashlib`, `hmac` are built into Python.
@@ -0,0 +1,11 @@
1
+ cnslab/__init__.py,sha256=eI91CvvsodG8LvL8xWbg-FWs7QYKaRkzmn-Q-X3li8A,2175
2
+ cnslab/__main__.py,sha256=MSmt_5Xg84uHqzTN38JwgseJK8rsJn_11A8WD99VtEo,61
3
+ cnslab/cli.py,sha256=3bHxZp0PeyBqJlCnfMeHtZJrACZt43Zri5qMw6o4uzM,2894
4
+ cnslab/programs.py,sha256=zxTTqXtiwrofhXbrTfF99JTpDfRxCtLNaRXgH2t4fD0,15991
5
+ cryptodown/__init__.py,sha256=BNqdJSow1BSguq7y6SkWaCUPwfZvEPrD6znp4Jiz9_0,71
6
+ cryptodown/__main__.py,sha256=Ae3GbZyIA32F2Q1ufWpMa2zhT9L-t49z1UWO7GCKmE0,67
7
+ cryptodown-1.0.0.dist-info/METADATA,sha256=1j9zjx9R7HiXobtGjQXSJBC5JSHRaqcWYYr4pNcZuS4,4095
8
+ cryptodown-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
9
+ cryptodown-1.0.0.dist-info/entry_points.txt,sha256=3rvALVv5eQd3H9B9RIc5Q685xPaDBN1PJyK1GQioJDg,94
10
+ cryptodown-1.0.0.dist-info/top_level.txt,sha256=W2uiiRWTREButMA6x3x8OZU2TToxLh6wiKpEXa8ebJU,18
11
+ cryptodown-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,4 @@
1
+ [console_scripts]
2
+ cns = cnslab.cli:main
3
+ cnslab = cnslab.cli:main
4
+ cryptodown = cnslab.cli:main
@@ -0,0 +1,2 @@
1
+ cnslab
2
+ cryptodown