🔐 Security

Encryption

Encryption

A core security technology that converts data into a form only authorized users can read. It ensures confidentiality by converting plaintext into ciphertext, and various algorithms are used depending on the purpose, such as symmetric-key (AES), asymmetric-key (RSA), and hash (SHA-256).

📖 History of Encryption

BC 700

Ancient ciphers

The Scytale cipher - a strip of leather wound around a rod to hide a message. The Caesar Cipher - substitutes letters by shifting the alphabet a fixed number of places.

1940s

Mechanical ciphers

The German Enigma machine. Alan Turing succeeded in breaking it, hastening the end of World War II. The origin of modern computer science.

1976

The birth of public-key cryptography

Publication of the Diffie-Hellman key exchange. Development of the RSA algorithm in 1977. Solving the key distribution problem laid the foundation of Internet security.

2001

AES standardization

The U.S. NIST adopted AES (Advanced Encryption Standard) as a standard. It is used as the standard encryption method by governments, financial institutions, and companies worldwide.

2020s

Quantum-resistant cryptography

Research on Post-Quantum Cryptography (PQC) to prepare for the quantum computer threat. NIST is standardizing CRYSTALS-Kyber, CRYSTALS-Dilithium, and others.

🔐 The Three Elements of Information Security (CIA Triad)

Encryption is a technical means of realizing the three core elements of information security.

🔒
Confidentiality
Confidentiality
Only authorized users can access the information. Implemented with encryption such as AES and RSA.
✅
Integrity
Integrity
Guarantees that information has not been tampered with. Verified with SHA-256 hashes and HMAC.
🆔
Authentication
Authentication
Verifying the identity of users/systems. Implemented with digital signatures and certificates.

🔑 Comparison of Encryption Types

🔐
Symmetric-key encryption
Uses the same key for encryption and decryption. Fast, suitable for large volumes of data.
AES-256 ChaCha20 3DES
🔓
Asymmetric-key encryption
Uses a public/private key pair. Solves the key exchange problem and enables digital signatures.
RSA ECC Ed25519
#️⃣
Hash function
One-way transformation (cannot be decrypted). Used for integrity verification and password storage.
SHA-256 bcrypt Argon2

📊 Comparison of Major Algorithms

Algorithm Type Key size Speed Main use Security status
AES-256 Symmetric key 256 bit Very fast File encryption, TLS, disks Recommended
ChaCha20 Symmetric key 256 bit Very fast Mobile, IoT, TLS 1.3 Recommended
RSA-2048 Asymmetric key 2048 bit Slow Key exchange, digital signatures Recommended (4096 preferred)
ECC P-256 Asymmetric key 256 bit Fast TLS, certificates, signatures Recommended
SHA-256 Hash 256 bit Very fast Integrity verification, blockchain Recommended
Argon2id Hash (KDF) Variable Intentional delay Password storage Highly recommended
DES Symmetric key 56 bit Fast Legacy systems Do not use
MD5 Hash 128 bit Fast Checksum (non-secure) Not for security use

💻 Actual Implementation Code

# AES-256-GCM 암호화 (Python cryptography 라이브러리)
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
import os
import base64

class AESEncryptor:
    """AES-256-GCM 암호화 클래스 (인증된 암호화)"""

    def __init__(self, key: bytes = None):
        # 키가 없으면 256비트(32바이트) 랜덤 키 생성
        self.key = key or AESGCM.generate_key(bit_length=256)
        self.aesgcm = AESGCM(self.key)

    def encrypt(self, plaintext: str, associated_data: bytes = None) -> str:
        """평문을 암호화하여 Base64 문자열로 반환"""
        # 12바이트 nonce (GCM 권장 크기)
        nonce = os.urandom(12)

        # 암호화 (인증 태그 자동 추가)
        ciphertext = self.aesgcm.encrypt(
            nonce,
            plaintext.encode('utf-8'),
            associated_data
        )

        # nonce + ciphertext를 Base64로 인코딩
        return base64.b64encode(nonce + ciphertext).decode('utf-8')

    def decrypt(self, encrypted: str, associated_data: bytes = None) -> str:
        """암호문을 복호화하여 평문 반환"""
        data = base64.b64decode(encrypted)
        nonce, ciphertext = data[:12], data[12:]

        # 복호화 (인증 실패 시 예외 발생)
        plaintext = self.aesgcm.decrypt(nonce, ciphertext, associated_data)
        return plaintext.decode('utf-8')

# 사용 예시
encryptor = AESEncryptor()

# 민감한 데이터 암호화
secret_data = "주민등록번호: 901234-1234567"
encrypted = encryptor.encrypt(secret_data)
print(f"암호화: {encrypted}")

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

