Spaces:
Runtime error
Runtime error
| import streamlit as st | |
| from cryptography.hazmat.primitives import padding | |
| from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes | |
| from cryptography.hazmat.backends import default_backend | |
| import base64 | |
| import os | |
| def aes_encrypt(plaintext, key): | |
| backend = default_backend() | |
| # Generate a random IV (Initialization Vector) | |
| iv = os.urandom(16) | |
| cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=backend) | |
| encryptor = cipher.encryptor() | |
| padder = padding.PKCS7(128).padder() | |
| padded_data = padder.update(plaintext) + padder.finalize() | |
| ciphertext = encryptor.update(padded_data) + encryptor.finalize() | |
| return base64.b64encode(iv + ciphertext) | |
| def aes_decrypt(ciphertext, key): | |
| backend = default_backend() | |
| decoded_ciphertext = base64.b64decode(ciphertext) | |
| iv = decoded_ciphertext[:16] | |
| ciphertext = decoded_ciphertext[16:] | |
| cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=backend) | |
| decryptor = cipher.decryptor() | |
| decrypted_data = decryptor.update(ciphertext) + decryptor.finalize() | |
| unpadder = padding.PKCS7(128).unpadder() | |
| unpadded_data = unpadder.update(decrypted_data) + unpadder.finalize() | |
| return unpadded_data | |
| def main(): | |
| st.title("AES Encryption and Decryption") | |
| operation = st.radio("Select operation:", ("Encrypt", "Decrypt")) | |
| key = st.text_input("Enter 16-byte key:", "") | |
| if len(key) != 16: | |
| st.warning("Key must be exactly 16 bytes long") | |
| return | |
| if operation == "Encrypt": | |
| plaintext = st.text_area("Enter plaintext:", "") | |
| if st.button("Encrypt"): | |
| encrypted_data = aes_encrypt(plaintext.encode('utf-8'), key.encode('utf-8')) | |
| st.success("Encryption successful!") | |
| st.text("Encrypted data:") | |
| st.write(encrypted_data.decode('utf-8')) | |
| else: | |
| ciphertext = st.text_area("Enter ciphertext:", "") | |
| if st.button("Decrypt"): | |
| decrypted_data = aes_decrypt(ciphertext.encode('utf-8'), key.encode('utf-8')) | |
| st.success("Decryption successful!") | |
| st.text("Decrypted data:") | |
| st.write(decrypted_data.decode('utf-8')) | |
| if __name__ == "__main__": | |
| main() | |