개발/python

[Python example] 간단한 문자열 암호화 예제

Dsp 2009. 1. 12. 06:52
문자열을 암호화하는 방법은 여러가지가 있습니다만,
이번에는 가장 간단한 방법 중 하나인 caesar  암호법을 이용해 보죠.
caesar 암호법은 각각의 알파벳을 나열한 후, 일정한 간격으로 옮기는 방법입니다.
예를 들어, 'GOOD'를 오른쪽으로 하나씩 옮기면 'HPPE'가 되서 알아보기 힘들게 되는 것이죠.

이 문제는 chr과 ord를 이용하면 아래 예제와 같이 간단하게 해결됩니다.

import sys
SHIFT=1

def encrypt( raw ):
    ret = ''
    for char in raw:
        ret+=chr( ord(char)+SHIFT )
    return ret

def decrypt( raw ):
    ret = ''
    for char in raw:
        ret+=chr( ord(char)-SHIFT )
    return ret
   
if __name__=="__main__":
    print( sys.version )
    raw = input("input : ")
    encrypted = encrypt( raw )
    print("encrypted : " + encrypted)
   
    decrypted = decrypt( encrypted )
    print("decrypted : " + decrypted)
    input("press any key")

이 예제에서 어느정도 간격으로 이동할지에 대한 변수는 SHIFT입니다.
즉 현재는 오른쪽으로 1칸 이동하게 짜여져 있는 것입니다.
실행시켜보면 다음과 같이 암호화/복호화가 잘 되는 것을 볼 수 있습니다.

3.0 (r30:67507, Dec  3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)]
input : hello world
encrypted : ifmmp!xpsme
decrypted : hello world
press any key