# 키 안전 저장 (실제로는 KMS, HSM 사용)
key_b64 = base64.b64encode(encryptor.key).decode()
print(f"키(안전 저장 필요): {key_b64}")
# RSA 암호화 + 디지털 서명 (Python cryptography)
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import serialization
import base64

class RSACrypto:
    """RSA 암호화 및 디지털 서명"""

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

    def encrypt(self, plaintext: str) -> str:
        """공개키로 암호화 (상대방이 보낸 공개키 사용)"""
        ciphertext = self.public_key.encrypt(
            plaintext.encode('utf-8'),
            padding.OAEP(
                mgf=padding.MGF1(algorithm=hashes.SHA256()),
                algorithm=hashes.SHA256(),
                label=None
            )
        )
        return base64.b64encode(ciphertext).decode('utf-8')

    def decrypt(self, ciphertext: str) -> str:
        """개인키로 복호화 (자신의 개인키 사용)"""
        plaintext = self.private_key.decrypt(
            base64.b64decode(ciphertext),
            padding.OAEP(
                mgf=padding.MGF1(algorithm=hashes.SHA256()),
                algorithm=hashes.SHA256(),
                label=None
            )
        )
        return plaintext.decode('utf-8')

    def sign(self, message: str) -> str:
        """개인키로 서명 (발신자 신원 증명)"""
        signature = self.private_key.sign(
            message.encode('utf-8'),
            padding.PSS(
                mgf=padding.MGF1(hashes.SHA256()),
                salt_length=padding.PSS.MAX_LENGTH
            ),
            hashes.SHA256()
        )
        return base64.b64encode(signature).decode('utf-8')

    def verify(self, message: str, signature: str) -> bool:
        """공개키로 서명 검증 (발신자 확인)"""
        try:
            self.public_key.verify(
                base64.b64decode(signature),
                message.encode('utf-8'),
                padding.PSS(
                    mgf=padding.MGF1(hashes.SHA256()),
                    salt_length=padding.PSS.MAX_LENGTH
                ),
                hashes.SHA256()
            )
            return True
        except:
            return False

# 사용 예시: 안전한 메시지 전송
alice = RSACrypto()
bob = RSACrypto()

# Alice가 Bob에게 암호화된 메시지 전송
message = "계약금 1억원을 아래 계좌로 송금"

# Bob의 공개키로 암호화 (Bob만 복호화 가능)
encrypted = bob.encrypt(message)

# Alice의 개인키로 서명 (Alice가 보낸 것 증명)
signature = alice.sign(message)

# Bob이 수신 후
decrypted = bob.decrypt(encrypted)
is_valid = alice.verify(decrypted, signature)  # Alice 공개키로 검증

print(f"메시지: {decrypted}")
print(f"서명 검증: {'유효' if is_valid else '위조 의심'}")
# 패스워드 안전 저장 (bcrypt + Argon2)
import bcrypt
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError
import secrets

class PasswordManager:
    """안전한 패스워드 관리 (Argon2id 권장)"""

    def __init__(self, use_argon2: bool = True):
        self.use_argon2 = use_argon2
        if use_argon2:
            # Argon2id: 메모리 하드 + GPU 저항
            self.hasher = PasswordHasher(
                time_cost=3,          # 반복 횟수
                memory_cost=65536,     # 64MB 메모리
                parallelism=4,         # 4 스레드
                hash_len=32,           # 해시 길이
                salt_len=16            # Salt 길이
            )

    def hash_password(self, password: str) -> str:
        """패스워드를 해시하여 저장용 문자열 반환"""
        if self.use_argon2:
            return self.hasher.hash(password)
        else:
            # bcrypt: 자동 salt 생성, cost factor 12 권장
            salt = bcrypt.gensalt(rounds=12)
            return bcrypt.hashpw(password.encode(), salt).decode()

    def verify_password(self, password: str, hash_str: str) -> bool:
        """입력된 패스워드가 저장된 해시와 일치하는지 확인"""
        try:
            if self.use_argon2:
                self.hasher.verify(hash_str, password)
                return True
            else:
                return bcrypt.checkpw(password.encode(), hash_str.encode())
        except (VerifyMismatchError, ValueError):
            return False

    def needs_rehash(self, hash_str: str) -> bool:
        """해시 파라미터 업그레이드 필요 여부 확인"""
        if self.use_argon2:
            return self.hasher.check_needs_rehash(hash_str)
        return False

# 사용 예시: 회원가입/로그인
pm = PasswordManager(use_argon2=True)

# 회원가입 시
user_password = "MySecure@Pass123!"
stored_hash = pm.hash_password(user_password)
print(f"DB 저장: {stored_hash}")

# 로그인 시
login_attempt = "MySecure@Pass123!"
if pm.verify_password(login_attempt, stored_hash):
    print("로그인 성공!")

    # 해시 파라미터 업그레이드 체크
    if pm.needs_rehash(stored_hash):
        new_hash = pm.hash_password(login_attempt)
        print("해시 업그레이드 완료")
