🔒 Security

Cryptography

Cryptography

Cryptography is the discipline of mathematical techniques and protocols for protecting information securely. It includes symmetric-key encryption (AES), asymmetric-key encryption (RSA, ECC), and hash functions (SHA-256), and ensures the confidentiality, integrity, authentication, and non-repudiation of data.

📖 Detailed Explanation

Cryptography began with the ancient Caesar cipher and has become the core discipline of modern computer security. "Crypto" comes from the Greek word for "hidden," and "graphein" means "to write." Modern cryptography goes beyond simple character substitution and is based on complex mathematical problems (integer factorization, discrete logarithms, elliptic curves). The four core goals of cryptography are Confidentiality, Integrity, Authentication, and Non-repudiation.

Symmetric Encryption uses the same key for encryption and decryption. AES (Advanced Encryption Standard) is the representative example and supports 128/192/256-bit keys. Symmetric keys are fast and efficient, but they have a key exchange problem. Asymmetric Encryption solves this problem by using a pair of a public key and a private key. RSA and ECC (Elliptic Curve Cryptography) are representative examples; RSA is based on the difficulty of integer factorization, and ECC is based on the elliptic curve discrete logarithm problem.

In practice, hybrid encryption is used. In the TLS handshake, the session key is securely exchanged using ECDHE (asymmetric key), and subsequent communication is encrypted with AES-GCM (symmetric key). This approach takes advantage of both the secure key exchange of asymmetric keys and the performance of symmetric keys. Digital signatures (RSA-PSS, ECDSA) use asymmetric keys to verify the origin and integrity of a message.

The advancement of quantum computers is putting RSA and ECC at risk. A quantum computer using Shor's algorithm can break a 2048-bit RSA key within a few hours. In 2024, NIST published post-quantum cryptography (PQC) standards. ML-KEM (key encapsulation) and ML-DSA (digital signatures) are the new standards and use lattice-based cryptography. Symmetric ciphers such as AES-256 remain secure against Grover's algorithm if the key size is doubled. As of 2025, organizations are preparing for PQC migration with a "hybrid approach."

💻 Code Example

# AES-256-GCM 암호화 예제 (Python)
# pip install cryptography
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
import os
import base64

class AESEncryptor:
    """AES-256-GCM 암호화 클래스"""

    def __init__(self, password: str):
        # 비밀번호에서 256비트 키 파생 (PBKDF2)
        salt = os.urandom(16)
        kdf = PBKDF2HMAC(
            algorithm=hashes.SHA256(),
            length=32,  # 256비트 = 32바이트
            salt=salt,
            iterations=600000,  # 2025 OWASP 권장
        )
        self.key = kdf.derive(password.encode())
        self.salt = salt

    def encrypt(self, plaintext: str) -> dict:
        """
        AES-256-GCM 암호화
        - GCM 모드: 암호화 + 인증(무결성 보장)을 동시에
        - Nonce(IV): 각 암호화마다 고유해야 함 (절대 재사용 금지!)
        """
        # 12바이트 nonce (GCM 권장 크기)
        nonce = os.urandom(12)

        aesgcm = AESGCM(self.key)
        ciphertext = aesgcm.encrypt(
            nonce,
            plaintext.encode('utf-8'),
            associated_data=None  # AAD: 추가 인증 데이터 (옵션)
        )

        return {
            'ciphertext': base64.b64encode(ciphertext).decode(),
            'nonce': base64.b64encode(nonce).decode(),
            'salt': base64.b64encode(self.salt).decode()
        }

    def decrypt(self, encrypted_data: dict) -> str:
        """AES-256-GCM 복호화"""
        nonce = base64.b64decode(encrypted_data['nonce'])
        ciphertext = base64.b64decode(encrypted_data['ciphertext'])

        aesgcm = AESGCM(self.key)
        plaintext = aesgcm.decrypt(nonce, ciphertext, None)

        return plaintext.decode('utf-8')


# 사용 예시
encryptor = AESEncryptor("my-secure-password-2025!")

# 암호화
message = "민감한 데이터: 신용카드 번호 4242-****-****-4242"
encrypted = encryptor.encrypt(message)
print(f"암호화된 데이터: {encrypted['ciphertext'][:50]}...")

# 복호화
decrypted = encryptor.decrypt(encrypted)
print(f"복호화된 데이터: {decrypted}")

