lyimo commited on
Commit
f1cb997
·
verified ·
1 Parent(s): bc20421

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +74 -105
app.py CHANGED
@@ -1,106 +1,75 @@
1
- import gradio as gr
2
- import os
3
- import numpy as np
4
- from PIL import Image
5
- from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
6
- from cryptography.hazmat.backends import default_backend
7
  import cv2
8
-
9
- class CBCEncryption:
10
- def __init__(self, key, iv):
11
- self.cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
12
- self.encryptor = self.cipher.encryptor()
13
- self.decryptor = self.cipher.decryptor()
14
-
15
- def encrypt(self, image):
16
- return self.encryptor.update(image)
17
-
18
- def decrypt(self, image):
19
- return self.decryptor.update(image)
20
-
21
- def finalize_encrypt(self):
22
- return self.encryptor.finalize()
23
-
24
- def finalize_decrypt(self):
25
- return self.decryptor.finalize()
26
-
27
- def add_gaussian_noise(image, mean=0, var=0.01):
28
- noise = np.random.normal(mean, var**0.5, image.shape)
29
- noisy_image = image + noise
30
- return noisy_image
31
-
32
- def remove_gaussian_noise(image, mean=0, var=0.01):
33
- # This is a simplified approach to remove noise.
34
- # In practice, you might need a more sophisticated method to estimate the noise statistics.
35
- return image - np.random.normal(mean, var**0.5, image.shape)
36
-
37
- def EncryptImage(encryption, image, key):
38
- image = Image.open(image)
39
- image_np = np.array(image)
40
- noisy_image_np = add_gaussian_noise(image_np)
41
- noisy_image = Image.fromarray(noisy_image_np.astype(np.uint8))
42
- noisy_image.save('temp.bmp')
43
- with open('temp.bmp', 'rb') as reader:
44
- with open('encrypted.bmp', 'wb') as writer:
45
- image_data = reader.read()
46
- header, body = image_data[:54], image_data[54:]
47
- body += b'\x35' * (16 - (len(body) % 16))
48
- body = encryption.encrypt(body) + encryption.finalize_encrypt()
49
- writer.write(header + body)
50
- os.remove('temp.bmp')
51
- return 'encrypted.bmp'
52
-
53
- def DecryptImage(decryption, image, key):
54
- with open(image, 'rb') as reader:
55
- with open('decrypted.bmp', 'wb') as writer:
56
- image_data = reader.read()
57
- header, body = image_data[:54], image_data[54:]
58
- body = decryption.decrypt(body)
59
- unpadded_body = unpad_data(body)
60
- decrypted_image_np = np.frombuffer(unpadded_body, dtype=np.uint8).reshape(image.shape)
61
- original_image_np = remove_gaussian_noise(decrypted_image_np)
62
- original_image = Image.fromarray(original_image_np.astype(np.uint8))
63
- original_image.save('decrypted.bmp')
64
- return 'decrypted.bmp'
65
-
66
- def unpad_data(data):
67
- padding_byte = data[-1]
68
- padding_length = padding_byte if padding_byte < 16 else 16
69
- unpadded_data = data[:-padding_length]
70
- return unpadded_data
71
-
72
- def main():
73
- def action(image, key, action_type):
74
- if len(key) > 32:
75
- return 'Key is too long. Maximum key length is 32 characters.'
76
- key = key.encode('utf-8')
77
- key = key.ljust(32, b'\x35')
78
-
79
- iv = key[:16]
80
- iv = bytearray(iv)
81
- for i in range(16):
82
- iv[i] = iv[i] ^ 0x35
83
- iv = bytes(iv)
84
-
85
- AesCbc = CBCEncryption(key, iv)
86
- if action_type == 'Encrypt':
87
- output_path = EncryptImage(AesCbc, image, key)
88
- elif action_type == 'Decrypt':
89
- output_path = DecryptImage(AesCbc, image, key)
90
- else:
91
- return 'Invalid action type. Choose either Encrypt or Decrypt.'
92
- return output_path
93
-
94
- # Define the Gradio interface
95
- iface = gr.Interface(
96
- action, # Single function to wrap
97
- ["image", "text", "text"], # Input types: image, key, action_type
98
- "image", # Output type
99
- title="AES CBC Encryption/Decryption with Gaussian Noise",
100
- description="Upload an image, a key, and choose Encrypt or Decrypt to process the image."
101
- )
102
-
103
- iface.launch()
104
-
105
- if __name__ == '__main__':
106
- main()
 
 
 
 
 
 
 
1
  import cv2
2
+ import numpy as np
3
+ import gradio as gr
4
+ from cryptography.fernet import Fernet
5
+
6
+ def encrypt_image(image, password):
7
+ # Convert the image to a NumPy array
8
+ image_array = np.array(image)
9
+
10
+ # Generate a key from the password
11
+ key = Fernet.generate_key()
12
+ fernet = Fernet(key)
13
+
14
+ # Encrypt the image data using the key
15
+ encrypted_image_data = fernet.encrypt(image_array.tobytes())
16
+
17
+ # Add Gaussian noise to the encrypted image data
18
+ noise = np.random.normal(0, 30, encrypted_image_data.shape).astype('uint8')
19
+ encrypted_image_data += noise
20
+
21
+ return encrypted_image_data, key
22
+
23
+ def decrypt_image(encrypted_image_data, key, password):
24
+ # Check if the password is correct
25
+ try:
26
+ fernet = Fernet(key)
27
+ except Exception:
28
+ return "Incorrect password"
29
+
30
+ # Remove the Gaussian noise from the encrypted image data
31
+ encrypted_image_data = encrypted_image_data.astype('int16') - 30
32
+ encrypted_image_data = encrypted_image_data.clip(0, 255).astype('uint8')
33
+
34
+ # Decrypt the image data using the key
35
+ decrypted_image_data = fernet.decrypt(encrypted_image_data.tobytes())
36
+
37
+ # Convert the decrypted data back to an image
38
+ decrypted_image = cv2.imdecode(np.frombuffer(decrypted_image_data, np.uint8), cv2.IMREAD_COLOR)
39
+
40
+ return decrypted_image
41
+
42
+ # Create the Gradio interface
43
+ image_input = gr.inputs.Image(label="Upload Image")
44
+ password_input = gr.inputs.Textbox(label="Enter Password")
45
+ encrypt_button = gr.Button("Encrypt Image")
46
+ decrypt_button = gr.Button("Decrypt Image")
47
+ output_image = gr.outputs.Image(label="Output Image")
48
+
49
+ # Define the Gradio functions
50
+ def encrypt(image, password):
51
+ encrypted_data, key = encrypt_image(image, password)
52
+ return encrypted_data, key
53
+
54
+ def decrypt(encrypted_data, key, password):
55
+ decrypted_image = decrypt_image(encrypted_data, key, password)
56
+ return decrypted_image
57
+
58
+ # Create the Gradio app
59
+ app = gr.Interface(
60
+ fn=encrypt,
61
+ inputs=[image_input, password_input, encrypt_button],
62
+ outputs=[output_image, gr.outputs.Textbox(label="Encryption Key")],
63
+ examples=None,
64
+ )
65
+
66
+ # Add the decrypt functionality to the app
67
+ app.add(
68
+ fn=decrypt,
69
+ inputs=[gr.inputs.Image(label="Encrypted Image"), gr.inputs.Textbox(label="Encryption Key"), password_input, decrypt_button],
70
+ outputs=output_image,
71
+ examples=None,
72
+ )
73
+
74
+ # Launch the app
75
+ app.launch()