💻 Programming

Hash

Hash

Converts data into a fixed-length value. Used for hash tables, encryption, and integrity verification.

📖 Detailed Explanation

A hash is a function that converts data of arbitrary size into a fixed-size value. A hash function always returns the same output for the same input, and even a slight change in the input produces a completely different output. Thanks to these characteristics, it plays a key role in various fields such as data integrity verification, fast data retrieval, and cryptography.

A hash table is a representative data structure that uses a hash function; it stores key-value pairs and can look them up in O(1) time complexity on average. Python's dict, JavaScript's Object, and Java's HashMap are implemented based on hash tables, providing fast search performance even for large-scale data.

The key property of cryptographic hash functions (SHA-256, MD5, etc.) is one-wayness. It is computationally infeasible to reverse-engineer the original data from a hash value, and they are used for password storage, digital signatures, blockchain, and more. In particular, passwords are stored as hashes, and authentication is performed by comparing the hash of the entered password with the stored hash.

A hash collision is a phenomenon in which different inputs produce the same hash value. A good hash function has an extremely low probability of collisions, but in hash tables, collisions are handled by chaining or open addressing. Just as a commit ID in Git is a SHA-1 hash, hashes are also essential for file integrity verification and version control.

💻 Code Example

# 1. 해시 테이블 (Dictionary) 기본 사용
user_scores = {}  # 빈 해시 테이블 생성

# O(1) 시간에 데이터 삽입
user_scores["alice"] = 95
user_scores["bob"] = 87
user_scores["charlie"] = 92

# O(1) 시간에 데이터 조회
print(user_scores["alice"])  # 출력: 95

# 키 존재 여부 확인 - O(1)
if "bob" in user_scores:
    print(f"Bob의 점수: {user_scores['bob']}")

# 2. 암호학적 해시 (SHA-256)
import hashlib

def hash_password(password: str) -> str:
    """비밀번호를 SHA-256으로 해시하여 저장용 문자열 반환"""
    salt = "my_secret_salt"  # 실무에서는 랜덤 salt 사용
    salted = password + salt
    return hashlib.sha256(salted.encode()).hexdigest()

# 비밀번호 해시 생성
stored_hash = hash_password("mypassword123")
print(f"저장된 해시: {stored_hash[:32]}...")

# 로그인 시 검증
def verify_password(input_pw: str, stored: str) -> bool:
    return hash_password(input_pw) == stored

print(verify_password("mypassword123", stored_hash))  # True
print(verify_password("wrongpassword", stored_hash))  # False

# 3. 파일 무결성 검증
def get_file_hash(filepath: str) -> str:
    """파일의 MD5 해시 계산 (무결성 검증용)"""
    hash_md5 = hashlib.md5()
    with open(filepath, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()

# 4. 해시를 이용한 중복 제거
def remove_duplicates(items: list) -> list:
    """해시 기반 O(n) 중복 제거"""
    seen = set()  # set도 해시 테이블 기반
    result = []
    for item in items:
        if item not in seen:
            seen.add(item)
            result.append(item)
    return result

data = [1, 2, 2, 3, 3, 3, 4]
print(remove_duplicates(data))  # [1, 2, 3, 4]

🗣️ Say It Like This in Practice

💬 In a Meeting
"The user session lookup is slow because it iterates through an array. If we switch to a hash map, it improves from O(n) to O(1). If we use the session ID as the key, we can look up even 1 million users in constant time."
💬 In an Interview
"Hash collisions are resolved with chaining and open addressing. Chaining stores entries in a linked list in the same bucket, and open addressing looks for another empty bucket. Python's dict uses open addressing, and it resizes when the load factor exceeds 2/3."
💬 In a code review
"You must not store passwords with MD5. Please use bcrypt or argon2. MD5 is vulnerable to rainbow table attacks, and if you hash without a salt, the same password ends up with the same hash."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Using a mutable object as a hash key

Mutable objects such as lists cannot be used as hash keys. This is because if the hash value changes, lookup becomes impossible. Use immutable objects such as tuples or frozensets as keys.

❌
Using MD5/SHA-1 directly for passwords

Because general-purpose hashes are fast, they are vulnerable to brute-force attacks. For passwords, use intentionally slow hash algorithms such as bcrypt, scrypt, and argon2, and always add a salt.

✅
Choosing an appropriate hash function

Choose a hash that fits the purpose. Use fast hashes (MurmurHash, xxHash) for hash tables, SHA-256 for cryptography, and bcrypt/argon2 for passwords. Git is transitioning from SHA-1 to SHA-256.

🔗 Related Terms

📚 Learn More