# 주의사항:
# 1. Nonce는 절대 재사용 금지! (같은 키로 같은 nonce 사용 = 보안 붕괴)
# 2. CBC 모드 대신 GCM 모드 사용 (Padding Oracle 공격 방지)
# 3. ECB 모드는 절대 사용 금지 (패턴 노출)
# RSA 및 하이브리드 암호화 예제 (Python)
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
import os
import base64

class HybridEncryptor:
    """
    하이브리드 암호화 (RSA + AES)
    - RSA로 대칭키 암호화 (키 교환)
    - AES로 실제 데이터 암호화 (성능)
    """

    def __init__(self):
        # RSA 4096비트 키 쌍 생성 (2048은 최소, 4096 권장)
        self.private_key = rsa.generate_private_key(
            public_exponent=65537,
            key_size=4096
        )
        self.public_key = self.private_key.public_key()

    def get_public_key_pem(self) -> bytes:
        """공개키를 PEM 형식으로 내보내기"""
        return self.public_key.public_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PublicFormat.SubjectPublicKeyInfo
        )

    def encrypt(self, plaintext: str, recipient_public_key) -> dict:
        """
        하이브리드 암호화:
        1. 랜덤 AES 세션 키 생성
        2. RSA-OAEP로 세션 키 암호화
        3. AES-GCM으로 데이터 암호화
        """
        # 1. 랜덤 256비트 AES 세션 키 생성
        session_key = os.urandom(32)
        nonce = os.urandom(12)

        # 2. RSA-OAEP로 세션 키 암호화 (PSS 패딩 권장)
        encrypted_key = recipient_public_key.encrypt(
            session_key,
            padding.OAEP(
                mgf=padding.MGF1(algorithm=hashes.SHA256()),
                algorithm=hashes.SHA256(),
                label=None
            )
        )

        # 3. AES-GCM으로 데이터 암호화
        aesgcm = AESGCM(session_key)
        ciphertext = aesgcm.encrypt(nonce, plaintext.encode(), None)

        return {
            'encrypted_key': base64.b64encode(encrypted_key).decode(),
            'ciphertext': base64.b64encode(ciphertext).decode(),
            'nonce': base64.b64encode(nonce).decode()
        }

    def decrypt(self, encrypted_data: dict) -> str:
        """하이브리드 복호화"""
        # 1. RSA로 세션 키 복호화
        encrypted_key = base64.b64decode(encrypted_data['encrypted_key'])
        session_key = self.private_key.decrypt(
            encrypted_key,
            padding.OAEP(
                mgf=padding.MGF1(algorithm=hashes.SHA256()),
                algorithm=hashes.SHA256(),
                label=None
            )
        )

        # 2. AES로 데이터 복호화
        nonce = base64.b64decode(encrypted_data['nonce'])
        ciphertext = base64.b64decode(encrypted_data['ciphertext'])

        aesgcm = AESGCM(session_key)
        plaintext = aesgcm.decrypt(nonce, ciphertext, None)

        return plaintext.decode()


# 디지털 서명 예제
from cryptography.hazmat.primitives.asymmetric import padding as sign_padding

def sign_message(private_key, message: bytes) -> bytes:
    """RSA-PSS 디지털 서명"""
    signature = private_key.sign(
        message,
        sign_padding.PSS(
            mgf=sign_padding.MGF1(hashes.SHA256()),
            salt_length=sign_padding.PSS.MAX_LENGTH
        ),
        hashes.SHA256()
    )
    return signature

def verify_signature(public_key, message: bytes, signature: bytes) -> bool:
    """서명 검증"""
    try:
        public_key.verify(
            signature, message,
            sign_padding.PSS(
                mgf=sign_padding.MGF1(hashes.SHA256()),
                salt_length=sign_padding.PSS.MAX_LENGTH
            ),
            hashes.SHA256()
        )
        return True
    except Exception:
        return False
// Node.js 암호화 예제
const crypto = require('crypto');

// === AES-256-GCM 암호화 ===
class AESCrypto {
    constructor(password) {
        // 비밀번호에서 키 파생 (scrypt 사용)
        this.salt = crypto.randomBytes(16);
        this.key = crypto.scryptSync(password, this.salt, 32); // 256비트
    }

    encrypt(plaintext) {
        // 12바이트 IV (GCM 권장)
        const iv = crypto.randomBytes(12);

        const cipher = crypto.createCipheriv('aes-256-gcm', this.key, iv);
        let encrypted = cipher.update(plaintext, 'utf8', 'base64');
        encrypted += cipher.final('base64');

        // Auth Tag (GCM 무결성 검증용)
        const authTag = cipher.getAuthTag();

        return {
            ciphertext: encrypted,
            iv: iv.toString('base64'),
            authTag: authTag.toString('base64'),
            salt: this.salt.toString('base64')
        };
    }

