Spaces:
Runtime error
Runtime error
Initial Commit
Browse files
app.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from Crypto.Cipher import AES
|
| 3 |
+
from Crypto.Util.Padding import pad, unpad
|
| 4 |
+
from Crypto.Random import get_random_bytes
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def encrypt(plaintext, key):
|
| 8 |
+
iv = get_random_bytes(AES.block_size) # Generate a random IV
|
| 9 |
+
cipher = AES.new(key, AES.MODE_CBC, iv)
|
| 10 |
+
ciphertext = cipher.encrypt(pad(plaintext.encode(), AES.block_size))
|
| 11 |
+
return iv.hex() + ciphertext.hex()
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def decrypt(ciphertext, key):
|
| 15 |
+
try:
|
| 16 |
+
iv = bytes.fromhex(ciphertext[:32]) # Extract the IV from the ciphertext
|
| 17 |
+
ciphertext = bytes.fromhex(ciphertext[32:])
|
| 18 |
+
cipher = AES.new(key, AES.MODE_CBC, iv)
|
| 19 |
+
decrypted = cipher.decrypt(ciphertext)
|
| 20 |
+
unpadded = unpad(decrypted, AES.block_size)
|
| 21 |
+
return unpadded.decode()
|
| 22 |
+
except (ValueError, IndexError):
|
| 23 |
+
return "Decryption failed. Please check the ciphertext and key."
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def aes_cipher(text, key, mode):
|
| 27 |
+
key = key.encode() # Encode key as byte string
|
| 28 |
+
result = ""
|
| 29 |
+
|
| 30 |
+
if mode == "Encrypt":
|
| 31 |
+
result = encrypt(text, key)
|
| 32 |
+
elif mode == "Decrypt":
|
| 33 |
+
result = decrypt(text, key)
|
| 34 |
+
else:
|
| 35 |
+
print('Invalid mode:', mode)
|
| 36 |
+
|
| 37 |
+
return result
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
iface = gr.Interface(
|
| 41 |
+
fn=aes_cipher,
|
| 42 |
+
inputs=[
|
| 43 |
+
"text",
|
| 44 |
+
"text",
|
| 45 |
+
gr.inputs.Radio(["Encrypt", "Decrypt"], label="Mode")
|
| 46 |
+
],
|
| 47 |
+
outputs="text",
|
| 48 |
+
title="AES Encryption/Decryption",
|
| 49 |
+
description="Enter the text and key to perform AES encryption or decryption.",
|
| 50 |
+
examples=[
|
| 51 |
+
["Hello World!", get_random_bytes(16).hex(), "Encrypt"],
|
| 52 |
+
["2f89f30e4ea8f8f77f7bce0e6a1d4b1b", get_random_bytes(16).hex(), "Decrypt"],
|
| 53 |
+
]
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
iface.launch(share=True)
|