Python🐍

카이사르 암호화 복호화

hoho0311 2025. 1. 19. 00:28

 

과거에서부터 여러 중요한 정보를 암호화하려는 노력이 많았다.

과거 약 기원전 100년경에 로마의 장군인 카이사르가 동맹군들과 소통하기 위해 만든 암호인

카이사르 암호에 대해 간략히 설명하겠다.

 

카이사르 암호(Caesar cipher) 또는 시저 암호는 암호학에서 다루는 간단한 치환암호의 일종이다.

카이사르 암호는 암호화하고자 하는 내용을 알파벳별로 일정한 거리만큼 일어서 다른 알파벳으로 치환하는 방식이다.

아래 사진을 보면 더 이해가 잘 될 것이다.

 

카이사르 암호는 각각의 알파벳을 일정한 거리만큼 밀어 글자를 치환하는 방식으로 암호화한다. 위 예제에서는 3글자씩밀어서 암호화하기 떄문에 'B'는 'E'로 치환한다.

 

더 자세한 내용은 아래 링크를 달아 두겠다.

https://namu.wiki/w/%EC%95%94%ED%98%B8#s-2.1.2

 

import art

print(art.logo)

alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
			'p', 'q', 'r', 's', 't', 'u','v', 'w', 'x', 'y', 'z']

먼저 카이사르 프로그램을 실행하면 나오는 제목 부분과 모든 알파벳을 리스트에 적은 알파벳이 있다.

아트 파일은 마지막에 올리겠다.

def caesar(original_text, shift_amount, encode_or_decode):
    output_text = ""
    if encode_or_decode == "decode":
        shift_amount *= -1

    for letter in original_text:

        if letter not in alphabet:
            output_text += letter
        else:
            shifted_position = alphabet.index(letter) + shift_amount
            shifted_position %= len(alphabet)
            output_text += alphabet[shifted_position]
    print(f"Here is the {encode_or_decode}d result: {output_text}")

가장 중요한 시저 함수이다.

받는 인자로는 original_text, shift_amount, encode_or_decode다. 각각 설명하겠다.

 

original_text : 사용자가 암호화나 복호화하고 싶은 내용을 입력한다..

shift_amount : 사용자가 얼마나 알파벳을 밀거나 당길지 입력한다.

encode_or_decode : 사용자가 암호화할지 복호화할지 입력한다.

 

좀 더 자세히 코드를 뜯어서 설명하겠다.

    output_text = ""
    if encode_or_decode == "decode":
        shift_amount *= -1

 

output_text는 암호화나 복호화한 결과를 담당하는 변수이다. 

모든 글자를 하나씩 더하는 방식이어서 for문 안에 입력하면 초기화되기 때문에

for문 밖에 선언하였다.

 

If문이다.

암호화하기 위해서는 밀고 복호화하기 위해서는 당겨야 하기 때문에

음수를 곱하여 방향을 정하였다.

 쉽게 말해 왼쪽으로 갈지 오른쪽으로 갈지 정한다.

 for letter in original_text:

        if letter not in alphabet:
            output_text += letter
        else:
            shifted_position = alphabet.index(letter) + shift_amount
            shifted_position %= len(alphabet)
            output_text += alphabet[shifted_position]
    print(f"Here is the {encode_or_decode}d result: {output_text}")

 

가장 어려웠던 for문이다.

for letter in original_text: 는 사용자가 입력한 글자를 한 글자씩 확인하겠다는 반복문이다.

 

만약 letter가 알파벳이 아니라 숫자나 특수기호일 때 그냥 무시하고 output_text에 추가하였다.

shifted_position은 사용자가 입력한 글자의 알파벳 순서를 구하고 shift_amount를 더하였다.

(암호화 방식에 따라 더하거나 뺄 수 있다.)

 

마지막엔 output_text에 밀거나 당긴 알파벳을 추가한다.

 

should_continue = True

while should_continue:

    direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n").lower()
    text = input("Type your message:\n").lower()
    shift = int(input("Type the shift number:\n"))

    caesar(original_text=text, shift_amount=shift, encode_or_decode=direction)

    restart = input("Type 'yes' if you want to go again. Otherwise, type 'no'.\n").lower()
    if restart == "no":
        should_continue = False
        print("Goodbye")

마지막 while문 부분이다.

should_continue를 Ture로 주고 while문을 무한 반복에 넣는다.

사용자에게 필요한 정보를 받은 후

caesar 함수를 호출한 뒤 각 인자를 보내주면 결과가 나온다.

 

마지막에 사용자에게 계속 사용할 건지 물어본다.

만약 No를 입력할 시 should_continueFalse로 변하여

즉시 무한 루프에서 빠져나와 프로그램이 종료된다.

 

마지막으로 실행화면 첨부하고 글을 마무리하겠다.

 

뭐 했다고 벌써부터 어려워서 막히기 시작한다.

이제 슬슬 지피티 없으면 힘들다...

마지막까지 잘할 수 있을지 걱정이다.

 

logo = """           
 ,adPPYba, ,adPPYYba,  ,adPPYba, ,adPPYba, ,adPPYYba, 8b,dPPYba,  
a8"     "" ""     `Y8 a8P_____88 I8[    "" ""     `Y8 88P'   "Y8  
8b         ,adPPPPP88 8PP"""""""  `"Y8ba,  ,adPPPPP88 88          
"8a,   ,aa 88,    ,88 "8b,   ,aa aa    ]8I 88,    ,88 88          
 `"Ybbd8"' `"8bbdP"Y8  `"Ybbd8"' `"YbbdP"' `"8bbdP"Y8 88   
            88             88                                 
           ""             88                                 
                          88                                 
 ,adPPYba, 88 8b,dPPYba,  88,dPPYba,   ,adPPYba, 8b,dPPYba,  
a8"     "" 88 88P'    "8a 88P'    "8a a8P_____88 88P'   "Y8  
8b         88 88       d8 88       88 8PP""""""" 88          
"8a,   ,aa 88 88b,   ,a8" 88       88 "8b,   ,aa 88          
 `"Ybbd8"' 88 88`YbbdP"'  88       88  `"Ybbd8"' 88          
              88                                             
              88           
"""