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))
我需要用关键字加密,有什么帮助吗? p.s它需要像上面的代码一样基本。 它适用于GCSE(英国) 如果它需要一些命令那么你能告诉我他们做了什么:)所以我可以在任务中解释它:))
答案 0 :(得分: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"