在此任务中,我需要根据给定的密钥对消息进行加密。面临的挑战是将字母的索引编入索引,并进行更改以替换消息中的字母。到目前为止,我的代码是:
def encode(key,plaintext):
for i in key:
key.index(i)
for i in plaintext:
print(plaintext.index(i))
alpha = ["abcdefghijklmnopqrstuvwxyz"]
def main():
plaintextMessages = [
["This is the plaintext message.",
"bcdefghijklmnopqrstuvwxyza"],
["Let the Wookiee win!",
"epqomxuagrdwkhnftjizlcbvys"],
["Baseball is 90% mental. The other half is physical.\n\t\t- Yogi Berra",
"hnftjizlcbvysepqomxuagrdwk"],
["I used to think I was indecisive, but now I'm not too sure.",
"mqncdaigyhkxflujzervptobws"],
["Einstein's equation 'e = mc squared' shows that mass and\n\t\tenergy are interchangeable.",
"bludcmhojaifxrkzenpsgqtywv"] ]
codedMessages = [
["Uijt jt uif dpefe nfttbhf.",
"bcdefghijklmnopqrstuvwxyza"],
["Qnhxgomhqm gi 10% bnjd eho 90% omwlignh. - Zghe Xmy",
"epqomxuagrdwkhnftjizlcbvys"],
["Ulj njxu htgcfj C'gj jgjm mjfjcgjt cx, 'Ep pej jyxj veprx rlhu\n\t\t uljw'mj tpcez jculjm'. - Mcfvw Zjmghcx",
"hnftjizlcbvysepqomxuagrdwk"],
["M 2-wdme uxc yr kylc ua xykd m qxdlcde, qpv wup cul'v gmtd mlw\n\t\t vuj aue yv. - Hdeew Rdyladxc",
"mqncdaigyhkxflujzervptobws"] ]
for i in plaintextMessages:
encode(i[1],i[0])
main()
我可以获得键的索引和消息,但是我对如何使这些东西交互或相互影响感到困惑。
答案 0 :(得分:0)
如果键应按数字移动明文(例如b会将其移动2),则ord
和chr
函数将有所帮助。您可以遍历明文,使用ord
查找字母编号,然后将其移动,然后使用chr
查找新字母。
例如
keyAscii = ord(key[i]) - 96 #I'm assuming all keys are like the above and lowercase
textAscii = ord(plaintext[i]) + keyAscii
if((textAscii > 90 and < 97) or (textAscii > 122)): #This part is to keep it as letters
textAscii -= 26
对于解码编码的消息,您可以执行相反的操作,然后减去ASCII值。