class KaiSa:
def __init__(self):
self.LETTERS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
self.key = 10
def set_key(self, key):
"""在這裏,key等於偏移量"""
self.key = key
def encrypt(self, message):
"""加密"""
translated = ''
for symbol in message: # 遍歷字符串
if symbol in self.LETTERS: # 判斷字符是否可以加密
index = self.LETTERS.find(symbol) # 獲取下標 即對應位置
index = index + self.key # 向右偏移 獲取對應加密 字符
# 已知對應 位置是 0到len-1 所以大於等於len的時候減len
while index >= len(self.LETTERS):
index = index - len(self.LETTERS)
# 得出 加/解密 後的 字符
translated = translated + self.LETTERS[index]
else:
# 不能加密的就不變
translated = translated + symbol
return translated
def decrypt(self, message):
"""解密"""
translated = ''
for symbol in message: # 遍歷字符串
if symbol in self.LETTERS: # 判斷字符是否可以解密
index = self.LETTERS.find(symbol) # 獲取下標 即對應位置
index = index - self.key
# 已知對應 位置是 0到len-1 所以大於等於len的時候減len
while index < 0:
index = index + len(self.LETTERS)
# 得出 加/解密 後的 字符
translated = translated + self.LETTERS[index]
else:
# 不能加密的就不變
translated = translated + symbol
return translated
kaisa = KaiSa()
kaisa.set_key(13)
contant = 'This is my secret message.' # 內容
jiami_contant = kaisa.encrypt(contant) # 加密
jiemi_contant = kaisa.decrypt(jiami_contant) # 解密
print('初始內容', contant)
print('加密內容', jiami_contant)
print('解密內容', jiemi_contant)