Hash
Hash
A function that converts data into a fixed-length value. Used in hash tables, cryptography, and integrity verification.
Hash
A function that converts data into a fixed-length value. Used in hash tables, cryptography, and integrity verification.
A hash is the result of a function that converts data of arbitrary size into a fixed-size value. A hash function always produces the same output for the same input, and it is difficult to derive the input from the output (one-way property). Hashes are widely used in hash tables, encryption, data integrity verification, blockchain, and more.
A hash table is a data structure that stores key-value pairs, using a hash function to convert a key into an array index. In theory, search, insertion, and deletion are possible in O(1) time. Python's dict, JavaScript's Object/Map, and Java's HashMap are based on hash tables.
Cryptographic hash functions (SHA-256, SHA-3, bcrypt, etc.) are specialized for security. They provide collision resistance (it is difficult for different inputs to produce the same output) and preimage resistance (it is difficult to guess the input from the output). They are used for password storage, digital signatures, and blockchain.
A hash collision (Collision) is a phenomenon in which different inputs produce the same hash value. In hash tables, collisions are handled by chaining (Chaining) or open addressing (Open Addressing). A good hash function minimizes collisions and distributes values evenly.
# Python 해시 예제
import hashlib
from collections import defaultdict
# 1. 기본 해시 함수
text = "Hello, World!"
hash_value = hash(text)
print(f"Python hash: {hash_value}")
# 2. SHA-256 해시
sha256_hash = hashlib.sha256(text.encode()).hexdigest()
print(f"SHA-256: {sha256_hash}")
# 출력: dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f
# 3. 파일 무결성 검증
def file_hash(filepath):
sha256 = hashlib.sha256()
with open(filepath, 'rb') as f:
for chunk in iter(lambda: f.read(4096), b''):
sha256.update(chunk)
return sha256.hexdigest()
# 4. 해시 테이블 (dict) 활용
user_cache = {}
user_cache['alice'] = {'name': 'Alice', 'age': 30}
user_cache['bob'] = {'name': 'Bob', 'age': 25}
print(user_cache.get('alice')) # O(1) 조회
# 5. 충돌 처리 예시 (체이닝)
class HashTable:
def __init__(self, size=10):
self.size = size
self.table = [[] for _ in range(size)]
def _hash(self, key):
return hash(key) % self.size
def set(self, key, value):
index = self._hash(key)
for i, (k, v) in enumerate(self.table[index]):
if k == key:
self.table[index][i] = (key, value)
return
self.table[index].append((key, value))
def get(self, key):
index = self._hash(key)
for k, v in self.table[index]:
if k == key:
return v
return None
Senior: We're storing passwords with SHA-256, but we need to switch to bcrypt.
Junior: Isn't SHA-256 secure enough?
Senior: SHA-256 is a fast hash, so a GPU can try billions of guesses per second. bcrypt is deliberately designed to be slow, which makes brute force difficult. It also handles salting automatically.
Interviewer: Please explain the time complexity of a hash table and its worst case.
Candidate: On average it is O(1), but if all keys fall into the same bucket, it becomes O(n). To prevent this, you need a good hash function and appropriate load factor management. Typically, the table is resized when the load factor exceeds 0.75.
Interviewer: Please compare the methods for resolving hash collisions.
Candidate: Chaining handles collisions by keeping a linked list in each bucket, and it is simple to implement. Open addressing finds another empty slot to store the value, and it has good cache efficiency but deletion is complicated.
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
Reviewer: You're hashing API tokens with MD5, but MD5 is no longer secure.
Author: You mean collision attacks are possible?
Reviewer: Yes, replace it with SHA-256 or SHA-3. Security-related hashes should always use the latest recommended algorithms.