-4
print ("")
print ("Welcome to Vigenere cipher!")
print ("")
print ("This program will encrypt then offer you a decryption of your message.")
print ("")
print ("Start this off with inputting your message you would like to encrypt.")
m = input("")
print ("")
print ("Now enter your keyword you would like to use. (it must be (" +str(len(m)),"or less letters.))")
k = input("")

if len(k) > len(m):
    print ("")
    print ("sorry this is an invaild keyword")
    print ("Please re-enter your keyword.")
    k = input("")
else:
    print ("Your keyword is great. Lets keep going")

print ("")

print ("Is this correct?")
print ("")

print("-------\n"
  "Message:  ",m,"\n"
  "Key:      ",k,
  "\n-------")
print ("")

print ("yes or no")
correct = input ("")
if 'yes'.startswith(correct.lower()):
print("Great! Lets keep going.")
else:
    print ("You previously put: " +str(m), " as your message.")
    print ("Please re-enter the keyword you wish to use. (it must be (" +str(len(m)),"or less letters.))")
    k = input("")
encrypted = ("")
print ("")

for a in m:
    print ("The message letters are")
    encrypt2 = ord(a)

    for b in k:
        print ("The keyword letters are")
        encrypt = ord(b)
        encrypt3 = (encrypt) + (encrypt2)
        encrpyted = chr(encrypt3)
        print (chr(encrypt3))

我需要它用关键字加密,有什么帮助吗?ps 它需要像上面的代码一样基本。它适用于 GCSE(英国),如果它需要一些命令,那么你能告诉我它们是做什么的吗:) 所以我可以在任务中解释它:)

4

1 回答 1

1

首先,您的问题失败:

所有的代码for a in m:都是不必要的,这不是你问题的一部分,你真正的问题是使用 vigenere 密码算法加密一个单词,这可以用两行代替:

message = "ATTACKATDAWN"
key_adj = "LEMONLEMONLE"

或者如果你喜欢

message = "ATTACKATDAWN"
key = "LEMON"
#key_adj and message equal length
key_adj = key + key*((len(message)/len(key))-1) + key[:len(message)%len(key)]
#key_adj is LEMONLEMONLE

注意:我重命名变量,以便帮助您的人更好地理解,

由于输入现在不是问题,我可以解决问题

其次,您的算法失败:

最明显的错误是使用嵌套for,越多越好,这会使您的解决方案复杂化,对于这个问题,您只需要一个for

for a in m:
    for b in k:
        ....

第二个失败,是密码方程....例如,第一个字母:

letter_menssage = "A" -> ord("A") = 65
letter_key = "L" -> ord("L") = 76
                                  +141 -> chr(141) = "ì"

有了所有这些解释,现在我可以展示一个解决方案:

#i use zip function, match letter message with letter key
# (A,L) (T,E) (T,M) (A,O) (C,N) (K,L) etc.
encrypt = ""
for letter_msg, letter_key in zip(message, key_adj):
    code_letter_msg = ord(letter_msg)-ord('A')
    code_letter_key = ord(letter_key)-ord('A')
    encrypt += chr((code_letter_msg+code_letter_key) % 26 + ord('A'))

print (encrypt)

你得到:

LXFOPVEFRNHR

解释方程:

letter_menssage = "A" -> ord("A")-65 = 0
letter_key = "L" -> ord("L")-65 = 11
                                    ((0+11)%26 + 65)-> chr(76) = "L"

letter_menssage = "T" -> ord("A")-65 = 19
letter_key = "E" -> ord("E")-65 = 4
                                    ((19+4)%26 + 65)-> chr(88) = "X"
于 2015-05-20T20:43:39.080 回答