Activity 42: Documentation of Python Flask hash
In computer science, hashing is a technique used to map data of arbitrary size (such as passwords, files, or any other data) to fixed-size values. These values are typically called hash values or hash codes, and they are generated by a function called a hash function. The key properties of hash functions are:
Deterministic: The same input will always produce the same hash value.
Fast: The function should be able to quickly generate the hash value.
Irreversible: Hashing is a one-way operation. It is computationally difficult to retrieve the original input from the hash value.
Uniqueness: Ideally, hash functions produce unique outputs for distinct inputs, although in practice there can be hash collisions (two different inputs producing the same hash).
Why Hashing Is Important
Hashing plays a crucial role in various domains such as:
Password Storage: When you register on websites, your password is typically not stored in plain text. Instead, the password is hashed, and the hash value is stored. When you log in, the system hashes the entered password and compares it with the stored hash. This ensures that even if a database is compromised, the actual passwords are not exposed.
Data Integrity: Hashing is used to ensure that data has not been tampered with. A hash value can be computed for a file, and when the file is accessed or transmitted, the hash can be recalculated to check its integrity.
Data Retrieval: Hashing is used in data structures like hash tables and hash maps for efficient data retrieval, ensuring that data is accessed in constant time, on average.
Step 1: Set Up Flask
Make sure you have Flask installed. If not, you can install it using:
pip install flask
Step 2: Create a Python Flask Application
Create a directory for your project (e.g., surname_python_flask_hash
) and create a file called app.py
. This file will contain the logic for our web application.
from flask import Flask, request, jsonify
import hashlib
app = Flask(__name__)
# Dictionary to store hash values
user_data = {}
# Route for GET /gethash
@app.route('/gethash', methods=['GET'])
def get_hash():
username = request.args.get('username') # Get the username from the query string
if username in user_data:
return jsonify({"username": username, "hash": user_data[username]})
return jsonify({"error": "User not found"}), 404
# Route for POST /sethash
@app.route('/sethash', methods=['POST'])
def set_hash():
data = request.json
username = data.get("username")
password = data.get("password")
if username and password:
# Hash the password using SHA-256
hashed_password = hashlib.sha256(password.encode()).hexdigest()
# Store the hashed password
user_data[username] = hashed_password
return jsonify({"message": "Hash stored successfully"}), 201
return jsonify({"error": "Username and password required"}), 400
# Route for GET /login
@app.route('/login', methods=['GET'])
def login():
username = request.args.get('username')
password = request.args.get('password')
if username and password:
hashed_password = hashlib.sha256(password.encode()).hexdigest()
if user_data.get(username) == hashed_password:
return jsonify({"message": "Login successful"})
return jsonify({"error": "Invalid username or password"}), 401
return jsonify({"error": "Username and password required"}), 400
# Route for GET /register
@app.route('/register', methods=['GET'])
def register():
return jsonify({"message": "Please use POST /sethash to register a user."})
if __name__ == '__main__':
app.run(debug=True)
Explanation of the Code:
GET
/gethash
:This route allows you to query a username and retrieve the associated hash.
The hash value is stored in the
user_data
dictionary where the username is the key, and the hashed password is the value.
POST
/sethash
:This route accepts a JSON object with a
username
and apassword
.The password is hashed using the
hashlib.sha256()
function, which returns a SHA-256 hash.The hashed password is stored in the
user_data
dictionary.
GET
/login
:This route accepts a
username
andpassword
.The password is hashed and compared with the stored hash value for that username.
If they match, the login is successful; otherwise, an error is returned.
GET
/register
:- This route simply provides information on how to register a user, directing the user to use the POST
/sethash
method to create a user.
- This route simply provides information on how to register a user, directing the user to use the POST
Step 3: Run the Flask Application
Run the application using the following command:
python app.py
The Flask server will start and you can now interact with the following routes:
GET
/gethash?username=<username>
: Retrieve the hash of a username.POST
/sethash
: Send a JSON object withusername
andpassword
to store the hash.GET
/login?username=<username>&password=<password>
: Check if the provided username and password match the stored hash.GET
/register
: A simple guide for registering a user.
Example Usage
- POST
/sethash
Example:http://127.0.0.1:5000/sethash
{
"username": "Ramon",
"password": "jovsecretpassword"
}
This will store the hash of the password for Ramon
.
- GET
/gethash
Example:
http://127.0.0.1:5000/gethash?username=Ramon
This will return the hash of Ramon
's password.
- GET
/login
Example:
http://127.0.0.1:5000/login?username=Ramon&password=jovsecretpassword
If the password matches the stored hash, the response will indicate a successful login.
- GET /
register
Example: