암호화 알고리즘: 대칭키와 비대칭키
암호화 알고리즘 완벽 가이드
1. 대칭키 암호화
같은 키로 암호화/복호화
AES (Advanced Encryption Standard)
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
# 암호화
key = get_random_bytes(32) # 256비트
cipher = AES.new(key, AES.MODE_GCM)
plaintext = b"Secret message"
ciphertext, tag = cipher.encrypt_and_digest(plaintext)
# 복호화
cipher = AES.new(key, AES.MODE_GCM, nonce=cipher.nonce)
decrypted = cipher.decrypt_and_verify(ciphertext, tag)
AES 모드
ECB (Electronic Codebook) - 사용 금지!
같은 평문 → 같은 암호문
패턴 노출 위험
CBC (Cipher Block Chaining)
이전 블록과 XOR
IV (Initialization Vector) 필요
GCM (Galois/Counter Mode) - 권장
암호화 + 무결성 검증
병렬 처리 가능
2. 비대칭키 암호화
공개키로 암호화, 개인키로 복호화
RSA
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
# 키 생성
key = RSA.generate(2048)
private_key = key.export_key()
public_key = key.publickey().export_key()
# 암호화 (공개키)
cipher = PKCS1_OAEP.new(RSA.import_key(public_key))
ciphertext = cipher.encrypt(b"Secret")
# 복호화 (개인키)
cipher = PKCS1_OAEP.new(RSA.import_key(private_key))
plaintext = cipher.decrypt(ciphertext)
하이브리드 암호화
# 1. AES 키 생성 (대칭키)
aes_key = get_random_bytes(32)
# 2. 데이터를 AES로 암호화
cipher = AES.new(aes_key, AES.MODE_GCM)
encrypted_data = cipher.encrypt(large_data)
# 3. AES 키를 RSA로 암호화
rsa_cipher = PKCS1_OAEP.new(public_key)
encrypted_aes_key = rsa_cipher.encrypt(aes_key)
# 전송: encrypted_data + encrypted_aes_key
3. 해시 함수
SHA-256
import hashlib
data = b"Hello, World!"
hash_value = hashlib.sha256(data).hexdigest()
print(hash_value) # a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e
비밀번호 해싱 (bcrypt)
import bcrypt
# 해싱
password = b"user_password"
salt = bcrypt.gensalt(rounds=12) # Cost factor
hashed = bcrypt.hashpw(password, salt)
# 검증
if bcrypt.checkpw(password, hashed):
print("Password match")
4. 디지털 서명
from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA256
# 서명 생성
message = b"Important document"
hash_obj = SHA256.new(message)
signature = pkcs1_15.new(private_key).sign(hash_obj)
# 서명 검증
try:
pkcs1_15.new(public_key).verify(hash_obj, signature)
print("Signature is valid")
except (ValueError, TypeError):
print("Signature is invalid")
결론
암호화 선택 가이드:
- 데이터 암호화: AES-GCM
- 키 교환: RSA, ECDH
- 비밀번호: bcrypt, Argon2
- 무결성: HMAC, SHA-256