Encryption
Encryption
A technology that protects confidentiality by converting data into an unreadable form. Divided into symmetric-key (AES) and asymmetric-key (RSA) encryption and hash functions.
Encryption
A technology that protects confidentiality by converting data into an unreadable form. Divided into symmetric-key (AES) and asymmetric-key (RSA) encryption and hash functions.
Encryption is a technology that protects data from unauthorized access by converting plaintext into ciphertext. Decryption, the reverse process of encryption, converts ciphertext back into plaintext. Modern cryptography uses mathematical algorithms and keys to provide a level of security at which decryption is practically impossible even with computers.
Symmetric encryption uses the same key for encryption and decryption. AES and ChaCha20 are representative examples; they are fast and suitable for processing large amounts of data. The drawback is the key exchange problem: a method for delivering the key securely is required. Asymmetric encryption uses a pair of a public key and a private key. RSA and ECDSA are representative examples; data encrypted with the public key can only be decrypted with the private key. Secure communication is possible without key exchange, but it is slower than symmetric encryption.
A hash function, unlike encryption, is a one-way transformation. It converts an input of arbitrary size into a fixed-size output (hash value), and restoring the original is impossible. SHA-256, bcrypt, and Argon2 are representative examples. They are used for password storage, data integrity verification, and digital signatures. The same input always produces the same hash, but tracing the original back from the hash is computationally infeasible.
In practice, a hybrid approach is used. In the TLS handshake, a session key is securely exchanged using asymmetric keys, and subsequent data transmission is encrypted with the symmetric key (the session key). This makes it possible to take advantage of both the security of asymmetric keys and the speed of symmetric keys. The standard is to protect data at rest with AES-256 and data in transit with TLS.
# AES-256-GCM 대칭키 암호화 - Python cryptography
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
import os
import base64
class SymmetricEncryption:
"""대칭키 암호화: 같은 키로 암호화/복호화"""
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) -> dict:
"""
평문 암호화
GCM 모드는 암호화 + 무결성 검증(AEAD) 제공
"""
# 12바이트 nonce (매번 새로 생성!)
nonce = os.urandom(12)
# 암호화 (UTF-8 인코딩)
ciphertext = self.aesgcm.encrypt(
nonce,
plaintext.encode('utf-8'),
None # associated_data (선택)
)
return {
'nonce': base64.b64encode(nonce).decode(),
'ciphertext': base64.b64encode(ciphertext).decode()
}
def decrypt(self, encrypted: dict) -> str:
"""암호문 복호화"""
nonce = base64.b64decode(encrypted['nonce'])
ciphertext = base64.b64decode(encrypted['ciphertext'])
plaintext = self.aesgcm.decrypt(nonce, ciphertext, None)
return plaintext.decode('utf-8')
# 사용 예시
if __name__ == "__main__":
crypto = SymmetricEncryption()
# 민감 데이터 암호화
original = "사용자 비밀번호: P@ssw0rd123"
encrypted = crypto.encrypt(original)
print(f"암호문: {encrypted['ciphertext'][:40]}...")
# 복호화
decrypted = crypto.decrypt(encrypted)
print(f"복호화: {decrypted}")
# 키 저장 (안전한 곳에!)
print(f"키: {base64.b64encode(crypto.key).decode()}")
# RSA 비대칭키 암호화 - 공개키/개인키 쌍 사용
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import hashes, serialization
class AsymmetricEncryption:
"""비대칭키 암호화: 공개키로 암호화, 개인키로 복호화"""
def __init__(self):
# RSA 키 쌍 생성 (2048비트 이상 권장)
self.private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048
)
self.public_key = self.private_key.public_key()
def encrypt(self, plaintext: str) -> bytes:
"""공개키로 암호화 (누구나 암호화 가능)"""
ciphertext = self.public_key.encrypt(
plaintext.encode('utf-8'),
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
return ciphertext
def decrypt(self, ciphertext: bytes) -> str:
"""개인키로 복호화 (키 소유자만 복호화 가능)"""
plaintext = self.private_key.decrypt(
ciphertext,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
return plaintext.decode('utf-8')
def export_public_key(self) -> str:
"""공개키를 PEM 형식으로 내보내기 (공유 가능)"""
pem = self.public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
return pem.decode('utf-8')
def sign(self, message: str) -> bytes:
"""개인키로 서명 (발신자 증명)"""
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 signature
def verify(self, message: str, signature: bytes) -> bool:
"""공개키로 서명 검증"""
try:
self.public_key.verify(
signature,
message.encode('utf-8'),
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
return True
except Exception:
return False
# 사용 예시: 안전한 메시지 전송
sender = AsymmetricEncryption()
receiver = AsymmetricEncryption()
# 1. 발신자가 수신자의 공개키로 암호화
message = "기밀 정보입니다"
encrypted = receiver.public_key.encrypt(
message.encode(),
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
print(f"암호화 완료: {len(encrypted)} bytes")
# 2. 수신자가 자신의 개인키로 복호화
decrypted = receiver.decrypt(encrypted)
print(f"복호화: {decrypted}")
# 해시 함수 & 비밀번호 해싱
import hashlib
import bcrypt
import secrets
# === 1. SHA-256 해시 (데이터 무결성 검증) ===
def sha256_hash(data: str) -> str:
"""SHA-256 해시 생성 - 파일 무결성, 데이터 검증용"""
return hashlib.sha256(data.encode()).hexdigest()
# 같은 입력 = 같은 해시
print(sha256_hash("hello")) # 2cf24dba5fb0a30e26e83b2ac5b9e29e...
print(sha256_hash("hello")) # 동일한 해시
# 작은 변화 = 완전히 다른 해시 (눈사태 효과)
print(sha256_hash("hello!")) # 전혀 다른 값
# === 2. 비밀번호 해싱 (bcrypt 권장) ===
def hash_password(password: str) -> bytes:
"""
비밀번호 해싱 - bcrypt 사용
- 솔트 자동 생성
- 계산 비용 조절 가능 (brute-force 방어)
"""
salt = bcrypt.gensalt(rounds=12) # 2^12 반복
return bcrypt.hashpw(password.encode(), salt)
def verify_password(password: str, hashed: bytes) -> bool:
"""비밀번호 검증"""
return bcrypt.checkpw(password.encode(), hashed)
# 비밀번호 저장 시
password = "MySecretP@ss123"
hashed = hash_password(password)
print(f"저장할 해시: {hashed.decode()}")
# 로그인 시 검증
is_valid = verify_password("MySecretP@ss123", hashed)
print(f"비밀번호 일치: {is_valid}") # True
is_valid = verify_password("wrong_password", hashed)
print(f"비밀번호 일치: {is_valid}") # False
# === 3. 토큰 생성 (secrets 모듈) ===
# API 키, 세션 토큰 등 암호학적으로 안전한 랜덤 값
api_key = secrets.token_urlsafe(32) # URL-safe 32바이트
session_token = secrets.token_hex(16) # 16바이트 hex
print(f"API Key: {api_key}")
print(f"Session: {session_token}")
"We encrypt data at rest with AES-256 and protect data in transit with TLS 1.3. Encryption keys are managed in AWS KMS, and I'll set the key rotation period to 90 days. Passwords are hashed with bcrypt and stored."
"We applied column-level encryption to personal information. Resident registration numbers and card numbers are encrypted with AES-256-GCM, and fields that need to be searched use deterministic encryption, so indexing is possible. We use hashing and encryption separately."
"The difference between symmetric and asymmetric keys is how the keys are used. Symmetric keys use the same key for encryption and decryption, so they are fast but have a key exchange problem; asymmetric keys use a public key/private key pair, so they are secure without key exchange but slow. TLS combines the two as a hybrid."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
MD5 and SHA-1 are vulnerable to collision attacks. Use SHA-256 or higher even for integrity verification. Use bcrypt or Argon2 for password hashing.
Do not implement encryption algorithms yourself. Use only proven libraries (cryptography, OpenSSL). "Homegrown encryption" is almost always vulnerable.
If you write encryption keys directly in code, they are exposed in Git. Use a secure key management system such as environment variables, KMS, or Vault.
Use AES-256-GCM (symmetric key), RSA-2048+ (asymmetric key), and bcrypt/Argon2 (passwords). Establish a key rotation policy, and store ciphertext and keys separately.