    decrypt(encryptedData) {
        const decipher = crypto.createDecipheriv(
            'aes-256-gcm',
            this.key,
            Buffer.from(encryptedData.iv, 'base64')
        );

        decipher.setAuthTag(Buffer.from(encryptedData.authTag, 'base64'));

        let decrypted = decipher.update(encryptedData.ciphertext, 'base64', 'utf8');
        decrypted += decipher.final('utf8');

        return decrypted;
    }
}

// === RSA 키 쌍 생성 및 암호화 ===
function generateRSAKeyPair() {
    return crypto.generateKeyPairSync('rsa', {
        modulusLength: 4096,  // 4096비트 권장
        publicKeyEncoding: { type: 'spki', format: 'pem' },
        privateKeyEncoding: { type: 'pkcs8', format: 'pem' }
    });
}

function rsaEncrypt(publicKey, data) {
    return crypto.publicEncrypt(
        {
            key: publicKey,
            padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
            oaepHash: 'sha256'
        },
        Buffer.from(data)
    ).toString('base64');
}

// === 해시 및 HMAC ===
function hashSHA256(data) {
    return crypto.createHash('sha256').update(data).digest('hex');
}

function hmacSHA256(key, data) {
    return crypto.createHmac('sha256', key).update(data).digest('hex');
}

// === ECDH 키 교환 (Perfect Forward Secrecy) ===
function ecdhKeyExchange() {
    // Alice와 Bob의 ECDH 키 쌍 생성
    const alice = crypto.createECDH('prime256v1');  // P-256
    alice.generateKeys();

    const bob = crypto.createECDH('prime256v1');
    bob.generateKeys();

    // 공개키 교환 후 공유 비밀 계산
    const aliceSecret = alice.computeSecret(bob.getPublicKey());
    const bobSecret = bob.computeSecret(alice.getPublicKey());

    // 두 비밀이 동일함! (이것으로 세션 키 파생)
    console.log('Shared secret match:', aliceSecret.equals(bobSecret));

    return aliceSecret;
}

// 사용 예시
const aes = new AESCrypto('my-secure-password');
const encrypted = aes.encrypt('비밀 메시지');
console.log('Encrypted:', encrypted.ciphertext);
console.log('Decrypted:', aes.decrypt(encrypted));

🗣️ Say It Like This in Practice

💬 In a Security Architecture Meeting
"We encrypt sensitive data with AES-256-GCM. For key management, we use AWS KMS, and key rotation is performed automatically once a year. We separate database encryption keys from application-level encryption keys and manage them hierarchically."
💬 In a code review
"You should use GCM mode instead of ECB mode. ECB generates the same ciphertext block for the same plaintext block, so patterns are exposed. Also, the IV (Nonce) must be newly generated every time. If you reuse the same IV with the same key, security collapses completely."
💬 In Post-Quantum Cryptography Discussions
"For long-term stored data, we need to consider the quantum computer threat. To defend against 'Harvest Now, Decrypt Later' attacks, we are considering switching sensitive data to hybrid encryption (existing algorithms + PQC). NIST ML-KEM-768 is the general-purpose recommendation."

⚠️ Cautions & Best Practices

❌
Implementing Encryption Algorithms Yourself

"Don't roll your own crypto" - Do not implement encryption algorithms yourself. Use proven libraries (OpenSSL, libsodium, cryptography). Subtle implementation errors can become critical vulnerabilities.

❌
Using Vulnerable Algorithms

MD5, SHA-1, DES, RC4, and ECB mode are no longer secure. Use SHA-256 or higher, AES-256, RSA 2048+, or ECC P-256 or higher. Use OAEP or PSS instead of PKCS#1 v1.5 padding.

❌
Hardcoded Keys

Do not hardcode encryption keys in source code. Use environment variables, a secrets manager (AWS Secrets Manager, HashiCorp Vault), or KMS. If a key is pushed to Git, rotate it immediately.

✅
Encryption Best Practices

Use AES-256-GCM, generate a unique IV/Nonce, automate key rotation, protect keys with HSM/KMS, apply Crypto-agility (a design that allows algorithms to be swapped), and consider a PQC hybrid for long-term data. Combine encryption with hashing (integrity) and signatures (authentication).

🔗 Related Terms

📚 Learn More