【问题标题】:Encrypting a message using a cyclic cypher使用循环密码加密消息
【发布时间】:2012-03-20 12:17:20
【问题描述】:

这是一个例子:

  • 普通:ABCDEFGHIJKLMNOPQRSTUVWXYZ
  • Shift = 4
  • 密码:DEFGHIJKLMNOPQRSTUVWXYZABC

代码如下:

print ("This is a cyclic cipher program that will encrypt messages.")

#phrase = input("Please enter a phrase to encrypt.")
phrase = "ABCDEFG"
#shift_value = int(input ("Please enter a shift value between 1 - 5."))
shift_value = 1
encoded_phrase = ""
ascii_codes = 0
x = ""
#accepted_ascii_codes = range(65,90) and range(97,122)

for c in phrase:
ascii_codes = ord(c) # find ascii codes for each charcter in phrase
ascii_codes = ascii_codes + shift_value # add an integer (shift value) to ascii codes
phrase_rest = chr(ascii_codes) # convert ascii codes back to characters
encoded_phrase = encoded_phrase + c # stores the phrase character in a new variable
encoded_phrase = encoded_phrase.replace(c,phrase_rest) # replace original character

print (phrase) # prints "ABCDEFG"
print (encoded_phrase) # prints "HHHHHHH"

【问题讨论】:

    标签: python python-3.x ascii encryption cyclic


    【解决方案1】:

    您在每个循环中重新编码您的密码字母,这样可以解决问题:

    for c in phrase:
      ascii_codes = ord(c) # find ascii codes for each charcter in phrase
      ascii_codes = ascii_codes + shift_value # add an integer (shift value) to ascii codes
      phrase_rest = chr(ascii_codes) # convert ascii codes back to characters
      encoded_phrase = encoded_phrase + phrase_rest # stores the phrase character in a new variable
    

    但是,您可能想要建立一个包含原始字母和加密字母的字典。然后,您将遍历它们并获得加密的句子。例如:

    cypher = {'a': 'x', 'b': 'y', ... }
    encoded = ''
    for c in phrase:
      encoded += cypher[c]
    

    【讨论】:

    • 感谢 FMC!我不熟悉字典,但我会尝试一下。
    猜你喜欢
    • 1970-01-01
    • 2022-01-28
    • 1970-01-01
    • 1970-01-01
    • 2020-11-01
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    • 2019-01-14
    相关资源
    最近更新 更多