下面展示 代码:CaesarEncryption.py
# CaesarEncryption
分别处理中文和英文
# CaesarEncryption
def caesarEncode(plaintext,bias=3):
ciphertext = ""
for char in plaintext:
if "a" <= char <= "z":
t = (ord(char) - ord("a") + bias) % 26 + ord("a")
ciphertext += chr(t)
elif "A" <= char <= "Z":
t = (ord(char) - ord("A") + bias) % 26 + ord("A")
ciphertext += chr(t)
else:
ciphertext += char
return ciphertext
def caesarDecode(ciphertext,bias=3):
plaintext = ""
for char in ciphertext:
if "a" <= char <= "z":
t = (ord(char) - ord("a") - bias) % 26 + ord("a")
plaintext += chr(t)
elif "A" <= char <= "Z":
t = (ord(char) - ord("A") - bias) % 26 + ord("A")
plaintext += chr(t)
else:
plaintext += char
return plaintext
def caesarEncodeChinese(plaintext,bias=3):
START = 19968
END = 40869
RANGE = END - START + 1
ciphertext = ""
for char in plaintext:
if START <= ord(char) <= END:
t = (ord(char) - START + bias) % RANGE + START
ciphertext += chr(t)
else:
ciphertext += char
return ciphertext
if __name__ == "__main__":
# s = "This is an excellent Python book."
# s = "Wklv lv dq hafhoohqw Sbwkrq errn."
# sE = caesarEncode(s)
# print(sE)
# sE = caesarEncode(sE,-3)
# print(sE)
# sED = caesarDecode(sE)
# print(sED)
# import this
zen = """The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!"""
# print("-"*20)
# print(caesarEncode(zen,13))
# print("-"*20)
# print(caesarEncode(zen,-13))
s = "这是一个用Python进行恺撒密码加密的实例。"
sE = caesarEncodeChinese(s)
print(sE)
sED = caesarEncodeChinese(sE,-3)
print(sED)