一文详解凯撒密码的原理及Python实现

  # 恺撒密码加密

  def Caesar_PW_Encryption():

  inputText = input("请输入明文文本: ")

  for index in inputText:

  if "a" <= index <= "z":

  print(chr(ord("a") + (ord(index) - ord("a") + 3) % 26), end='')

  elif "A" <= index <= "Z":

  print(chr(ord("A") + (ord(index) - ord("A") + 3) % 26), end='')

  else:

  print(index, end='')

  # 恺撒密码解密

  def Ceasar_PW_Decryption():

  inputText = input("请输入加密后文本: ")

  for index in inputText:

  if "a" <= index <= "z":

  print(chr(ord("a") + (ord(index) - ord("a") - 3) % 26), end='')

  elif "A" <= index <= "Z":

  print(chr(ord("A") + (ord(index) - ord("A") - 3) % 26), end='')

  else:

  print(index, end='')

  if __name__ == '__main__':

  # 恺撒密码加密

  Caesar_PW_Encryption()

  # 恺撒密码解密

  Ceasar_PW_Decryption()