Sobes.tech
Junior
244

What do you know about hash functions?

Answer from AI

sobes.tech AI

A hash function is a function that transforms input data (of arbitrary size) into a fixed-size output string called a hash or message digest.

Main properties of hash functions:

  • Deterministic: The same input always produces the same hash.
  • Computational efficiency: Hash calculation should be fast.
  • Sensitivity to changes: Even a small change in input data should result in a significant change in the hash ("avalanche effect").
  • One-wayness: It should be practically impossible to reconstruct the original data from the hash.
  • Collision resistance: It should be very difficult to find two different inputs that produce the same hash.

Types of hash functions:

  • Cryptographic hash functions: Used in cryptography to ensure data integrity, digital signatures (MD5, SHA-1, SHA-256, SHA-3). MD5 and SHA-1 are considered less secure due to vulnerabilities.
  • Non-cryptographic hash functions: Used to speed up data lookup (e.g., in hash tables), checksums (CRC32). They do not possess collision resistance or one-wayness.

Application of hash functions in Python:

  • Hash tables (dictionaries): Use hashing internally for quick access to elements by key. Dictionary keys must be hashable (immutable).
  • Sets: Similarly, use hashes to store unique elements.
  • File integrity verification: Comparing hashes before and after data transfer.
  • Password storage: Store hashes of passwords instead of the passwords themselves (using salt to complicate dictionary attacks).
  • Cryptographic operations: The hashlib library provides access to various cryptographic hash functions.

Example of using hashlib:

import hashlib

data = b"Hello, world!"  # Input data must be in bytes
sha256_hash = hashlib.sha256(data).hexdigest()

print(f"SHA-256 hash for '{data.decode()}': {sha256_hash}")

# Example of data change
data_changed = b"Hello, world!!"
sha256_hash_changed = hashlib.sha256(data_changed).hexdigest()

print(f"SHA-256 hash for '{data_changed.decode()}': {sha256_hash_changed}")  # Hash will change significantly

Properties of hashable objects in Python:

  • The object must have a __hash__ method returning an integer.
  • The object must have an __eq__ method for equality comparison.
  • If a == b, then hash(a) should be equal to hash(b).
  • Usually, only immutable objects (strings, numbers, tuples) are hashable by default. Mutable objects (lists, dictionaries) are not hashable.