🔒 Security

Hashing

Hashing (Hash Function)

Hashing is a one-way function that converts data of arbitrary length into a fixed-length value (hash value, digest). The original cannot be recovered; Argon2 and bcrypt are used for password storage, and SHA-256 for data integrity verification.

📖 Detailed Explanation

A hash function is a mathematical function that takes an input of arbitrary size and produces a fixed-size output (hash value, digest). A cryptographic hash function must have three core properties. One-wayness (Pre-image Resistance): the original input cannot be recovered from the hash value. Collision Resistance: finding two inputs that produce the same hash is practically infeasible. Avalanche Effect: a small change in the input causes a drastic change in the output.

Hash functions are classified by purpose. General-purpose hash functions (SHA-256, SHA-3, BLAKE3) are used for data integrity verification, digital signatures, and blockchain. Password hashing functions (Argon2, bcrypt, scrypt) are intentionally designed to be slow, making brute-force attacks difficult. Argon2, the winner of the 2015 Password Hashing Competition, is the best choice as of 2025, and OWASP also recommends Argon2id as the top priority.

The key to password storage is Salt and an appropriate Work Factor. A Salt is a random value generated for each password, which prevents Rainbow Table attacks. Modern algorithms such as Argon2 and bcrypt handle Salt automatically. The Work Factor (Cost Factor) is the amount of computation/memory required for hashing, and it should be increased gradually in line with improvements in hardware performance. OWASP recommends a minimum of 19MiB of memory and 2 iterations for Argon2id, and 128MiB and 3-5 iterations for security-critical systems.

bcrypt is old but still secure. However, it is more vulnerable than Argon2 to GPU-based attacks. This is because Argon2 is a memory-hard algorithm, which makes large-scale parallel cracking difficult given the limited memory of GPUs. bcrypt's 72-byte password limit must also be taken into account. If you use bcrypt in a legacy system, set the Cost Factor to 12 or higher. For new projects, it is better to choose Argon2id. Adding a Pepper (a server-side secret key) provides an additional layer of protection even if the database is leaked.

💻 Code Example

# Argon2id 비밀번호 해싱 - 2025 최고의 선택 (Python)
# pip install argon2-cffi
from argon2 import PasswordHasher, exceptions
from argon2.profiles import RFC_9106_LOW_MEMORY, RFC_9106_HIGH_MEMORY

# === 기본 사용법 ===
ph = PasswordHasher()

def hash_password(password: str) -> str:
    """비밀번호 해싱"""
    # Argon2id는 Salt를 자동 생성하고 해시에 포함
    return ph.hash(password)

def verify_password(stored_hash: str, input_password: str) -> bool:
    """비밀번호 검증"""
    try:
        ph.verify(stored_hash, input_password)
        return True
    except exceptions.VerifyMismatchError:
        return False
    except exceptions.InvalidHashError:
        return False

# === OWASP 권장 파라미터로 커스텀 설정 ===
class SecurePasswordHasher:
    """OWASP 2025 권장 파라미터 적용"""

    def __init__(self, high_security: bool = False):
        if high_security:
            # 보안 중시: 128 MiB 메모리, 3회 반복
            self.ph = PasswordHasher(
                time_cost=3,           # 반복 횟수
                memory_cost=131072,    # 128 MiB (KB 단위)
                parallelism=4,         # 병렬 스레드
                hash_len=32,           # 해시 길이
                salt_len=16            # Salt 길이
            )
        else:
            # 일반: 19 MiB 메모리, 2회 반복 (최소 권장)
            self.ph = PasswordHasher(
                time_cost=2,
                memory_cost=19456,     # 19 MiB
                parallelism=1,
                hash_len=32,
                salt_len=16
            )

    def hash(self, password: str) -> str:
        return self.ph.hash(password)

    def verify(self, hash: str, password: str) -> tuple[bool, bool]:
        """
        검증 + 리해싱 필요 여부 반환
        파라미터가 변경되면 기존 해시를 새 파라미터로 업데이트 필요
        """
        try:
            self.ph.verify(hash, password)
            needs_rehash = self.ph.check_needs_rehash(hash)
            return True, needs_rehash
        except exceptions.VerifyMismatchError:
            return False, False


# 사용 예시
hasher = SecurePasswordHasher(high_security=True)

# 회원가입: 해싱
password = "MySecureP@ssw0rd2025!"
hashed = hasher.hash(password)
print(f"해시: {hashed}")
# 결과 예: $argon2id$v=19$m=131072,t=3,p=4$Salt$Hash

