带有大写字母的凯撒密码

时间:2019-03-03 02:58:02

标签: python caesar-cipher

因此,当我使用小写字母时,当前我的Caesar密码程序运行良好。但是,当我输入大写的单词或短语时,我希望它能正常工作。这是我现在的代码。希望你们都能帮助我完成这项工作。

用户定义的功能

def加密(消息,距离):     “”“将获取邮件并旋转一定距离,以创建加密的邮件”“”

encryption = ""
for ch in message:
    ordvalue = ord(ch)
    cipherValue = ordvalue + distance
    if cipherValue > ord("z"):
        cipherValue = ord("a") + distance - (ord("z") - ordvalue + 1)
    encryption += chr(cipherValue)
return encryption

def解密(消息,距离):     “”“将解密以上消息”“”

decryption = ""
for cc in message:
    ordvalue = ord(cc)
    decryptValue = ordvalue - distance
    if decryptValue < ord("a"):
        decryptValue = ord("z") - distance - (ord("a") - ordvalue - 1)
    decryption += chr(decryptValue)
return decryption

def binaryConversion(消息):     “”“将单词转换为二进制代码”“”

binary = ""
for cb in message:
    binaryString = " " #Binary number
    binaryNumber = ord(cb)
    while binaryNumber > 0:
        binaryRemainder = binaryNumber % 2
        binaryNumber = binaryNumber // 2
        binaryString = str(binaryRemainder) + binaryString
    binary += binaryString
return binary

while循环

run = True

运行时:

#input 

message = input("Enter word to be encrypted: ") #original message
distance = int(input("Enter the distance value: ")) #distance letters will be moved

#variables

fancy = encrypt(message, distance)
boring = decrypt(fancy, distance)
numbers = binaryConversion(message)

#output
print("\n")
print("Your word was: ", format(message, ">20s"))
print("The distance you rotated was: ", format(distance), "\n")
print("The encryption is: ", format(fancy, ">16s"))
print("The decryption is: ", format(boring, ">16s"))
print("The binary code is: ", format(numbers)) #I know an error comes here but it will work in the end

repeat = input("Would you like to encrypt again? Y/N ")
print("\n")
if repeat == "N" or repeat == "n":
    run = False
else:
    run = True

Finale

print(“谢谢你,就像凯撒大帝曾经说过的那样,'Veni,vidi,vici'”)

谢谢

1 个答案:

答案 0 :(得分:1)

我建议您以映射而不是偏移的思维方式解决此问题。您可以基于偏移量构建映射,但是如果您使用字典或其他形式的一对一映射,则字符处理会更容易。

例如:

  offset = 5
  source = "abcdefghijklmnopqrstuvwxyz"
  target = source[offset:]+source[:offset]
  source = source + source.upper()
  target = target + target.upper()
  encrypt = str.maketrans(source,target)
  decrypt = str.maketrans(target,source)

  e = "The quick brown Fox jumped over the lazy Dogs".translate(encrypt)
  print(e)
  d = e.translate(decrypt)
  print(d)