-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
80 lines (62 loc) · 2.84 KB
/
main.py
File metadata and controls
80 lines (62 loc) · 2.84 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
from rcncipher import encrypt, decrypt
def text_to_128_bit_hex_chunks(text):
# Convert text to bytes
text_bytes = text.encode('utf-8')
# Calculate the number of 128-bit chunks
num_chunks = (len(text_bytes) + 15) // 16
# Pad the text_bytes to make its length a multiple of 16 bytes
padded_bytes = text_bytes.ljust(num_chunks * 16, b'\0')
# Divide the padded bytes into 128-bit chunks
chunks = [padded_bytes[i:i+16] for i in range(0, len(padded_bytes), 16)]
# Convert each chunk to hexadecimal representation
hex_chunks = [chunk.hex() for chunk in chunks]
# print(hex_chunks)
return hex_chunks
def text_to_hex(text):
# Convert text to bytes
text_bytes = text.encode('utf-8')
# Convert bytes to hexadecimal representation
hex_representation = text_bytes.hex()
return hex_representation
def hex_to_text(hex_string):
# Convert hexadecimal string to bytes
byte_string = bytes.fromhex(hex_string)
# Decode bytes to text using UTF-8 encoding
text = byte_string.decode('utf-8')
return text
# User input to perform encryption or decryption
while(True):
choice = input("Enter 'e' for encryption or 'd' for decryption: ")
if choice == 'e':
# Get the key and plaintext from the user
# key = input("Enter the key: ")
key = text_to_hex(input("Enter the key: "))
if len(key) <= 32: # Each hexadecimal character represents 4 bits
print("Hexadecimal representation:", key)
else:
raise ValueError("Hexadecimal representation exceeds 128 bits.")
plaintext = input("Enter the plaintext: ")
# Convert the plaintext into 128-bit chunks
chunks = text_to_128_bit_hex_chunks(plaintext)
# Encrypt each 128-bit chunk
ciphertext = ''.join(encrypt(chunk, key) for chunk in chunks)
print("Ciphertext:", ciphertext)
# break
elif choice == 'd':
# Get the key and ciphertext from the user
key = text_to_hex(input("Enter the key: "))
if len(key) <= 32: # Each hexadecimal character represents 4 bits
print("Hexadecimal representation:", key)
else:
raise ValueError("Hexadecimal representation exceeds 128 bits.")
ciphertext = input("Enter the ciphertext: ")
# Decrypt the ciphertext
decrypted_chunks = [hex_to_text(decrypt(ciphertext[i:i+32], key)) for i in range(0, len(ciphertext), 32)]
# Remove the padding and convert the decrypted chunks to text
decrypted_text = ''.join(decrypted_chunks)
print("Decrypted text:", decrypted_text)
elif choice == 'exit':
break
else:
choice = input("Invalid choice. Type exit to, well, exit. Enter 'e' for encryption or 'd' for decryption: ")
continue