CoolFace
Apppublic

adilaijaz10/secure_data_encryption_assignment

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
app.py169 linesDownload Raw Back to root
1import streamlit as st2import hashlib3import base644import uuid5from cryptography.fernet import Fernet6from cryptography.hazmat.primitives import hashes7from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC8 9# Initialize session state for failed attempts and login status10if 'failed_attempts' not in st.session_state:11    st.session_state.failed_attempts = 012if 'is_authenticated' not in st.session_state:13    st.session_state.is_authenticated = True14if 'stored_data' not in st.session_state:15    st.session_state.stored_data = {}  # {"id": {"encrypted_text": "xyz", "passkey_hash": "hashed", "salt": "salt"}}16 17# Function to derive encryption key from passkey18def get_key_from_passkey(passkey, salt=None):19    if salt is None:20        salt = uuid.uuid4().hex.encode()21    kdf = PBKDF2HMAC(22        algorithm=hashes.SHA256(),23        length=32,24        salt=salt if isinstance(salt, bytes) else salt.encode(),25        iterations=100000,26    )27    key = base64.urlsafe_b64encode(kdf.derive(passkey.encode()))28    return key, salt29 30# Function to hash passkey31def hash_passkey(passkey):32    return hashlib.sha256(passkey.encode()).hexdigest()33 34# Function to encrypt data35def encrypt_data(text, passkey):36    key, salt = get_key_from_passkey(passkey)37    cipher = Fernet(key)38    encrypted_text = cipher.encrypt(text.encode()).decode()39    return encrypted_text, salt40 41# Function to decrypt data42def decrypt_data(data_id, encrypted_text, passkey):43    if data_id not in st.session_state.stored_data:44        st.session_state.failed_attempts += 145        return None46    47    data_info = st.session_state.stored_data[data_id]48    salt = data_info["salt"]49    stored_passkey_hash = data_info["passkey_hash"]50    51    # Check if passkey is correct52    if hash_passkey(passkey) != stored_passkey_hash:53        st.session_state.failed_attempts += 154        return None55    56    # Derive key and decrypt57    key, _ = get_key_from_passkey(passkey, salt)58    cipher = Fernet(key)59    try:60        decrypted_text = cipher.decrypt(encrypted_text.encode()).decode()61        st.session_state.failed_attempts = 062        return decrypted_text63    except Exception:64        st.session_state.failed_attempts += 165        return None66 67# Function to reset attempts after successful login68def reset_attempts():69    st.session_state.failed_attempts = 070    st.session_state.is_authenticated = True71 72# Streamlit UI73st.title("๐Ÿ”’ Secure Data Encryption System")74 75# Check if too many failed attempts76if st.session_state.failed_attempts >= 3:77    st.session_state.is_authenticated = False78 79# Navigation80menu = ["Home", "Store Data", "Retrieve Data", "Login"]81choice = st.sidebar.selectbox("Navigation", menu)82 83if not st.session_state.is_authenticated and choice != "Login":84    st.warning("๐Ÿ”’ Too many failed attempts! Please login to continue.")85    choice = "Login"86 87if choice == "Home":88    st.subheader("๐Ÿ  Welcome to the Secure Data System")89    st.write("Use this app to **securely store and retrieve data** using unique passkeys.")90    st.info("Your data is encrypted with strong cryptography and can only be accessed with the correct passkey.")91    92    # Display stored data count93    st.subheader("๐Ÿ“Š System Status")94    st.write(f"Number of encrypted entries: {len(st.session_state.stored_data)}")95 96elif choice == "Store Data":97    st.subheader("๐Ÿ“‚ Store Data Securely")98    user_data = st.text_area("Enter Data to Encrypt:")99    passkey = st.text_input("Create a Passkey:", type="password")100    confirm_passkey = st.text_input("Confirm Passkey:", type="password")101 102    if st.button("Encrypt & Save"):103        if user_data and passkey and confirm_passkey:104            if passkey != confirm_passkey:105                st.error("โš ๏ธ Passkeys don't match!")106            else:107                # Generate a unique ID for this data108                data_id = uuid.uuid4().hex109                110                # Hash the passkey and encrypt the data111                passkey_hash = hash_passkey(passkey)112                encrypted_text, salt = encrypt_data(user_data, passkey)113                114                # Store the encrypted data with its metadata115                st.session_state.stored_data[data_id] = {116                    "encrypted_text": encrypted_text,117                    "passkey_hash": passkey_hash,118                    "salt": salt119                }120                121                st.success("โœ… Data stored securely!")122                st.info(f"Your data ID is: **{data_id}**")123                st.warning("โš ๏ธ Please save this ID. You will need it to retrieve your data.")124        else:125            st.error("โš ๏ธ All fields are required!")126 127elif choice == "Retrieve Data":128    st.subheader("๐Ÿ” Retrieve Your Data")129    data_id = st.text_input("Enter Data ID:")130    passkey = st.text_input("Enter Passkey:", type="password")131    132    attempts_left = 3 - st.session_state.failed_attempts133    st.info(f"Attempts remaining: {attempts_left}")134 135    if st.button("Decrypt"):136        if data_id and passkey:137            if data_id in st.session_state.stored_data:138                encrypted_text = st.session_state.stored_data[data_id]["encrypted_text"]139                decrypted_text = decrypt_data(data_id, encrypted_text, passkey)140                141                if decrypted_text:142                    st.success("โœ… Decryption successful!")143                    st.code(decrypted_text, language="text")144                else:145                    st.error(f"โŒ Incorrect passkey! Attempts remaining: {3 - st.session_state.failed_attempts}")146                    147                    if st.session_state.failed_attempts >= 3:148                        st.warning("๐Ÿ”’ Too many failed attempts! Redirecting to Login Page.")149                        st.session_state.is_authenticated = False150                        st.experimental_rerun()151            else:152                st.error("โŒ Data ID not found!")153        else:154            st.error("โš ๏ธ Both fields are required!")155 156elif choice == "Login":157    st.subheader("๐Ÿ”‘ Reauthorization Required")158    st.write("You have been locked out due to too many failed attempts.")159    login_pass = st.text_input("Enter Master Password:", type="password")160 161    if st.button("Login"):162        # In a real application, use a more secure master password or authentication system163        if login_pass == "admin123":  164            reset_attempts()165            st.success("โœ… Reauthorized successfully! Redirecting...")166            st.experimental_rerun()167        else:168            st.error("โŒ Incorrect password!")169