이번 프로젝트에서는 문자열을 활용해 고전 암호 기법인 Caesar Cipher와 Vigenère Cipher를 구현해보고, 이를 해독하는 방법까지 단계별로 정리해보았다.
Step 1: Caesar Cipher란?
Caesar Cipher는 고대 로마의 카이사르가 사용하던 고전 암호 방식으로, 알파벳을 일정한 수만큼 "밀어서" 암호화하는 방식이다.
파이썬의 문자열 조작을 이용하여 암호문과 오프셋을 파라미터로 하는 암호문 Decode 함수를 아래와 같이 구현할 수 있다.
def caesar_decode(message, offset):
alphabet = "abcdefghijklmnopqrstuvwxyz"
translated = ""
for char in message:
if char in alphabet:
idx = alphabet.index(char)
translated += alphabet[(idx + offset) % 26]
else:
translated += char
return translated
위 함수는 암호 문장의 각 문자를 하나씩 순회하며, alphabet.index()를 이용해 loop의 현재 문자의 위치를 찾고, + offset으로 새로운 문자의 위치를 계산한 뒤 % 26으로 알파벳 범위를 넘지 않도록 처리한다.
Step 2: 메시지 암호화하기 (Caesar Encode)
Caesar Encode 함수는 Decode 함수의 반대 방향으로 문자를 오프셋만큼 이동시켜 문장을 암호화 한다.
def caesar_encode(message, offset):
alphabet = "abcdefghijklmnopqrstuvwxyz"
encoded = ""
for char in message:
if char in alphabet:
idx = alphabet.index(char)
encoded += alphabet[(idx - offset) % 26]
else:
encoded += char
return encoded
이 함수는 동일한 로직이지만 방향만 바뀌었으며, 복호화된 메시지를 다시 암호화하면 원본 메시지를 되찾을 수 있다.
Step 3: Caesar Cipher의 약점 - Brute Force 공격
Caesar Cipher의 가장 큰 약점은 shift 값을 모를 때도, 단 26가지 조합만으로 쉽게 무차별 대입 공격(Brute Force)이 가능하다는 것이다.
cipher = "vhfinmxkl atox kxgwxkxw tee hy maxlx hew..."
for i in range(1, 26):
print("Offset:", i)
print(caesar_decode(cipher, i))
결과를 출력해보며 사람이 읽을 수 있는 문장이 나올 때까지 반복하면 된다.
Step 4: Vigenère Cipher - 한층 더 강력한 암호 방식
Vigenère Cipher는 문자열의 각 문자마다 다른 offset 값을 사용하는 방식이다. 이 때 키워드(keyword)를 이용하며, 해당 키워드를 반복해서 메시지 길이만큼 확장하여 각각의 문자에 대응시킨다.
아래는 Vigenère Cipher를 활용한 암호문 Decode 함수이다.
def vigenere_decode(message, keyword):
alphabet = "abcdefghijklmnopqrstuvwxyz"
decoded = ""
keyword_phrase = ""
keyword_index = 0
for char in message:
if char in alphabet:
keyword_phrase += keyword[keyword_index % len(keyword)]
keyword_index += 1
else:
keyword_phrase += char
for i in range(len(message)):
if message[i] in alphabet:
m_idx = alphabet.index(message[i])
k_idx = alphabet.index(keyword_phrase[i])
decoded += alphabet[(m_idx + k_idx) % 26]
else:
decoded += message[i]
return decoded
반대로 암호화는 +가 아닌 - 연산을 사용하면 된다.
실습 정리
- str.index()와 % 26 연산으로 문자열 내 위치 조작을 처리함
- 문자열 하나하나를 순회하며 직접 위치를 계산해 암호/복호화
- Caesar → 고정된 offset, Vigenère → 키워드에 따라 달라지는 offset
- 단순한 암호일수록 brute-force로 손쉽게 깨질 수 있음
'Python' 카테고리의 다른 글
파이썬 String 조작 실습 (0) | 2025.04.05 |
---|---|
파이썬으로 JSON API 데이터 추출 및 CSV 변환하기 (0) | 2025.04.05 |
Python 반복문(Loop)과 리스트 실습 (0) | 2025.04.03 |
파이썬 리스트 함수 실습 (0) | 2025.04.02 |
Map, Lambda, Filter in Python (0) | 2024.06.06 |