Caesar cipher with Python
*This post comes from my blog
I created Caesar cipher with Python.
import sys
def caesar(plaintext, key):
"""
plaintext: original data
key: number of character shift
"""
ciphertext = ""
for ch in plaintext:
asc = ord(ch) # ASCIIに変換
if 65 <= asc <= 90:
num = asc - 65 # A=0, B=1, ..., Z=25
shift_asc = (num + key) % 26
cipherchar = chr(shift_asc + 65)
ciphertext += cipherchar
elif 97 <= asc <= 122:
num = asc - 97 # a=0, b=1, ..., z=25
shift_asc = (num + key) % 26
cipherchar = chr(shift_asc + 97)
ciphertext += cipherchar
else:
sys.stderr("Error: alphabet only")
return ciphertext
First of all, it processes a given string( plaintext
) character by character.
Convert to ASCII after that substitute A=0, B=1, ..., Z=25 for easy to use numbers, and then slide by the given number( key
).
Run the code:
t = caeser("flower", 3) # 第一引数: 暗号化したい文字列、第二引数: 3文字ずらす
print(t)
It generates the cipher text as below:
iorzhu
Caesar cipher is very simple algorithm that shift by the specified number.
Because of its simplicity, it is useless in modern times but often appears in the history of cipher because it played a role in the development of cryptography.