muhammadshaheryar commited on
Commit
e44d75a
Β·
verified Β·
1 Parent(s): 3ee7f11

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +184 -0
app.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Initialize session state variables if they don't exist
2
+ if 'failed_attempts' not in st.session_state:
3
+ st.session_state.failed_attempts = 0
4
+ if 'stored_data' not in st.session_state:
5
+ st.session_state.stored_data = {}
6
+ if 'current_page' not in st.session_state:
7
+ st.session_state.current_page = "Home"
8
+ if 'last_attempt_time' not in st.session_state:
9
+ st.session_state.last_attempt_time = 0
10
+
11
+ # Function to hash passkey
12
+ def hash_passkey(passkey):
13
+ return hashlib.sha256(passkey.encode()).hexdigest()
14
+
15
+ # Function to generate a key from passkey (for encryption)
16
+ def generate_key_from_passkey(passkey):
17
+ # Use the passkey to create a consistent key
18
+ hashed = hashlib.sha256(passkey.encode()).digest()
19
+ # Ensure it's valid for Fernet (32 url-safe base64-encoded bytes)
20
+ return base64.urlsafe_b64encode(hashed[:32])
21
+
22
+ # Function to encrypt data
23
+ def encrypt_data(text, passkey):
24
+ key = generate_key_from_passkey(passkey)
25
+ cipher = Fernet(key)
26
+ return cipher.encrypt(text.encode()).decode()
27
+
28
+ # Function to decrypt data
29
+ def decrypt_data(encrypted_text, passkey, data_id):
30
+ try:
31
+ # Check if the passkey matches
32
+ hashed_passkey = hash_passkey(passkey)
33
+ if data_id in st.session_state.stored_data and st.session_state.stored_data[data_id]["passkey"] == hashed_passkey:
34
+ # If passkey matches, decrypt the data
35
+ key = generate_key_from_passkey(passkey)
36
+ cipher = Fernet(key)
37
+ decrypted = cipher.decrypt(encrypted_text.encode()).decode()
38
+ st.session_state.failed_attempts = 0
39
+ return decrypted
40
+ else:
41
+ # Increment failed attempts
42
+ st.session_state.failed_attempts += 1
43
+ st.session_state.last_attempt_time = time.time()
44
+ return None
45
+ except Exception as e:
46
+ # If decryption fails, increment failed attempts
47
+ st.session_state.failed_attempts += 1
48
+ st.session_state.last_attempt_time = time.time()
49
+ return None
50
+
51
+ # Function to generate a unique ID for data
52
+ def generate_data_id():
53
+ import uuid
54
+ return str(uuid.uuid4())
55
+
56
+ # Function to reset failed attempts
57
+ def reset_failed_attempts():
58
+ st.session_state.failed_attempts = 0
59
+
60
+ # Function to change page
61
+ def change_page(page):
62
+ st.session_state.current_page = page
63
+
64
+ # Streamlit UI
65
+ st.title("πŸ”’ Secure Data Encryption System")
66
+
67
+ # Navigation
68
+ menu = ["Home", "Store Data", "Retrieve Data", "Login"]
69
+ choice = st.sidebar.selectbox("Navigation", menu, index=menu.index(st.session_state.current_page))
70
+
71
+ # Update current page based on selection
72
+ st.session_state.current_page = choice
73
+
74
+ # Check if too many failed attempts
75
+ if st.session_state.failed_attempts >= 3:
76
+ # Force redirect to login page
77
+ st.session_state.current_page = "Login"
78
+ st.warning("πŸ”’ Too many failed attempts! Reauthorization required.")
79
+
80
+ # Display current page
81
+ if st.session_state.current_page == "Home":
82
+ st.subheader("🏠 Welcome to the Secure Data System")
83
+ st.write("Use this app to **securely store and retrieve data** using unique passkeys.")
84
+
85
+ col1, col2 = st.columns(2)
86
+ with col1:
87
+ if st.button("Store New Data", use_container_width=True):
88
+ change_page("Store Data")
89
+ with col2:
90
+ if st.button("Retrieve Data", use_container_width=True):
91
+ change_page("Retrieve Data")
92
+
93
+ # Display stored data count
94
+ st.info(f"Currently storing {len(st.session_state.stored_data)} encrypted data entries.")
95
+
96
+ elif st.session_state.current_page == "Store Data":
97
+ st.subheader("πŸ“‚ Store Data Securely")
98
+ user_data = st.text_area("Enter Data:")
99
+ passkey = st.text_input("Enter 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 do not match!")
106
+ else:
107
+ # Generate a unique ID for this data
108
+ data_id = generate_data_id()
109
+
110
+ # Hash the passkey
111
+ hashed_passkey = hash_passkey(passkey)
112
+
113
+ # Encrypt the data
114
+ encrypted_text = encrypt_data(user_data, passkey)
115
+
116
+ # Store in the required format
117
+ st.session_state.stored_data[data_id] = {
118
+ "encrypted_text": encrypted_text,
119
+ "passkey": hashed_passkey
120
+ }
121
+
122
+ st.success("βœ… Data stored securely!")
123
+
124
+ # Display the data ID for retrieval
125
+ st.code(data_id, language="text")
126
+ st.info("⚠️ Save this Data ID! You'll need it to retrieve your data.")
127
+ else:
128
+ st.error("⚠️ All fields are required!")
129
+
130
+ elif st.session_state.current_page == "Retrieve Data":
131
+ st.subheader("πŸ” Retrieve Your Data")
132
+
133
+ # Show attempts remaining
134
+ attempts_remaining = 3 - st.session_state.failed_attempts
135
+ st.info(f"Attempts remaining: {attempts_remaining}")
136
+
137
+ data_id = st.text_input("Enter Data ID:")
138
+ passkey = st.text_input("Enter Passkey:", type="password")
139
+
140
+ if st.button("Decrypt"):
141
+ if data_id and passkey:
142
+ if data_id in st.session_state.stored_data:
143
+ encrypted_text = st.session_state.stored_data[data_id]["encrypted_text"]
144
+ decrypted_text = decrypt_data(encrypted_text, passkey, data_id)
145
+
146
+ if decrypted_text:
147
+ st.success("βœ… Decryption successful!")
148
+ st.markdown("### Your Decrypted Data:")
149
+ st.code(decrypted_text, language="text")
150
+ else:
151
+ st.error(f"❌ Incorrect passkey! Attempts remaining: {3 - st.session_state.failed_attempts}")
152
+ else:
153
+ st.error("❌ Data ID not found!")
154
+
155
+ # Check if too many failed attempts after this attempt
156
+ if st.session_state.failed_attempts >= 3:
157
+ st.warning("πŸ”’ Too many failed attempts! Redirecting to Login Page.")
158
+ st.session_state.current_page = "Login"
159
+ st.rerun() # Updated from experimental_rerun()
160
+ else:
161
+ st.error("⚠️ Both fields are required!")
162
+
163
+ elif st.session_state.current_page == "Login":
164
+ st.subheader("πŸ”‘ Reauthorization Required")
165
+
166
+ # Add a simple timeout mechanism
167
+ if time.time() - st.session_state.last_attempt_time < 10 and st.session_state.failed_attempts >= 3:
168
+ remaining_time = int(10 - (time.time() - st.session_state.last_attempt_time))
169
+ st.warning(f"πŸ•’ Please wait {remaining_time} seconds before trying again.")
170
+ else:
171
+ login_pass = st.text_input("Enter Master Password:", type="password")
172
+
173
+ if st.button("Login"):
174
+ if login_pass == "admin123": # Hardcoded for demo, replace with proper auth
175
+ reset_failed_attempts()
176
+ st.success("βœ… Reauthorized successfully!")
177
+ st.session_state.current_page = "Home"
178
+ st.rerun() # Updated from experimental_rerun()
179
+ else:
180
+ st.error("❌ Incorrect password!")
181
+
182
+ # Add a footer
183
+ st.markdown("---")
184
+ st.markdown("πŸ” Secure Data Encryption System | Educational Project")