[英]vigenere encryption probleme with 'spaces' on python
i can t pinpoint the reason why the encryption goes wrong after 'spaces' here is the code:我无法确定在“空格”之后加密出错的原因是代码:
def chiffre_vigenere(message,key):
message = message.lower()
key = key.lower()
encrypted = []
d = dict(a=0,b=1,c=2,d=3,e=4,f=5,g=6,h=7,i=8,j=9,k=10,l=11,m=12,n=13,o=14,p=15,q=16,r=17,s=18,t=19,u=20,v=21,w=22,x=23,y=24,z=25)
long_key = key
while len(message) > len(long_key) :
long_key = long_key + key
i=0
while i < len(message) :
decalage = d.get(long_key[i])
if message[i].isalpha() :
c = ord(message[i]) + decalage
if c > 122 :
c = c - 26
encrypted.append(chr(c))
else :
encrypted.append(message[i])
i = i+1
print(listToString(encrypted))
for example when i do: chiffre_vigenere('stack overflow','apple') it gives: sipno dkpvfadh the first word is encrypted right but after the space the encryption is wrong any help is appreciated thanks in advance例如,当我这样做时: chiffre_vigenere('stack overflow','apple') 它给出: sipno dkpvfadh 第一个单词是正确加密的,但是在空格之后加密是错误的,任何帮助都提前感谢
The problem is that you're using the same counter variable i
to mark your place in two different strings: message
and long_key
.问题是您使用相同的计数器变量
i
在两个不同的字符串中标记您的位置: message
和long_key
。 Whenever you encounter a non-alphabet character in message
, you're stepping to the next character, but you're also stepping to the next character in long_key
, which is not what you want to do.每当您在
message
中遇到非字母字符时,您都会跳到下一个字符,但您也会long_key
中的下一个字符,这不是您想要做的。
If you just use i
to count characters in long_key
then the problem goes away.如果您只使用
i
来计算long_key
中的字符,那么问题就会消失。 For example:例如:
def chiffre_vigenere(message,key):
message = message.lower()
key = key.lower()
encrypted = []
d = dict(a=0,b=1,c=2,d=3,e=4,f=5,g=6,h=7,i=8,j=9,k=10,l=11,m=12,n=13,o=14,p=15,q=16,r=17,s=18,t=19,u=20,v=21,w=22,x=23,y=24,z=25)
long_key = key
while len(message) > len(long_key):
long_key = long_key + key
i=0
for ch in message:
decalage = d.get(long_key[i])
if ch.isalpha() :
c = ord(ch) + decalage
if c > 122 :
c = c - 26
encrypted.append(chr(c))
i = i+1
else :
encrypted.append(ch)
print(listToString(encrypted))
You might also consider simplifying your code a little.你也可以考虑稍微简化你的代码。 You can use the
ord
function to convert ASCII values to integers, and a modulus operator to cycle through the values of key
without having to expand it to the size of the input message.您可以使用命令
ord
将 ASCII 值转换为整数,并使用模运算符循环遍历key
的值,而无需将其扩展为输入消息的大小。
def chiffre_vigenere(message,key):
key = key.lower()
encrypted = ''
i = 0
for ch in message.lower():
if 'a' <= ch <= 'z':
a = ord(ch) + ord(key[i]) - ord('a')
if a > ord('z'):
a -= 26
encrypted += chr(a)
i = (i + 1) % len(key)
else:
encrypted += ch
print(encrypted)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.