我正在尝试使用此代码将密文" htrgti" 解密为纯文本。我一直在" wigvix" 这不是我应该得到的信息。
鉴于纯文本(应该是一个常用的单词或短语)和密钥,对于每个说ciphertext
的地点,我用plaintext
替换它,并且每个地点都显示plaintext
1}}:
def caesar(ciphertext, shift):
alphabet=["a","b","c","d","e","f","g","h","i",
"j","k","l","m","n","o","p","q","r",
"s","t","u","v","w","x","y","z"]
plaintext = ""
for i in range(len(ciphertext)):
letter = ciphertext[i]
# Find the number position of the ith letter
num_in_alphabet = alphabet.index(letter)
# Find the number position of the cipher by adding the shift
plain_num = (num_in_alphabet + shift) % len(alphabet)
# Find the plain letter for the cipher number you computed
plain_letter = alphabet[plain_num]
# Add the cipher letter to the plaintext
plaintext = plaintext + plain_letter
return plaintext
答案 0 :(得分:0)
如果你正确地调用它,你的功能是有效的,正如@L.Llama暗示的那样,右移caesar("htrgti", 11)
是secret
。您的功能本身运行正常。这是代码的更好版本,但它仍然存在每个.index
查找为O(alphalen)的问题。所以,作为奖励,我添加了@ Two-Bit Alchemist建议的实现,以使用str.translate。
import string
alphabet = string.ascii_lowercase
alphalen = len(alphabet)
shift = 11
def caesar(ciphertext, shift):
plaintext = ""
for letter in ciphertext:
num_in_alphabet = alphabet.index(letter)
plain_num = (num_in_alphabet + shift) % alphalen
plain_letter = alphabet[plain_num]
plaintext = plaintext + plain_letter
return plaintext
print(caesar("htrgti", shift))
# secret
table = str.maketrans(alphabet, alphabet[shift:] + alphabet[:shift])
print("htrgti".translate(table))
# secret