else:
    print("로그인 실패")

# 패스워드 강도 검증 추가 권장
def check_password_strength(password: str) -> dict:
    return {
        "length": len(password) >= 12,
        "uppercase": any(c.isupper() for c in password),
        "lowercase": any(c.islower() for c in password),
        "digit": any(c.isdigit() for c in password),
        "special": any(c in "!@#$%^&*" for c in password)
    }

💬 Learning Through Conversation

👤
Junior Developer
I need to store user passwords in the database. Can I just encrypt them with AES?
🔐
Security engineer
Absolutely not! AES is two-way encryption, so it can be decrypted. Passwords must be stored as a Hash. Use Argon2id or bcrypt. Even if an attacker steals the DB, they cannot recover the original passwords.
👤
Junior Developer
But isn't SHA-256 faster and more well known? Why use Argon2?
🔐
Security engineer
That very "speed" is the problem! SHA-256 can compute billions of hashes per second, so it is vulnerable to brute-force attacks. Argon2 is deliberately slow and designed to use a lot of memory, which also makes GPU parallel attacks difficult.
👤
Junior Developer
What encryption should I use for communication between API servers?
🔐
Security engineer
Use TLS 1.3. Internally, TLS combines RSA/ECDHE for key exchange with AES-GCM/ChaCha20 for data encryption. The key is to not implement it yourself but to use a proven library (OpenSSL, BoringSSL).

⚠️ Cautions

🚫

No homemade encryption algorithms

"Don't roll your own crypto" - a homemade encryption algorithm will always have vulnerabilities. Use only proven standards such as AES, RSA, and SHA-256.

🔒

Never use ECB mode

AES-ECB turns identical plaintext into identical ciphertext, exposing patterns. Always use AES-GCM or AES-CBC (with an IV).

🔑

Key management matters more than encryption

If you hardcode encryption keys in code or commit them to Git, the encryption is meaningless. Use a dedicated key management system such as AWS KMS, HashiCorp Vault, or Azure Key Vault.

⏰

Preparing for quantum computers

In the 2030s, quantum computers may break RSA and ECC. Encrypted data collected today could be decrypted in the future, so plan a transition to Post-Quantum encryption for sensitive data.

🔥 Encryption Failure Cases

Adobe data breach
2013

Incident: The account information of 153 million Adobe users was leaked. Passwords had been encrypted in AES-ECB mode, and because ECB turns identical passwords into identical ciphertext, pattern analysis was possible.

Problem: Using two-way encryption (AES) for passwords was itself a mistake, and ECB mode fails to hide patterns. The ciphertext of the most commonly used password, "123456", was identical, so it was easily traced back.

153 million accounts exposed ECB mode vulnerability Password patterns exposed
Lesson:

Always store passwords as hashes (bcrypt, Argon2). Never use ECB mode for encryption.

Heartbleed (OpenSSL vulnerability)
2014

Incident: A buffer over-read vulnerability was found in OpenSSL's Heartbeat extension. Attackers could read 64KB of server memory, exposing the private keys used for encryption.

Impact: About 17% of web servers worldwide (over 500,000) were affected. Once a private key is exposed, all previously captured TLS communications can be decrypted.

500,000+ servers affected Private key exposure risk Past communications decryptable
Lesson:

Regularly updating cryptographic libraries is essential. Use Forward Secrecy (ECDHE) to minimize damage from key exposure.

WannaCry ransomware
2017

Incident: The WannaCry ransomware infected more than 300,000 computers in 150 countries. It encrypted victims' files with AES, then encrypted the AES key with an RSA public key, making decryption impossible without the attacker's private key.

Damage: The UK's NHS (National Health Service) was paralyzed, with surgeries cancelled and ambulances diverted. Worldwide damage is estimated at about 4 to 8 billion US dollars.

300,000+ computers infected $4-8 billion in damage NHS medical services disrupted
Lesson:

Encryption is a double-edged sword. Prepare against ransomware with regular backups, patch management, and network segmentation.

🧠 Comprehension Quiz

Q. What is the most appropriate way to store user passwords in a database?
A. Encrypt and store with AES-256-GCM
B. Hash and store with SHA-256
C. Hash and store with Argon2id or bcrypt
D. Encrypt and store with an RSA public key
Answer: C

Passwords must be stored as a hash that cannot be decrypted. Since AES/RSA can be decrypted, all passwords leak if the key is exposed.

SHA-256 is a fast hash function that can be computed billions of times per second, making it vulnerable to brute-force attacks.

Argon2id (recommended) and bcrypt are deliberately slow and memory-intensive, so they resist GPU parallel attacks.

🔗 Related Terms

📚 Learning Resources