cryptodome-lab 0.1.0__tar.gz

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.
Files changed (42) hide show
  1. cryptodome_lab-0.1.0/PKG-INFO +27 -0
  2. cryptodome_lab-0.1.0/README.md +20 -0
  3. cryptodome_lab-0.1.0/cryptodome_lab/__init__.py +1 -0
  4. cryptodome_lab-0.1.0/cryptodome_lab/__main__.py +33 -0
  5. cryptodome_lab-0.1.0/cryptodome_lab/practicals/Classical_Cryptography_Project_Documentation.docx +0 -0
  6. cryptodome_lab-0.1.0/cryptodome_lab/practicals/Classical_Cryptography_Project_Documentation.txt +99 -0
  7. cryptodome_lab-0.1.0/cryptodome_lab/practicals/Deff_Hell_INS_PRAC6.docx +0 -0
  8. cryptodome_lab-0.1.0/cryptodome_lab/practicals/Deff_Hell_INS_PRAC6.txt +36 -0
  9. cryptodome_lab-0.1.0/cryptodome_lab/practicals/Encrypt_decrypt___Hashing_algo.docx +0 -0
  10. cryptodome_lab-0.1.0/cryptodome_lab/practicals/Encrypt_decrypt___Hashing_algo.txt +38 -0
  11. cryptodome_lab-0.1.0/cryptodome_lab/practicals/INS_PRAC4_2.docx +0 -0
  12. cryptodome_lab-0.1.0/cryptodome_lab/practicals/INS_PRAC4_2.txt +81 -0
  13. cryptodome_lab-0.1.0/cryptodome_lab/practicals/INS_PRAC4_2_1.docx +0 -0
  14. cryptodome_lab-0.1.0/cryptodome_lab/practicals/INS_PRAC4_2_1.txt +51 -0
  15. cryptodome_lab-0.1.0/cryptodome_lab/practicals/INS_PRAC8.docx +0 -0
  16. cryptodome_lab-0.1.0/cryptodome_lab/practicals/INS_PRAC8.txt +19 -0
  17. cryptodome_lab-0.1.0/cryptodome_lab/practicals/PRACTICAL_NO_9.docx +0 -0
  18. cryptodome_lab-0.1.0/cryptodome_lab/practicals/PRACTICAL_NO_9.txt +40 -0
  19. cryptodome_lab-0.1.0/cryptodome_lab/practicals/Prac2_Ins.docx +0 -0
  20. cryptodome_lab-0.1.0/cryptodome_lab/practicals/Prac2_Ins.txt +70 -0
  21. cryptodome_lab-0.1.0/cryptodome_lab/practicals/Prac5_RSA_Algorithm_INS_Assignment.docx +0 -0
  22. cryptodome_lab-0.1.0/cryptodome_lab/practicals/Prac5_RSA_Algorithm_INS_Assignment.txt +94 -0
  23. cryptodome_lab-0.1.0/cryptodome_lab/practicals/Prac5_RSA_Algorithm_INS_Assignment_1.docx +0 -0
  24. cryptodome_lab-0.1.0/cryptodome_lab/practicals/Prac5_RSA_Algorithm_INS_Assignment_1.txt +94 -0
  25. cryptodome_lab-0.1.0/cryptodome_lab/practicals/Prac_7_MD5_INS.docx +0 -0
  26. cryptodome_lab-0.1.0/cryptodome_lab/practicals/Prac_7_MD5_INS.txt +108 -0
  27. cryptodome_lab-0.1.0/cryptodome_lab/practicals/Pract_4_1_ECB_CBC.docx +0 -0
  28. cryptodome_lab-0.1.0/cryptodome_lab/practicals/Pract_4_1_ECB_CBC.txt +121 -0
  29. cryptodome_lab-0.1.0/cryptodome_lab/practicals/Practical_10_Windows_Firewall_Blocking_1_docx.pdf +0 -0
  30. cryptodome_lab-0.1.0/cryptodome_lab/practicals/Practical_10_Windows_Firewall_Blocking_1_docx.txt +146 -0
  31. cryptodome_lab-0.1.0/cryptodome_lab/practicals/Rail_Fence_Cipher_prac5.docx +0 -0
  32. cryptodome_lab-0.1.0/cryptodome_lab/practicals/Rail_Fence_Cipher_prac5.txt +99 -0
  33. cryptodome_lab-0.1.0/cryptodome_lab/practicals/Rail_Fence_Cipher_prac5_1.docx +0 -0
  34. cryptodome_lab-0.1.0/cryptodome_lab/practicals/Rail_Fence_Cipher_prac5_1.txt +116 -0
  35. cryptodome_lab-0.1.0/cryptodome_lab/practicals/substitution_techniques_INS_prac_1.docx +0 -0
  36. cryptodome_lab-0.1.0/cryptodome_lab/practicals/substitution_techniques_INS_prac_1.txt +81 -0
  37. cryptodome_lab-0.1.0/cryptodome_lab.egg-info/PKG-INFO +27 -0
  38. cryptodome_lab-0.1.0/cryptodome_lab.egg-info/SOURCES.txt +40 -0
  39. cryptodome_lab-0.1.0/cryptodome_lab.egg-info/dependency_links.txt +1 -0
  40. cryptodome_lab-0.1.0/cryptodome_lab.egg-info/top_level.txt +1 -0
  41. cryptodome_lab-0.1.0/pyproject.toml +17 -0
  42. cryptodome_lab-0.1.0/setup.cfg +4 -0