# 로그인: 검증
valid, needs_rehash = hasher.verify(hashed, password)
if valid:
    print("비밀번호 일치!")
    if needs_rehash:
        # 파라미터 업그레이드 시 리해싱
        new_hash = hasher.hash(password)
        # DB에 new_hash 저장
        print("보안 파라미터 업그레이드됨")

# 해시 구조 분석
# $argon2id$v=19$m=131072,t=3,p=4$randomSalt$hashedOutput
# - argon2id: 알고리즘 (id = Argon2i + Argon2d 하이브리드)
# - v=19: 버전
# - m=131072: 메모리 (KB)
# - t=3: 반복 횟수
# - p=4: 병렬성
// bcrypt 비밀번호 해싱 (Node.js)
// npm install bcrypt
const bcrypt = require('bcrypt');

// === 기본 사용법 ===
class PasswordManager {
    constructor(costFactor = 12) {
        // Cost Factor (Work Factor)
        // 10 = 2^10 = 1,024 반복
        // 12 = 2^12 = 4,096 반복 (2025 최소 권장)
        // 14 = 2^14 = 16,384 반복 (높은 보안)
        this.saltRounds = costFactor;
    }

    async hashPassword(password) {
        // bcrypt는 Salt를 자동 생성하고 해시에 포함
        // 주의: bcrypt는 72바이트 제한이 있음!
        if (password.length > 72) {
            throw new Error('bcrypt는 72바이트까지만 처리합니다');
        }
        return await bcrypt.hash(password, this.saltRounds);
    }

    async verifyPassword(inputPassword, storedHash) {
        return await bcrypt.compare(inputPassword, storedHash);
    }

    // Cost Factor 업그레이드 확인
    needsRehash(hash) {
        const match = hash.match(/^\$2[aby]?\$(\d+)\$/);
        if (!match) return true;
        const currentCost = parseInt(match[1], 10);
        return currentCost < this.saltRounds;
    }
}

// 사용 예시
const pm = new PasswordManager(12);

async function demo() {
    const password = 'MySecureP@ssw0rd!';

    // 해싱
    const hash = await pm.hashPassword(password);
    console.log('bcrypt 해시:', hash);
    // 결과 예: $2b$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/X4.1zCYSQ0KYB6OiS

    // 검증
    const isValid = await pm.verifyPassword(password, hash);
    console.log('검증 결과:', isValid); // true

    // 잘못된 비밀번호
    const isWrong = await pm.verifyPassword('wrongpassword', hash);
    console.log('잘못된 비밀번호:', isWrong); // false

    // 리해싱 필요 확인 (Cost Factor 업그레이드 시)
    const oldHash = '$2b$10$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQ...'; // Cost 10
    if (pm.needsRehash(oldHash)) {
        console.log('보안 업그레이드 필요: 새로운 해시 생성');
    }
}

// Pepper 추가 (선택적 추가 보안)
const PEPPER = process.env.PASSWORD_PEPPER; // 환경 변수에서 로드

async function hashWithPepper(password) {
    const pm = new PasswordManager(12);
    // Pepper를 비밀번호에 추가 (HMAC 권장)
    const crypto = require('crypto');
    const pepperedPassword = crypto
        .createHmac('sha256', PEPPER)
        .update(password)
        .digest('hex');
    return await pm.hashPassword(pepperedPassword);
}

demo();

// bcrypt 해시 구조:
// $2b$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/X4.1zCYSQ0KYB6OiS
// $2b = 알고리즘 버전
// $12 = Cost Factor (2^12 반복)
// 나머지 = Salt + Hash (22자 Salt, 31자 Hash)
# SHA-256: 데이터 무결성, 디지털 서명, 블록체인 등
# 비밀번호에는 사용하지 마세요! (너무 빠름)
import hashlib
import hmac

# === 1. 파일 무결성 검증 ===
def calculate_file_hash(filepath: str) -> str:
    """파일의 SHA-256 해시 계산"""
    sha256 = hashlib.sha256()
    with open(filepath, 'rb') as f:
        for chunk in iter(lambda: f.read(8192), b''):
            sha256.update(chunk)
    return sha256.hexdigest()

# 다운로드한 파일 검증
expected = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
actual = calculate_file_hash("downloaded_file.zip")
if actual == expected:
    print("파일 무결성 검증 통과!")
else:
    print("파일이 변조되었거나 손상됨!")


