本体密码 - 不添加正确的值 [英] vigenere cipher - not adding correct values
问题描述
我想从for循环中获取特定的值,以添加到另一个字符串来创建一个vigenere密码。 b
userinput = input('enter message')
keyword = input('enter keyword')
new =''
for a in关键字:
pass
for i in(ord(x)for x in userinput):
if 96< i< 123:#lowercase
new + = chr(97 +(i + ord(a)-97)#keeps字母中的所有值
print(new)
所以我想要的答案如果我做abcd作为我的消息,'ab'作为我的关键字,所需的结果是'bddf'为'a' +'a'是'b'和'b'+'b'='d'等等。我将如何更改代码以匹配我想要的结果,或者我必须完全改变它,我将如何去做
尝试这个(你缺少 mod 26
-part )
from itertools import cycle
plaintext = input('enter message:')
keyword = input('enter keyword:')
def chr_to_int(char):
返回0如果char =='z'else ord(char)-96
def int_to_chr(integer):
返回'z'如果整数== 0 else chr(整数+ 96)
def add_chars(a,b):
返回int_to_chr((chr_to_int + chr_to_int(b))%26)
def vigenere(明文,关键字):
keystream =循环(关键字)
ciphertext =''
为pln,键入zip(明文,密钥流):
ciphertext + add_chars(pln,key)
return ciphertext
ciphertext = vigenere(plaintext,keyword)
print(ciphertext)
如果你喜欢列表推导,你也可以写
def vigenere(明文,关键字):
keystream =循环(关键字)
return''.join(add_chars(pln,key)
for pln,key in zip(plaintext,keystream))
更新
根据 a + a = b
的愿望更新。请注意,在这种情况下, z
是添加的中性元素( z + char = z
)。
I want to get specific values from a for loop to add to another string to create a vigenere cipher.
here's the code.
userinput = input('enter message')
keyword = input('enter keyword')
new = ''
for a in keyword:
pass
for i in (ord(x) for x in userinput):
if 96 < i < 123: #lowercase
new += chr(97 + (i+ord(a)-97)#keeps all values in alphabet
print(new)
so the answer i want if i do 'abcd' as my message and 'ab' as my keyword the desired outcome is 'bddf' as 'a' + 'a' is 'b' and 'b' + 'b' = 'd' and etc. how would i change the code to match my desired outcome or will i have to change it completely and how would i go about doing so.
try this (you are missing the mod 26
-part):
from itertools import cycle
plaintext = input('enter message: ')
keyword = input('enter keyword: ')
def chr_to_int(char):
return 0 if char == 'z' else ord(char)-96
def int_to_chr(integer):
return 'z' if integer == 0 else chr(integer+96)
def add_chars(a, b):
return int_to_chr(( chr_to_int(a) + chr_to_int(b) ) % 26 )
def vigenere(plaintext, keyword):
keystream = cycle(keyword)
ciphertext = ''
for pln, key in zip(plaintext, keystream):
ciphertext += add_chars(pln, key)
return ciphertext
ciphertext = vigenere(plaintext, keyword)
print(ciphertext)
if you like list comprehensions, you can also write
def vigenere(plaintext, keyword):
keystream = cycle(keyword)
return ''.join(add_chars(pln, key)
for pln, key in zip(plaintext, keystream))
UPDATE
updated according to the wish that a+a=b
. note that z
is in that case the neutral element for the addition (z+char=z
).
这篇关于本体密码 - 不添加正确的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!