#Vigenere Cipher
EncryptedMessage=""
Mode=""
Keywordcount = 0 #sets everything to 0
KeywordTwocount = 0
while Mode != "encrypt" and Mode != "decrypt":
Mode = input('Do you want to encrypt or decrypt a message?')
Mode = Mode.lower()
if Mode == "encrypt":
Message=input('Please eneter the message you wish to encrypt: ')
Keyword=input('Please enter the keyword you want to use:')
KeywordTwo = input(' Please enter second keyword you want to use:')
Keywordlength = len(Keyword)
KeywordTwolength = len(KeywordTwo)
for i in range(0, len(Message)):
Messageencrypt = Message[i]
Keywordencrypt = Keyword[Keywordcount]
KeywordTwoencrypt= KeywordTwo[KeywordTwocount]
if Messageencrypt.isalpha():
if Messageencrypt.isupper():
Messageencrypt = ord(Messageencrypt)
Keywordencrypt = Keywordencrypt.upper()
Keywordencrypt = ord(Keywordencrypt) - 64
KeywordTwoencrypt = KeywordTwoencrypt.upper()
KeywordTwoencrypt = ord(Keyword2encrypt) - 64
FirstCodedMessage = Messageencrypt + Keywordencrypt
FinalCodedMessage = FirstCodedMessage + Keyword2encrypt
if FinalCodedMessage > 90:
FinalCodedMessage = FinalCodedMessage - 26
Encryptedletter = chr(FinalCodedMessage)
elif Messageencrypt.islower():
Messageencrypt = ord(Messageencrypt)
Keywordencrypt = Keywordencrypt.upper()
Keywordencrypt = ord(Keywordencrypt) - 64
KeywordTwoencrypt = KeywordTwoencrypt.upper()
KeywordTwoencrypt = ord(KeywordTwoencrypt) - 64
FinalCodedMessage = Messageencrypt + Keywordencrypt
if FinalCodedMessage > 122:
FinalCodedMessage = FinalCodedMessage - 26
Encryptedletter = chr(FinalCodedMessage)
else:
Encryptedletter = Messageencrypt
EncryptedMessage = EncryptedMessage + Encryptedletter
Keywordcount = Keywordcount + 1
if Keywordcount >= Keywordlength:
Keywordcount = 0
KeywordTwocount = KeywordTwocount + 1
if KeywordTwocount >= Keywordlength:
KeywordTwocount = 0
print(EncryptedMessage)
什么是
KeywordTwoencrypt= KeywordTwo[KeywordTwocount] IndexError: string index out of range
意思? Error
另外,如何将此加密邮件另存为txt文件? Error
答案 0 :(得分:1)
if KeywordTwocount >= Keywordlength:
应为if KeywordTwocount >= KeywordTwolength:
如果存在索引问题,那么您应该仔细查看处理此特定索引增量/减量的代码的所有部分。
在这种特定情况下,您应该看到第二个关键字的索引与第一个关键字的长度无关。所以更新是错误的:
if KeywordTwocount >= Keywordlength:
KeywordTwocount = 0
通过定义使用一个关键字加密消息的函数,可以轻松避免此错误:
def vigenere(message, keyword):
...
然后你可以将这两者连在一起:
print(vigenere(vigenere(message, keyword1), keyword2))
使用内置函数写入文件也很容易:
with open('ciphertext.txt', 'w') as ct:
ct.write(EncryptedMessage)
答案 1 :(得分:0)
KeywordTwo[KeywordTwoCount] IndexError: string index out of range
表示索引(KeywordTwoCount
)大于您要将KeywordTwo
索引的字符串的长度。