Team Ai
Apppublic

elitecode/AES_Algorithm

sourceHugging Faceupdated 3y agoView on Hugging Face
0likes
app.py57 linesDownload Raw Back to root
1import gradio as gr2from Crypto.Cipher import AES3from Crypto.Util.Padding import pad, unpad4from Crypto.Random import get_random_bytes5 6 7def encrypt(plaintext, key):8    iv = get_random_bytes(AES.block_size)  # Generate a random IV9    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 14def decrypt(ciphertext, key):15    try:16        iv = bytes.fromhex(ciphertext[:32])  # Extract the IV from the ciphertext17        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 26def aes_cipher(text, key, mode):27    key = key.encode()  # Encode key as byte string28    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 result38 39 40iface = 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 56iface.launch(share=True)57