-
Notifications
You must be signed in to change notification settings - Fork 0
/
working image encoder decoder.py
90 lines (78 loc) · 2.79 KB
/
working image encoder decoder.py
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
from Crypto.Cipher import Blowfish
from Crypto import Random
import stegano.lsb as lsb
from PIL import Image
def read_key():
"""
Read the key from the file called key.txt
"""
with open('key.txt', 'rb') as f:
key = f.read()
return key
def encrypt(plaintext):
"""
Encrypt the plaintext using the Blowfish algorithm with the key read from the file.
Returns the encrypted ciphertext.
"""
# Generate a random initialization vector
iv = Random.new().read(Blowfish.block_size)
# Create the cipher object and encrypt the plaintext
cipher = Blowfish.new(read_key(), Blowfish.MODE_CBC, iv)
ciphertext = cipher.encrypt(pad(plaintext))
# Return the IV and ciphertext as a single byte string
return iv + ciphertext
def decrypt(ciphertext):
"""
Decrypt the ciphertext using the Blowfish algorithm with the key read from the file.
Returns the decrypted plaintext.
"""
# Extract the IV from the ciphertext
iv = ciphertext[:Blowfish.block_size]
# Create the cipher object and decrypt the ciphertext
cipher = Blowfish.new(read_key(), Blowfish.MODE_CBC, iv.encode())
plaintext = unpad(cipher.decrypt(ciphertext[Blowfish.block_size:]))
# Return the decrypted plaintext
return plaintext
def pad(s):
"""
Pad the given string s with zeros to a multiple of the block size.
"""
if isinstance(s, str):
s = s.encode()
return s + (Blowfish.block_size - len(s) % Blowfish.block_size) * bytes([0])
def unpad(s):
"""
Remove the zero padding from the given string s.
"""
return s.rstrip(bytes([0]))
# Generate a new key and write it to a file
key = Random.get_random_bytes(16)
with open('key.txt', 'wb') as f:
f.write(key)
while True:
print("Select an option:")
print("1. Encode")
print("2. Decode")
print("3. Exit")
choice = input("Enter your choice (1, 2, or 3): ")
if choice == '1':
path = input("Enter the path of the image: ")
image = Image.open(path)
plaintext = input("Enter the text to be encrypted: ")
#key = Random.get_random_bytes(16)
# with open('key.txt', 'wb') as f:
# f.write(key)
#ciphertext = encrypt(plaintext)
encoded_image = lsb.hide(image, plaintext)
encoded_image.save("encoded_image.png")
elif choice == '2':
path = input("Enter the path of the image: ")
image = Image.open(path)
plaintext = lsb.reveal(image)
#decrypted_plaintext = decrypt(ciphertext)
# keypath = input("Enter the path of the key: ")
print("Decrypted text:", plaintext)
elif choice == '3':
break
else:
print("Invalid choice. Please enter 1, 2, or 3.")