파이썬으로 블록 암호화 모드 구현하기

블록 암호화 모드는 암호화 알고리즘을 사용하여 데이터를 블록 단위로 암호화하는 기법입니다. 이 기법을 파이썬으로 구현하는 방법을 알아보겠습니다.

ECB (전자 코드북) 모드

ECB (Electronic Codebook) 모드는 가장 간단한 블록 암호화 모드로, 평문을 블록 단위로 나누고 각 블록을 독립적으로 암호화하는 방식입니다. 이 모드의 구현은 다음과 같습니다.

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
import os

def encrypt_ecb(key, plaintext):
    cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=default_backend())
    encryptor = cipher.encryptor()
    ciphertext = encryptor.update(plaintext) + encryptor.finalize()
    return ciphertext

def decrypt_ecb(key, ciphertext):
    cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=default_backend())
    decryptor = cipher.decryptor()
    plaintext = decryptor.update(ciphertext) + decryptor.finalize()
    return plaintext

# 테스트
key = os.urandom(32)  # 32바이트 랜덤 키 생성
plaintext = b'This is a test message.'
ciphertext = encrypt_ecb(key, plaintext)
decrypted_text = decrypt_ecb(key, ciphertext)

print("평문:", plaintext)
print("암호문:", ciphertext)
print("복호화된 텍스트:", decrypted_text)

CBC (암호 블록 연결) 모드

CBC (Cipher Block Chaining) 모드는 블록 간의 종속성을 도입하여 강력한 암호화를 제공하는 블록 암호화 모드입니다. ECB 모드와 달리 각 블록은 암호화할 때 이전 블록의 암호문과 XOR 연산을 수행합니다. 이 모드의 구현은 다음과 같습니다.

def encrypt_cbc(key, iv, plaintext):
    cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
    encryptor = cipher.encryptor()
    ciphertext = encryptor.update(plaintext) + encryptor.finalize()
    return ciphertext

def decrypt_cbc(key, iv, ciphertext):
    cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
    decryptor = cipher.decryptor()
    plaintext = decryptor.update(ciphertext) + decryptor.finalize()
    return plaintext

# 테스트
key = os.urandom(32)
iv = os.urandom(16)
plaintext = b'This is a test message.'
ciphertext = encrypt_cbc(key, iv, plaintext)
decrypted_text = decrypt_cbc(key, iv, ciphertext)

print("평문:", plaintext)
print("암호문:", ciphertext)
print("복호화된 텍스트:", decrypted_text)

블록 암호화 모드는 데이터 보안에 중요한 역할을 합니다. 적절한 모드를 선택하여 암호화를 사용하는 것은 보안 강화에 도움이 됩니다. 파이썬의 cryptography 모듈을 사용하여 간단한 블록 암호화 모드를 구현하는 방법을 알아보았습니다.

참고 자료