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)