Middle
How have you used hashing in your projects before?
sobes.tech AI
Answer from AI
I used hashing for the following purposes:
- Password management: Storing one-way hashed passwords instead of plain text for increased security.
# Example of using bcrypt for password hashing import bcrypt password = b"mysecretpassword" # Generate salt and hash the password hashed_password = bcrypt.hashpw(password, bcrypt.gensalt()) print(hashed_password) # Password verification is_valid = bcrypt.checkpw(password, hashed_password) print(is_valid) - Data integrity verification: Hashing files or data to ensure their immutability. SHA256 algorithms were used.
# Example of verifying file integrity using SHA256 import hashlib def hash_file(filepath): hasher = hashlib.sha256() with open(filepath, 'rb') as f: while chunk := f.read(4096): hasher.update(chunk) return hasher.hexdigest() file_hash = hash_file("my_important_document.txt") print(file_hash) - Caching: Using hash keys for quick access to cache entries, for example, when working with Redis.
# Example of using hashing for cache key import hashlib import redis r = redis.StrictRedis(decode_responses=True) def get_cached_data(key): # Create hash of the key cache_key_hash = hashlib.sha256(key.encode()).hexdigest() data = r.get(cache_key_hash) if data: print("Data from cache") return data else: print("Data not in cache") # Simulate fetching data from source source_data = f"Data for key: {key}" # Save to cache with hashed key r.set(cache_key_hash, source_data, ex=60) # expire in 60 seconds return source_data print(get_cached_data("user:123:profile")) print(get_cached_data("user:123:profile")) # Second time from cache - Data structures: Internal use of hashing in Python dictionaries (dict) and sets for efficient lookup and storage of unique elements.
# Python dict and set use hashing my_dict = {"key1": "value1", "key2": "value2"} my_set = {"item1", "item2", "item1"} print(my_dict["key1"]) # Fast access by hash print(my_set) # Unique elements, determined by hash
Depending on the task, an appropriate hashing algorithm and library (e.g., hashlib, bcrypt) were chosen.