Skip to content

Commit 7844a68

Browse files
authored
Merge pull request #15 from tainguyenbp/feat/learning-hacking-with-python-20240706
feat/learning-hacking-with-python-20240706
2 parents 90c485e + e544435 commit 7844a68

File tree

9 files changed

+411
-0
lines changed

9 files changed

+411
-0
lines changed
Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
# from flask import Flask, render_template, request, redirect, url_for, flash
2+
# from flask_wtf.csrf import CSRFProtect
3+
4+
# app = Flask(__name__)
5+
# app.secret_key = 'your_secret_key' # Necessary for CSRF protection
6+
# csrf = CSRFProtect(app)
7+
8+
# @app.route('/transfer', methods=['POST'])
9+
# def transfer():
10+
# try:
11+
# amount = float(request.form['amount'])
12+
# destination_account = request.form['destination_account']
13+
# # Logic to transfer funds...
14+
# # Assuming transfer logic is implemented here.
15+
16+
# flash('Transfer successful!', 'success')
17+
# except ValueError:
18+
# flash('Invalid amount. Please enter a valid number.', 'danger')
19+
# except Exception as e:
20+
# flash(f'An error occurred: {e}', 'danger')
21+
22+
# return redirect(url_for('dashboard'))
23+
24+
# @app.route('/dashboard')
25+
# def dashboard():
26+
# return render_template('dashboard.html')
27+
28+
# if __name__ == '__main__':
29+
# app.run()
30+
31+
32+
# from flask import Flask, render_template, request, redirect, url_for, flash, jsonify
33+
# from flask_wtf.csrf import CSRFProtect, generate_csrf
34+
35+
# app = Flask(__name__)
36+
# app.secret_key = 'your_secret_key' # Necessary for CSRF protection
37+
# csrf = CSRFProtect(app)
38+
39+
# @app.route('/transfer', methods=['POST'])
40+
# def transfer():
41+
# try:
42+
# amount = float(request.form['amount'])
43+
# destination_account = request.form['destination_account']
44+
# # Logic to transfer funds...
45+
# # Assuming transfer logic is implemented here.
46+
47+
# flash('Transfer successful!', 'success')
48+
# except ValueError:
49+
# flash('Invalid amount. Please enter a valid number.', 'danger')
50+
# except Exception as e:
51+
# flash(f'An error occurred: {e}', 'danger')
52+
53+
# return redirect(url_for('dashboard'))
54+
55+
# @app.route('/dashboard')
56+
# def dashboard():
57+
# return render_template('dashboard.html')
58+
59+
# @app.route('/get_csrf_token', methods=['GET'])
60+
# def get_csrf_token():
61+
# return jsonify({'csrf_token': generate_csrf()})
62+
63+
# if __name__ == '__main__':
64+
# app.run()
65+
66+
# from flask import Flask, render_template, request, redirect, url_for, flash, jsonify
67+
# from flask_wtf.csrf import CSRFProtect, generate_csrf
68+
69+
# app = Flask(__name__)
70+
# app.secret_key = 'your_secret_key' # Necessary for CSRF protection
71+
# csrf = CSRFProtect(app)
72+
73+
# @app.route('/transfer', methods=['POST'])
74+
# def transfer():
75+
# try:
76+
# amount = float(request.form['amount'])
77+
# destination_account = request.form['destination_account']
78+
# # Logic to transfer funds...
79+
# # Assuming transfer logic is implemented here.
80+
81+
# flash('Transfer successful!', 'success')
82+
# except ValueError:
83+
# flash('Invalid amount. Please enter a valid number.', 'danger')
84+
# except Exception as e:
85+
# flash(f'An error occurred: {e}', 'danger')
86+
87+
# return redirect(url_for('dashboard'))
88+
89+
# @app.route('/dashboard')
90+
# def dashboard():
91+
# return render_template('dashboard.html')
92+
93+
# @app.route('/get_csrf_token', methods=['GET'])
94+
# def get_csrf_token():
95+
# return jsonify({'csrf_token': generate_csrf()})
96+
97+
# if __name__ == '__main__':
98+
# app.run()
99+
100+
from flask import Flask, render_template, request, redirect, url_for, flash, jsonify, session
101+
from flask_wtf.csrf import CSRFProtect, generate_csrf
102+
from flask_session import Session
103+
104+
app = Flask(__name__)
105+
app.secret_key = 'your_secret_key' # Necessary for CSRF protection and session management
106+
107+
# Session configuration
108+
app.config['SESSION_TYPE'] = 'filesystem'
109+
Session(app)
110+
csrf = CSRFProtect(app)
111+
112+
@app.route('/transfer', methods=['POST'])
113+
def transfer():
114+
try:
115+
amount = float(request.form['amount'])
116+
destination_account = request.form['destination_account']
117+
# Logic to transfer funds...
118+
# Assuming transfer logic is implemented here.
119+
120+
flash('Transfer successful!', 'success')
121+
except ValueError:
122+
flash('Invalid amount. Please enter a valid number.', 'danger')
123+
except Exception as e:
124+
flash(f'An error occurred: {e}', 'danger')
125+
126+
return redirect(url_for('dashboard'))
127+
128+
@app.route('/dashboard')
129+
def dashboard():
130+
return render_template('dashboard.html')
131+
132+
@app.route('/get_csrf_token', methods=['GET'])
133+
def get_csrf_token():
134+
csrf_token = generate_csrf()
135+
session['csrf_token'] = csrf_token
136+
return jsonify({'csrf_token': csrf_token})
137+
138+
if __name__ == '__main__':
139+
app.run()
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<!doctype html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<title>Dashboard</title>
6+
</head>
7+
<body>
8+
<h1>Dashboard</h1>
9+
{% with messages = get_flashed_messages(with_categories=true) %}
10+
{% if messages %}
11+
<ul>
12+
{% for category, message in messages %}
13+
<li class="{{ category }}">{{ message }}</li>
14+
{% endfor %}
15+
</ul>
16+
{% endif %}
17+
{% endwith %}
18+
19+
<form action="{{ url_for('transfer') }}" method="POST">
20+
{{ csrf_token() }}
21+
<label for="amount">Amount:</label>
22+
<input type="text" id="amount" name="amount" required>
23+
<label for="destination_account">Destination Account:</label>
24+
<input type="text" id="destination_account" name="destination_account" required>
25+
<button type="submit">Transfer</button>
26+
</form>
27+
</body>
28+
</html>
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
```
2+
python3 -m venv path/to/venv
3+
source path/to/venv/bin/activate
4+
python3 -m pip install requests
5+
pip install Flask Flask-WTF Flask-Session
6+
7+
# Step 1: Fetch the CSRF token and store the session cookie
8+
csrf_token=$(curl -s -c cookiefile http://127.0.0.1:5000/get_csrf_token | jq -r '.csrf_token')
9+
10+
# Step 2: Use the CSRF token and the session cookie in the transfer request
11+
curl -X POST -b cookiefile http://127.0.0.1:5000/dashboard -d "amount=100&destination_account=123456&csrf_token=${csrf_token}"
12+
```
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Importing required libraries
2+
import base64, os
3+
4+
# Importing required libraries from cryptography
5+
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
6+
from cryptography.hazmat.backends import default_backend
7+
8+
# Function to encrypt data using AES-GCM algorithm and return the encrypted data in string format
9+
def encrypt(data:str, key:str) -> str:
10+
iv = os.urandom(12)
11+
encryptor = Cipher(algorithms.AES(key.encode('utf-8')), modes.GCM(iv), backend=default_backend()).encryptor()
12+
encrypted_data = encryptor.update(data.encode('utf-8')) + encryptor.finalize()
13+
return base64.urlsafe_b64encode(iv + encryptor.tag + encrypted_data).decode('utf-8')
14+
15+
# Function to decrypt data using AES-GCM algorithm and return the decrypted data in string format
16+
def decrypt(encrypted_data, key) -> str:
17+
decoded_data = base64.urlsafe_b64decode(encrypted_data)
18+
iv = decoded_data[:12]
19+
tag = decoded_data[12:28]
20+
encrypted_data = decoded_data[28:]
21+
decryptor = Cipher(algorithms.AES(key.encode('utf-8')), modes.GCM(iv, tag), backend=default_backend()).decryptor()
22+
return (decryptor.update(encrypted_data) + decryptor.finalize()).decode('utf-8')
23+
24+
# Main function to test the above functions
25+
if __name__ == '__main__':
26+
key = '689ef728d55342d9af07ed4194cf1d4C' # 32 bytes key for AES-256
27+
data = 'Hello, World' # Data to be encrypted
28+
29+
# Encrypting and decrypting the data
30+
encrypted_data = encrypt(data, key)
31+
print('Encrypted data:', encrypted_data)
32+
33+
decrypted_data = decrypt(encrypted_data, key)
34+
print('Decrypted data:', decrypted_data)
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# You sould install pycryptodome before runing this code
2+
# pip install pycryptodome
3+
import base64
4+
from Crypto.Cipher import DES
5+
from Crypto.Util.Padding import pad, unpad
6+
7+
def encrypt_data(data, key):
8+
cipher = DES.new(key.encode(), DES.MODE_ECB)
9+
padded_data = pad(data.encode(), DES.block_size)
10+
encrypted_data = cipher.encrypt(padded_data)
11+
return base64.b64encode(encrypted_data).decode('utf-8')
12+
13+
def decrypt_data(encrypted_data, key):
14+
cipher = DES.new(key.encode(), DES.MODE_ECB)
15+
decrypted_data = cipher.decrypt(base64.b64decode(encrypted_data.encode()))
16+
return unpad(decrypted_data, DES.block_size).decode('utf-8')
17+
18+
if __name__ == '__main__':
19+
key = 'abcdefgh' # 8 bytes key for DES
20+
data = 'Hello, World' # Data to be encrypted
21+
22+
encrypted_data = encrypt_data(data, key)
23+
print('Encrypted data:', encrypted_data)
24+
25+
decrypted_data = decrypt_data(encrypted_data, key)
26+
print('Decrypted data:', decrypted_data)
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
```
2+
python3 -m venv path/to/venv
3+
source path/to/venv/bin/activate
4+
python3 -m pip install Crypto
5+
6+
```
Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
# import os
2+
# from werkzeug.security import check_password_hash, generate_password_hash
3+
# from dotenv import load_dotenv
4+
5+
# load_dotenv()
6+
7+
# def login(username, password):
8+
# admin_username = os.getenv('ADMIN_USERNAME')
9+
# admin_password_hash = os.getenv('ADMIN_PASSWORD_HASH')
10+
11+
# if username == admin_username and check_password_hash(admin_password_hash, password):
12+
# # Login successful
13+
# return True
14+
# else:
15+
# # Login failed
16+
# return False
17+
18+
# # Example usage
19+
# if __name__ == "__main__":
20+
# # For demonstration, let's generate a hash for a password
21+
# password_to_hash = "password123"
22+
# hashed_password = generate_password_hash(password_to_hash)
23+
# print(f"Hashed password for '{password_to_hash}': {hashed_password}")
24+
25+
# # Simulate a login attempt
26+
# username_input = "admin"
27+
# password_input = "password123"
28+
29+
# if login(username_input, password_input):
30+
# print("Login successful!")
31+
# else:
32+
# print("Login failed!")
33+
34+
# import os
35+
# from werkzeug.security import check_password_hash, generate_password_hash
36+
# from dotenv import load_dotenv
37+
38+
# load_dotenv()
39+
40+
# def login(username, password):
41+
# admin_username = os.getenv('ADMIN_USERNAME')
42+
# admin_password_hash = os.getenv('ADMIN_PASSWORD_HASH')
43+
44+
# if username == admin_username and check_password_hash(admin_password_hash, password):
45+
# # Login successful
46+
# return True
47+
# else:
48+
# # Login failed
49+
# return False
50+
51+
# # Example usage
52+
# if __name__ == "__main__":
53+
# # For demonstration, let's generate a hash for a password
54+
# password_to_hash = "password123"
55+
# hashed_password = generate_password_hash(password_to_hash)
56+
# print("Hashed password for '{}': {}".format(password_to_hash, hashed_password))
57+
58+
# # Simulate a login attempt
59+
# username_input = "admin"
60+
# password_input = "password123"
61+
62+
# if login(username_input, password_input):
63+
# print("Login successful!")
64+
# else:
65+
# print("Login failed!")
66+
67+
# import os
68+
# import argparse
69+
# from werkzeug.security import check_password_hash, generate_password_hash
70+
# from dotenv import load_dotenv
71+
72+
# def login(username, password):
73+
# admin_username = os.getenv('ADMIN_USERNAME')
74+
# admin_password_hash = os.getenv('ADMIN_PASSWORD_HASH')
75+
76+
# if username == admin_username and check_password_hash(admin_password_hash, password):
77+
# # Login successful
78+
# return True
79+
# else:
80+
# # Login failed
81+
# return False
82+
83+
# def main():
84+
# # Set up argument parsing
85+
# parser = argparse.ArgumentParser(description="Run the login script with environment variables.")
86+
# parser.add_argument('-e', '--env', action='append', help="Environment variables in the form KEY=VALUE")
87+
88+
# args = parser.parse_args()
89+
90+
# # Set environment variables from command line arguments
91+
# if args.env:
92+
# for env_var in args.env:
93+
# key, value = env_var.split('=', 1)
94+
# os.environ[key] = value
95+
96+
# # Load .env file if it exists
97+
# load_dotenv()
98+
99+
# # Simulate a login attempt
100+
# username_input = "admin"
101+
# password_input = "password123"
102+
103+
# if login(username_input, password_input):
104+
# print("Login successful!")
105+
# else:
106+
# print("Login failed!")
107+
108+
# if __name__ == "__main__":
109+
# main()
110+
111+
import bcrypt
112+
113+
# Example function to hash a password (this would be done during user registration)
114+
def hash_password(password):
115+
salt = bcrypt.gensalt()
116+
hashed = bcrypt.hashpw(password.encode(), salt)
117+
return hashed
118+
119+
# Example hashed password storage (in a real application, this would be stored in a database)
120+
stored_password_hash = hash_password('password123')
121+
122+
# Function to verify login credentials
123+
def login(username, password):
124+
# In a real application, retrieve the stored password hash from the database
125+
if username == 'admin':
126+
return bcrypt.checkpw(password.encode(), stored_password_hash)
127+
else:
128+
# Login failed
129+
return False
130+
131+
# Example usage
132+
print(login('admin', 'password123')) # True
133+
print(login('admin', 'wrongpassword')) # False
134+
print(login('user', 'password123')) # False
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
```
2+
python3 -m venv path/to/venv
3+
source path/to/venv/bin/activate
4+
python3 -m pip install bcrypt
5+
6+
7+
8+
```

0 commit comments

Comments
 (0)