# === 2. HMAC: 메시지 인증 코드 ===
def create_hmac(key: bytes, message: bytes) -> str:
    """HMAC-SHA256으로 메시지 인증 코드 생성"""
    return hmac.new(key, message, hashlib.sha256).hexdigest()

def verify_hmac(key: bytes, message: bytes, expected_mac: str) -> bool:
    """HMAC 검증 (Timing Attack 방지)"""
    actual_mac = create_hmac(key, message)
    return hmac.compare_digest(actual_mac, expected_mac)

# API 요청 서명
api_key = b"secret-api-key-2025"
request_body = b'{"user_id": 123, "action": "transfer"}'
signature = create_hmac(api_key, request_body)
print(f"API 서명: {signature}")


# === 3. 블록체인/Merkle Tree ===
def merkle_hash(*items: bytes) -> str:
    """여러 데이터의 Merkle 해시 계산"""
    combined = b''.join(items)
    return hashlib.sha256(combined).hexdigest()


# === 4. 안전한 토큰 생성 ===
import secrets

def generate_secure_token(length: int = 32) -> str:
    """URL-safe 랜덤 토큰 생성"""
    return secrets.token_urlsafe(length)

def generate_api_key() -> tuple[str, str]:
    """API 키 생성: (실제 키, 저장용 해시)"""
    raw_key = secrets.token_hex(32)
    key_hash = hashlib.sha256(raw_key.encode()).hexdigest()
    return raw_key, key_hash  # raw_key는 사용자에게만, key_hash는 DB에

api_key, api_key_hash = generate_api_key()
print(f"사용자에게 전달: {api_key[:20]}...")
print(f"DB에 저장: {api_key_hash}")


# === 해시 알고리즘 선택 가이드 ===
#
# 비밀번호 저장: Argon2id > scrypt > bcrypt > PBKDF2
#   - SHA-256 단독 사용 금지! (너무 빠름 → 무차별 대입 취약)
#
# 데이터 무결성: SHA-256, SHA-3, BLAKE3
#   - MD5, SHA-1은 충돌 취약점으로 사용 금지
#
# 메시지 인증: HMAC-SHA256
#   - API 서명, JWT, 웹훅 검증 등
#
# 고성능 해싱: BLAKE3 (SHA-256보다 빠름)
#   - 파일 해싱, Merkle Tree 등

🗣️ Say It Like This in Practice

💬 In response to a security audit
"We hash passwords with Argon2id. With memory set to 128MiB and 3 iterations, we meet OWASP recommendations. Legacy bcrypt hashes are automatically migrated to Argon2 upon successful login. The Pepper is stored in an HSM, so there is an additional layer of protection even if the database is leaked."
💬 In a code review
"You must not store passwords with SHA-256. SHA-256 is fast, so a GPU can compute billions of hashes per second. bcrypt and Argon2 are intentionally slow and use a lot of memory, which raises the cost of cracking. Use the password_hash function provided by your framework."
💬 In a Performance Optimization Discussion
"If login response time is slow, you should adjust the Argon2 parameters. Aim for 200-500ms. If it is too fast, security is weakened, and if it is too slow, you become vulnerable to DoS attacks. Applying Rate Limiting to login requests and adding a delay on failure can mitigate brute-force attacks."

⚠️ Cautions & Best Practices

❌
Storing passwords with SHA-256/MD5/SHA-1

General-purpose hash functions are designed to be fast, which makes them vulnerable to password cracking. With a GPU, SHA-256 can be computed billions of times per second. Always use a hash dedicated to passwords, such as Argon2, bcrypt, or scrypt.

❌
Hashing without a Salt or reusing a Salt

Hashing without a Salt is vulnerable to Rainbow Table attacks. If the same Salt is used for all passwords, identical passwords produce identical hashes. Argon2 and bcrypt generate a Salt automatically, so there is no need to manage it yourself.

❌
Setting a low Work Factor

bcrypt cost=4 or Argon2 memory=4MB is not sufficient for security. OWASP recommendations: bcrypt cost 12+, Argon2id memory 19MiB+. Upgrade the parameters periodically as hardware performance improves.

✅
Password Hashing Best Practices

Use Argon2id as the top priority (bcrypt for legacy), upgrade parameters through rehashing at login, consider adding a Pepper, prevent brute-force attacks with Rate Limiting, and aim for a login response time of 200-500ms. For hash comparison, use a constant-time function to prevent Timing Attacks.

🔗 Related Terms

📚 Learn More