@@ -0,0 +1,27 @@
1
+ Metadata-Version: 2.4
2
+ Name: cryptodome-lab
3
+ Version: 0.1.0
4
+ Summary: Menu-based viewer for original cryptography practical materials
5
+ Requires-Python: >=3.9
6
+ Description-Content-Type: text/markdown
7
+
8
+ # cryptodome-lab
9
+
10
+ A simple menu-based viewer for practical materials in the supplied ZIP. The name is inspired by the `Crypto.Cipher` imports found in some source practicals; this is an independent educational viewer and is not affiliated with PyCryptodome.
11
+
12
+ The original DOCX/PDF files are included byte-for-byte unchanged. Text files are extracted from those documents for output viewing. Extraction may omit formatting, images, and code shown only inside screenshots. The viewer displays material; it does not execute the practical steps.
13
+
14
+ ## Run locally
15
+ From the folder containing `pyproject.toml`:
16
+ ```cmd
17
+ python -m pip install .
18
+ python -m cryptodome_lab
19
+ ```
20
+
21
+ ## Build and upload
22
+ ```cmd
23
+ python -m pip install --upgrade build twine
24
+ python -m build
25
+ python -m twine check dist/*
26
+ python -m twine upload dist/*
27
+ ```
@@ -0,0 +1,20 @@
1
+ # cryptodome-lab
2
+
3
+ A simple menu-based viewer for practical materials in the supplied ZIP. The name is inspired by the `Crypto.Cipher` imports found in some source practicals; this is an independent educational viewer and is not affiliated with PyCryptodome.
4
+
5
+ The original DOCX/PDF files are included byte-for-byte unchanged. Text files are extracted from those documents for output viewing. Extraction may omit formatting, images, and code shown only inside screenshots. The viewer displays material; it does not execute the practical steps.
6
+
7
+ ## Run locally
8
+ From the folder containing `pyproject.toml`:
9
+ ```cmd
10
+ python -m pip install .
11
+ python -m cryptodome_lab
12
+ ```
13
+
14
+ ## Build and upload
15
+ ```cmd
16
+ python -m pip install --upgrade build twine
17
+ python -m build
18
+ python -m twine check dist/*
19
+ python -m twine upload dist/*
20
+ ```
@@ -0,0 +1 @@
1
+ """Menu-based viewer for original cryptography practical materials."""
@@ -0,0 +1,33 @@
1
+ from pathlib import Path
2
+
3
+ PRACTICALS_DIR = Path(__file__).parent / "practicals"
4
+
5
+ def main():
6
+ practicals = sorted(PRACTICALS_DIR.glob("*.txt"))
7
+ if not practicals:
8
+ print("No practical text files were found.")
9
+ return
10
+
11
+ while True:
12
+ print("\\n=== CryptoDome Lab: Practical Viewer ===")
13
+ for number, path in enumerate(practicals, 1):
14
+ print(f"{number}. {path.stem.replace('_', ' ')}")
15
+ print("0. Exit")
16
+
17
+ choice = input("\\nEnter practical number to view: ").strip()
18
+ if choice == "0":
19
+ print("Exiting CryptoDome Lab.")
20
+ break
21
+ if not choice.isdigit() or not 1 <= int(choice) <= len(practicals):
22
+ print("Invalid choice. Try again.")
23
+ continue
24
+
25
+ path = practicals[int(choice) - 1]
26
+ print("\\n" + "=" * 72)
27
+ print(path.stem.replace("_", " "))
28
+ print("=" * 72 + "\\n")
29
+ print(path.read_text(encoding="utf-8"))
30
+ input("\\nPress Enter to return to the menu...")
31
+
32
+ if __name__ == "__main__":
33
+ main()
@@ -0,0 +1,99 @@
1
+ CLASSICAL CRYPTOGRAPHY PROJECT
2
+ Implementation, Encryption, Decryption & Cipher Analysis
3
+ Project Documentation
4
+ Python-based implementation of classical encryption techniques
5
+ 1. Project Overview
6
+ The project is a classical cryptography demonstration system implemented in Python. It provides encryption and decryption functions for multiple historical ciphers and allows the same plaintext to be processed through different algorithms for comparison. The implementation also measures characteristics of the resulting ciphertext, including execution time, chi-squared score, index of coincidence, Shannon entropy, and an estimated key-space size.
7
+ The code is organized as reusable functions and an Enigma class. Input validation is included for important parameters such as cipher keys, offsets, rotor settings, and Hill cipher matrices.
8
+ 2. Ciphers Implemented
9
+ 3. Caesar Cipher and ROT13
10
+ Caesar Cipher
11
+ The Caesar implementation applies a fixed shift to each alphabetic character. Uppercase and lowercase letters are preserved, while non-alphabetic characters remain unchanged. Decryption uses the same transformation with the negative of the encryption shift.
12
+ The project also includes a brute-force function that tries all 26 possible Caesar shifts.
13
+ ROT13
14
+ ROT13 is implemented as a Caesar transformation with a fixed shift of 13. Because shifting by 13 twice returns to the original letter, the same ROT13 operation can be used in both directions.
15
+ 4. Vigenere Cipher
16
+ The Vigenere cipher uses a repeating alphabetic key. For each alphabetic character, the corresponding key character determines the shift. The key index advances only when an alphabetic character is processed, while spaces and other non-alphabetic characters are preserved.
17
+ For decryption, the key shift is subtracted instead of added. The implementation validates that the key is non-empty and contains only alphabetic characters.
18
+ 5. One-Time Pad (OTP)
19
+ The OTP implementation applies a different key character to each alphabetic character of the plaintext. The key must be at least as long as the number of alphabetic characters in the message; otherwise the program raises an error. The implementation also provides a random key-generation helper.
20
+ The generated random key is intended for the class demonstration in this project; the source code itself notes that a cryptographic secrets source would be preferred for real security.
21
+ 6. Playfair Cipher
22
+ The Playfair implementation builds a 5×5 key matrix. The letter J is merged with I, producing a 25-letter square. The keyword is placed first without duplicates, followed by the remaining alphabet letters.
23
+ Before encryption, the plaintext is converted to uppercase letters, J is changed to I, and the message is divided into pairs. If a pair contains duplicate letters, an X is inserted between them. An X is also added if the final letter has no partner.
24
+ For each pair, the code applies the standard Playfair rules: letters in the same row move right, letters in the same column move down, and letters forming a rectangle exchange columns. Decryption reverses the row and column movements.
25
+ 7. Hill Cipher
26
+ The Hill cipher implementation converts a four-letter key into a 2×2 numerical matrix using A=0 through Z=25. Plaintext is processed in pairs and multiplied by the matrix modulo 26.
27
+ A key is valid only when the matrix is invertible modulo 26. The implementation checks the determinant and requires the determinant to be relatively prime to 26. Decryption uses the modular inverse of the key matrix.
28
+ If the number of alphabetic characters is odd, the implementation pads the message with X before processing.
29
+ 8. Enigma Cipher
30
+ The Enigma implementation is represented by an Enigma class. It uses three selectable rotors, each with a fixed wiring, and a reflector. The supported rotor wirings in the project are Rotor I, Rotor II and Rotor III.
31
+ The machine is initialized with a rotor order and three starting positions. Before every alphabetic character is processed, the rotors step. The right rotor advances for each letter, and notch conditions control when the middle and left rotors advance.
32
+ During encryption, the character travels from the right rotor to the middle rotor and then the left rotor, enters the reflector, and then travels backward through the left, middle and right rotors. The rotor-position adjustment is included in both the forward and backward transformations.
33
+ Enigma is reciprocal in this implementation. Therefore, a fresh machine with the same rotor order and starting positions can process the ciphertext again to recover the original plaintext.
34
+ 9. Wheel / Jefferson Disk Cipher
35
+ The Wheel cipher implementation uses multiple shuffled alphabet disks. Six disks are used by default. The disks are generated from a keyword; the keyword and disk number are used to initialize the random generator, so the same keyword recreates the same disk arrangement.
36
+ During encryption, the program selects disks cyclically. For each alphabetic character, it finds the character's position on the selected disk, adds the specified offset modulo 26, and outputs the character at the new position.
37
+ Decryption regenerates the same disks using the keyword and subtracts the same offset. Non-alphabetic characters are preserved.
38
+ 10. Ciphertext Analysis
39
+ Letter Frequency
40
+ The project counts occurrences of A–Z characters in a case-insensitive manner. This frequency information is used by the statistical analysis functions.
41
+ Chi-Squared Score
42
+ The chi-squared score compares observed letter frequencies with standard English frequencies. The implementation uses a lower score to indicate a ciphertext distribution that resembles natural English more closely.
43
+ Index of Coincidence
44
+ The Index of Coincidence measures how frequently pairs of letters are likely to match. The source documentation notes that values around 0.067 resemble natural English while lower values can indicate a more uniform distribution.
45
+ Shannon Entropy
46
+ Shannon entropy is calculated in bits per character using the A–Z distribution. The maximum possible entropy for a 26-letter alphabet is approximately log2(26), or 4.70 bits per character. Higher entropy represents greater unpredictability in the observed distribution.
47
+ Execution Time and Key Space
48
+ The project measures execution time using a high-resolution performance timer. It also records an estimated key-space size in bits for the implemented ciphers. For example, Caesar has 26 possible shifts, while the Wheel configuration uses six permutations of a 26-letter alphabet.
49
+ 11. Common Comparison Function
50
+ The compare_all function processes the same plaintext through the selected ciphers and creates a common result row for each cipher. Each row contains the cipher name, ciphertext, execution time, chi-squared score, index of coincidence, entropy, and key-space information.
51
+ This makes it possible to compare different classical techniques using consistent measurements rather than looking only at the encrypted text.
52
+ 12. Testing and Validation
53
+ The project includes a main test section that encrypts a sample message with every implemented cipher and then decrypts it. For the reversible cases, assertions are used to verify that the original plaintext is recovered.
54
+ The source test section ends with a message indicating that all round-trip tests passed when the expected results are obtained.
55
+ 13. Program Structure
56
+ 14. Conclusion
57
+ This project demonstrates how different classical cryptographic techniques transform plaintext into ciphertext using different mathematical and mechanical ideas. The project covers simple substitution, polyalphabetic encryption, pair-based methods, matrix-based encryption, rotor-based encryption, and disk-based encryption.
58
+ Beyond encryption and decryption, the project provides a practical comparison layer using execution time, statistical characteristics, entropy, and key-space estimates. The included round-trip tests provide a basic functional validation of the implementations.
59
+ The project is intended as an educational demonstration of classical cryptography and comparative cipher analysis rather than as a replacement for modern cryptographic standards.
60
+
61
+ [TABLE 1]
62
+ Project Area | Details
63
+ Programming Language | Python
64
+ Main Objective | Implement and compare classical cryptographic ciphers
65
+ Encryption Modes | Caesar, ROT13, Vigenere, OTP, Playfair, Hill, Enigma, Wheel/Jefferson Disk
66
+ Analysis | Chi-squared score, Index of Coincidence, Shannon entropy, timing and key-space comparison
67
+ Validation | Round-trip encryption/decryption tests
68
+
69
+ [TABLE 2]
70
+ Cipher | Basic Principle | Key / Setting
71
+ Caesar | Shifts alphabetic characters by a fixed amount. | Integer shift
72
+ ROT13 | Special Caesar transformation using a fixed 13-position shift. | No variable key
73
+ Vigenere | Uses repeating key letters to apply changing Caesar shifts. | Alphabetic key
74
+ One-Time Pad (OTP) | Applies a key-dependent shift to each alphabetic character. | Key at least as long as message letters
75
+ Playfair | Encrypts pairs of letters using a 5×5 key square. | Alphabetic keyword
76
+ Hill | Encrypts pairs using a 2×2 matrix modulo 26. | Exactly four letters; matrix must be invertible
77
+ Enigma | Uses three rotors, a reflector, and changing rotor positions. | Rotor order + starting positions
78
+ Wheel / Jefferson Disk | Uses shuffled alphabet disks and a position offset. | Keyword + offset
79
+
80
+ [TABLE 3]
81
+ Tested Component | Validation
82
+ Caesar | Encrypt then decrypt and compare with original sample
83
+ ROT13 | Apply ROT13 twice and compare with original
84
+ Vigenere | Encrypt and decrypt using the same key
85
+ OTP | Encrypt and decrypt using the generated key
86
+ Playfair | Encrypt and decrypt using the same keyword
87
+ Hill | Generate a valid key, encrypt, decrypt, and inspect the result
88
+ Enigma | Process ciphertext again using the same rotor settings
89
+ Wheel | Encrypt and decrypt using the same keyword and offset
90
+
91
+ [TABLE 4]
92
+ Component | Responsibility
93
+ Cipher functions | Provide independent encryption/decryption implementations.
94
+ Enigma class | Maintains rotor wiring, positions, stepping, and character processing.
95
+ Statistical analysis | Calculates frequency, chi-squared, coincidence, and entropy metrics.
96
+ Timing helper | Measures execution time of a cipher operation.
97
+ Comparison function | Runs selected ciphers on the same plaintext and collects common metrics.
98
+ Validation / errors | Checks keys, lengths, types, and valid Hill matrices.
99
+ Main test section | Runs sample round-trip tests for the implemented algorithms.
@@ -0,0 +1,36 @@
1
+ PRACTICAL NO:6
2
+ DIFFIE-HELLMAN KEY EXCHANGE ALGORITHM
3
+ Diffie-Hellman is a mathematical problem that is the foundation for many cryptographic protocols. Diffie-Hellman is one of the greatest inventions in Cybersecurity. This revolutionary algorithm was proposed by Whitfield Diffie and Martin Hellman in 1976, enabling two entities to agree upon a secret key without prior arrangements, even in the presence of potential eavesdroppers. Diffie-Hellman offers a powerful solution to secure key exchange which has always been challenging and prone to alteration, thus ensuring confidentiality and integrity in information.
4
+ CODE:
5
+ import random
6
+ def power(base,exponent,mod):
7
+ result=1
8
+ base=base%mod
9
+ while exponent > 0:
10
+ if exponent % 2 == 1:
11
+ result=(result*base)%mod
12
+ exponent=exponent >> 1
13
+ base=(base*base) % mod
14
+ return result
15
+ p=19
16
+ g=5
17
+ a_private=random.randint(1,p-2)
18
+ a_public=power(g,a_private,p)
19
+ b_private=random.randint(1,p-2)
20
+ b_public=power(g,b_private,p)
21
+ a_shared_key=power(b_public,a_private,p)
22
+ b_shared_key=power(a_public,b_private,p)
23
+ print("Public parameters:")
24
+ print(f"Prime (p): {p}")
25
+ print(f"Primitive root (g)|: {g} \n")
26
+ print("Alice's private key:",a_private)
27
+ print("Alice's public key:",a_public)
28
+ print("Bob's private key:",b_private)
29
+ print("Bob's public key:",b_public)
30
+ print("\nShared key computed by Alice:",a_shared_key)
31
+ print("Shared key computed by Bob:",b_shared_key)
32
+ if a_shared_key == b_shared_key:
33
+ print("\nKey exchange successful!! Shared symmetric key established. ")
34
+ else:
35
+ print("\nKey exchange failed. ")
36
+ OUTPUT:
@@ -0,0 +1,38 @@
1
+ Prac 1:-Encrypt and decrypt algo
2
+ Code:-
3
+ def encrypt(text,s):
4
+ result=""
5
+ for i in range(len(text)):
6
+ char=text[i]
7
+ if (char.isupper()):
8
+ result+=chr((ord(char) + s-65) % 26 +65)
9
+ else:
10
+ result+=chr((ord(char) + s-97) % 26 +97)
11
+ return result
12
+ def decrypt(text,s):
13
+ result=""
14
+ for i in range(len(text)):
15
+ char=text[i]
16
+ if (char.isupper()):
17
+ result+=chr((ord(char) - s-65) % 26 +65)
18
+ else:
19
+ result+=chr((ord(char) - s-97) % 26 +97)
20
+ return result
21
+ text="attackontitan"
22
+ s=5
23
+ print("text is:",text)
24
+ print("shift of:",s)
25
+ print("encrypted result:",encrypt(text,s))
26
+ de=encrypt(text,s)
27
+ print(decrypt(de,s))
28
+ Output:-
29
+ 2.Hashing
30
+ import bcrypt
31
+ pwd=b'Mypass'
32
+ salt=bcrypt.gensalt()
33
+ hashed=bcrypt.hashpw(pwd,salt)
34
+ print("Salt :")
35
+ print(salt)
36
+ print("Hashed")
37
+ print(hashed)
38
+ Output:-
@@ -0,0 +1,81 @@
1
+ PRACTICAL NO: 4.2
2
+ AES
3
+ CBC
4
+ CODE:
5
+ from Crypto.Cipher import AES
6
+ from Crypto.Random import get_random_bytes
7
+ import base64
8
+ def pad(data):
9
+ pad_len=16-(len(data)%16)
10
+ return data+chr(pad_len) * pad_len
11
+ def unpad(data):
12
+ pad_len=ord(data[-1])
13
+ return data[:-pad_len]
14
+ def encrypt_aes(palin_text,key):
15
+ iv=get_random_bytes(16)
16
+ cipher=AES.new(key,AES.MODE_CBC,iv)
17
+ padded_text=pad(palin_text)
18
+ encrypted=cipher.encrypt(padded_text.encode('utf-8'))
19
+ return base64.b64encode(iv+encrypted).decode('utf-8')
20
+ def decrypt_aes(cipher_text,key):
21
+ raw=base64.b64decode(cipher_text)
22
+ iv=raw[:16]
23
+ encrypted=raw[16:]
24
+ cipher=AES.new(key,AES.MODE_CBC,iv)
25
+ decrypted=cipher.decrypt(encrypted).decode('utf-8')
26
+ return unpad(decrypted)
27
+ if __name__=="__main__":
28
+ key=get_random_bytes(16)
29
+ print("AES key (base64):",base64.b64encode(key).decode("utf-8"))
30
+ msg="Hello,AES encryption!"
31
+ print("Original msg:",msg)
32
+ encrypted=encrypt_aes(msg,key)
33
+ print("Encrypted (Base64):",encrypted)
34
+ decrypted=decrypt_aes(encrypted,key)
35
+ print("Decrypted (Base64):",decrypted)
36
+ OUTPUT:
37
+ ECB
38
+ CODE:
39
+ from Crypto.Cipher import AES
40
+ from Crypto.Util.Padding import pad,unpad
41
+ key=b'SixteenByteKey12'
42
+ data=b'Secure Database Payload Data'
43
+ cipher_encrypt=AES.new(key,AES.MODE_ECB)
44
+ padded_data=pad(data,AES.block_size)
45
+ ciphertext=cipher_encrypt.encrypt(padded_data)
46
+ cipher_decrypt=AES.new(key,AES.MODE_ECB)
47
+ decrypted_padded=cipher_decrypt.decrypt(ciphertext)
48
+ original_data=unpad(decrypted_padded,AES.block_size)
49
+ print(f"Ciphertext (Hex) : {ciphertext.hex()}")
50
+ print(f"Decrypted Data: {original_data.decode()}")
51
+ OUTPUT:
52
+ from Crypto.Cipher import AES
53
+ from Crypto.Util.Padding import pad, unpad
54
+ from Crypto.Random import get_random_bytes
55
+ # 16-byte AES key (AES-128)
56
+ key = b"1234567890abcdef"
57
+ # Generate a random IV
58
+ iv = get_random_bytes(16)
59
+ # ---------- Encryption ----------
60
+ input_file = "C:/Users/Admin/Downloads/simple.txt"
61
+ encrypted_file = "encrypted.bin"
62
+ with open(input_file, "rb") as f:
63
+ plaintext = f.read()
64
+ cipher = AES.new(key, AES.MODE_CBC, iv)
65
+ ciphertext = cipher.encrypt(pad(plaintext, AES.block_size))
66
+ with open(encrypted_file, "wb") as f:
67
+ # Store IV followed by ciphertext
68
+ f.write(iv)
69
+ f.write(ciphertext)
70
+ print("File encrypted successfully as:", encrypted_file)
71
+ # ---------- Decryption ----------
72
+ decrypted_file = "decrypted_file"
73
+ with open(encrypted_file, "rb") as f:
74
+ iv = f.read(16) # Read IV
75
+ ciphertext = f.read() # Read ciphertext
76
+ cipher = AES.new(key, AES.MODE_CBC, iv)
77
+ decrypted_data = unpad(cipher.decrypt(ciphertext), AES.block_size)
78
+ with open(decrypted_file, "wb") as f:
79
+ f.write(decrypted_data)
80
+ print("File decrypted successfully as:", decrypted_file)
81
+ Output:-
@@ -0,0 +1,51 @@
1
+ PRACTICAL NO: 4.2
2
+ AES
3
+ CBC
4
+ CODE:
5
+ from Crypto.Cipher import AES
6
+ from Crypto.Random import get_random_bytes
7
+ import base64
8
+ def pad(data):
9
+ pad_len=16-(len(data)%16)
10
+ return data+chr(pad_len) * pad_len
11
+ def unpad(data):
12
+ pad_len=ord(data[-1])
13
+ return data[:-pad_len]
14
+ def encrypt_aes(palin_text,key):
15
+ iv=get_random_bytes(16)
16
+ cipher=AES.new(key,AES.MODE_CBC,iv)
17
+ padded_text=pad(palin_text)
18
+ encrypted=cipher.encrypt(padded_text.encode('utf-8'))
19
+ return base64.b64encode(iv+encrypted).decode('utf-8')
20
+ def decrypt_aes(cipher_text,key):
21
+ raw=base64.b64decode(cipher_text)
22
+ iv=raw[:16]
23
+ encrypted=raw[16:]
24
+ cipher=AES.new(key,AES.MODE_CBC,iv)
25
+ decrypted=cipher.decrypt(encrypted).decode('utf-8')
26
+ return unpad(decrypted)
27
+ if __name__=="__main__":
28
+ key=get_random_bytes(16)
29
+ print("AES key (base64):",base64.b64encode(key).decode("utf-8"))
30
+ msg="Hello,AES encryption!"
31
+ print("Original msg:",msg)
32
+ encrypted=encrypt_aes(msg,key)
33
+ print("Encrypted (Base64):",encrypted)
34
+ decrypted=decrypt_aes(encrypted,key)
35
+ print("Decrypted (Base64):",decrypted)
36
+ OUTPUT:
37
+ ECB
38
+ CODE:
39
+ from Crypto.Cipher import AES
40
+ from Crypto.Util.Padding import pad,unpad
41
+ key=b'SixteenByteKey12'
42
+ data=b'Secure Database Payload Data'
43
+ cipher_encrypt=AES.new(key,AES.MODE_ECB)
44
+ padded_data=pad(data,AES.block_size)
45
+ ciphertext=cipher_encrypt.encrypt(padded_data)
46
+ cipher_decrypt=AES.new(key,AES.MODE_ECB)
47
+ decrypted_padded=cipher_decrypt.decrypt(ciphertext)
48
+ original_data=unpad(decrypted_padded,AES.block_size)
49
+ print(f"Ciphertext (Hex) : {ciphertext.hex()}")
50
+ print(f"Decrypted Data: {original_data.decode()}")
51
+ OUTPUT:
@@ -0,0 +1,19 @@
1
+ PRACTICAL NO:8
2
+ HMAC-SHA1
3
+ Aim
4
+ To write a Python program to calculate the HMAC-SHA1 (Hash-based Message Authentication Code using SHA-1) signature for a given message and secret key.
5
+ Introduction
6
+ HMAC stands for Hash-based Message Authentication Code. It is a mechanism used to verify the integrity and authenticity of a message. HMAC uses a cryptographic hash function together with a secret key. Both the sender and receiver must know the same secret key.
7
+ HMAC-SHA1 uses the SHA-1 hash algorithm as its underlying hash function. The result of HMAC-SHA1 is a 160-bit (20-byte) message authentication code, normally displayed as 40 hexadecimal characters.
8
+ Need for HMAC
9
+ A normal hash function can detect accidental changes to data, but by itself it does not prove who generated the hash. An attacker who changes a message could also calculate a new ordinary hash. HMAC solves this problem by combining the message with a secret key that is known only to the communicating parties.
10
+ HMAC-SHA1
11
+ In HMAC-SHA1, SHA-1 is used as the hash function. The secret key is
12
+ processed according to the HMAC construction and combined with the
13
+ message using two fixed padding values called ipad and opad.
14
+ 8.1
15
+ CODE:
16
+ OUTPUT:
17
+ 8.2
18
+ CODE:
19
+ OUTPUT:
@@ -0,0 +1,40 @@
1
+ PRACTICAL NO:9
2
+ OPENSSL IMPLEMENTATION
3
+ 1.open terminal run as admin
4
+ 2.locate to bin folder of openssl
5
+ 3.run command
6
+ openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365 -nodes
7
+ 4.cert.pem and key.pem is been created cut and paste in a same folder where server and client
8
+ server.py
9
+ import socket
10
+ import ssl
11
+ host = 'localhost'
12
+ port = 8443
13
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
14
+ sock.bind((host, port))
15
+ sock.listen(5)
16
+ print(f"[*] Listening on https://{host}:{port}")
17
+ context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
18
+ context.load_cert_chain(certfile="cert.pem", keyfile="key.pem")
19
+ while True:
20
+ client_socket, addr = sock.accept()
21
+ print(f"[+] Connection from {addr}")
22
+ with context.wrap_socket(client_socket, server_side=True) as ssock:
23
+ data = ssock.recv(1024).decode()
24
+ print("[Client says]:", data)
25
+ ssock.sendall(b"Hello from secure server!")
26
+ client.py
27
+ import socket
28
+ import ssl
29
+ hostname = "localhost"
30
+ port = 8443
31
+ context = ssl.create_default_context()
32
+ context.check_hostname = False
33
+ context.verify_mode = ssl.CERT_NONE # Allow self-signed certs
34
+ with socket.create_connection((hostname, port)) as sock:
35
+ with context.wrap_socket(sock, server_hostname=hostname) as ssock:
36
+ ssock.sendall(b"Hello secure server!")
37
+ print("[Server says]:", ssock.recv(1024).decode())
38
+ All in same folder
39
+ 5.run server.py
40
+ 6.run client.py
@@ -0,0 +1,70 @@
1
+ Prac 2:Ins
2
+ 1.Vernam cipher
3
+ Code:-
4
+ def vernam_encrypt(plaintext, key):
5
+ if len(plaintext)!=len(key):
6
+ raise ValueError("key must be same length as plaintext.")
7
+ return ''.join(chr(ord(p)^ ord(k)) for p,k in zip(plaintext,key))
8
+ def vernam_decrypt(ciphertext,key):
9
+ return vernam_encrypt(ciphertext,key)
10
+ plaintext=input("enter text to encrypt:")
11
+ key=input("please enter key same length as text:")
12
+ ciphertext=vernam_encrypt(plaintext,key)
13
+ print("Encrypted:",ciphertext)
14
+ decrypt=vernam_decrypt(ciphertext,key)
15
+ print("Decrypted:",decrypt)
16
+ Output:-
17
+ 2.Playfair cipher
18
+ Code:-
19
+ def prepare_key_matrix(key):
20
+ key=key.upper().replace("J","I")
21
+ seen=set()
22
+ key_matrix=[]
23
+ for char in key:
24
+ if char not in seen and char.isalpha():
25
+ seen.add(char)
26
+ key_matrix.append(char)
27
+ for char in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
28
+ if char not in seen:
29
+ seen.add(char)
30
+ key_matrix.append(char)
31
+ return [key_matrix[i:i+5] for i in range (0,25,5)]
32
+ def find_position(matrix,char):
33
+ for row_idx,row in enumerate(matrix):
34
+ if char in row:
35
+ return row_idx,row.index(char)
36
+ return None,None
37
+ def encrypt_digraph(digraph,matrix):
38
+ a,b=digraph
39
+ row1,col1=find_position(matrix, a)
40
+ row2,col2=find_position(matrix, b)
41
+ if row1== row2:
42
+ return matrix[row1][(col1 +1)%5] +matrix[row2][(col2 +1)%5]
43
+ elif col1 == col2:
44
+ return matrix[(row1 +1)%5][col1] +matrix[(row2+1)%5][col2]
45
+ else:
46
+ return matrix[row1][col2]+matrix[row2][col1]
47
+ def prepare_plaintext(text) :
48
+ text=text.upper().replace("J","I").replace(" ","")
49
+ cleaned=[]
50
+ i=0
51
+ while i<len(text):
52
+ a=text[i]
53
+ b=text[i+1] if i+1 <len(text) else "X"
54
+ if a==b:
55
+ cleaned.append(a +"X")
56
+ i+=1
57
+ else:
58
+ cleaned.append(a+b)
59
+ i+=2
60
+ if len(cleaned[-1]) ==1:
61
+ cleaned[-1] +="X"
62
+ return cleaned
63
+ def playfair_encrypt(plaintext,key):
64
+ matrix=prepare_key_matrix(key)
65
+ digraphs=prepare_plaintext(plaintext)
66
+ ciphertext=''.join(encrypt_digraph(pair,matrix) for pair in digraphs)
67
+ return ciphertext
68
+ cipher=playfair_encrypt("hell o","monarchy")
69
+ print(cipher)
70
+ Output:-
@@ -0,0 +1,94 @@
1
+ Prac 5:RSA Algorithm
2
+ Code:-
3
+ def gcd(a,b):
4
+ while b:
5
+ a,b=b,a%b
6
+ return a
7
+ def mod_inverse(e,phi):
8
+ for d in range(1,phi):
9
+ if (e*d)%phi==1:
10
+ return d
11
+ return None
12
+ def encrypt(public_key,plaintext):
13
+ e,n=public_key
14
+ cipher=[pow(ord(char),e,n) for char in plaintext]
15
+ return cipher
16
+ def decrypt(private_key,ciphertext):
17
+ d,n=private_key
18
+ plain=''.join(chr(pow(char,d,n))for char in ciphertext)
19
+ return plain
20
+ p=61
21
+ q=53
22
+ n=p*q
23
+ phi=(p-1)*(q-1)
24
+ e=17
25
+ while gcd(e,phi)!=1:
26
+ e+=2
27
+ d=mod_inverse(e,phi)
28
+ public_key=(e,n)
29
+ private_key=(d,n)
30
+ msg=input("Enter the message:")
31
+ cipher_text=encrypt(public_key,msg)
32
+ decrypted_text=decrypt(private_key,cipher_text)
33
+ print("public key:",public_key)
34
+ print("private key:",private_key)
35
+ print(e)
36
+ print("original msg:",msg)
37
+ print("Encrypted:",cipher_text)
38
+ print("Decrypted:",decrypted_text)
39
+ Output:-
40
+ RSA Assingment:-
41
+ Code:-
42
+ import hashlib
43
+ def gcd(a,b):
44
+ while b:
45
+ a,b=b,a%b
46
+ return a
47
+ def mod_inverse(e,phi):
48
+ for d in range(1,phi):
49
+ if (e*d)%phi==1:
50
+ return d
51
+ return None
52
+ def encrypt(public_key,plaintext):
53
+ e,n=public_key
54
+ cipher=[pow(ord(char),e,n) for char in plaintext]
55
+ return cipher
56
+ def decrypt(private_key,ciphertext):
57
+ d,n=private_key
58
+ plain=''.join(chr(pow(char,d,n))for char in ciphertext)
59
+ return plain
60
+ p=61
61
+ q=53
62
+ n=p*q
63
+ phi=(p-1)*(q-1)
64
+ e=17
65
+ while gcd(e,phi)!=1:
66
+ e+=2
67
+ d=mod_inverse(e,phi)
68
+ public_key=(e,n)
69
+ private_key=(d,n)
70
+ msg=input("Enter the msg:")
71
+ cipher_text=encrypt(public_key,msg)
72
+ decrypted_text=decrypt(private_key,cipher_text)
73
+ print("public key:",public_key)
74
+ print("private key:",private_key)
75
+ print("original msg:",msg)
76
+ print("Encrypted:",cipher_text)
77
+ print("Decrypted:",decrypted_text)
78
+ hash_hex = hashlib.sha256(msg.encode('utf-8')).hexdigest()
79
+ hash_int = int(hash_hex, 16)
80
+ # Truncate hash integer to fit within modular size n
81
+ hash_int_mod = hash_int % n
82
+ print(f"Original msg : '{msg}'")
83
+ print(f"Full SHA-256 Hash: {hash_hex}")
84
+ print(f"Hash Integer : {hash_int}")
85
+ print(f"Hash (mod n) : {hash_int_mod}\n")
86
+ signature = pow(hash_int_mod, d, n)
87
+ print(f"Digital Signature: {signature}\n")
88
+ decrypted_hash = pow(signature, e, n)
89
+ print(f"Decrypted Hash : {decrypted_hash}")
90
+ if decrypted_hash == hash_int_mod:
91
+ print("Verification Result: SUCCESS - Signature is VALID!")
92
+ else:
93
+ print("Verification Result: FAILED - Invalid signature or tampered message.")
94
+ Output:-