【问题标题】:Ignoring spaces in Vigenere Cipher忽略 Vigenere Cipher 中的空格
【发布时间】:2019-07-30 10:17:37
【问题描述】:

我已经为 vigenere 密码编写了一个加密和解密程序,但在涉及空格时我被卡住了。我可以用什么条件来克服它并完全忽略它

print("Enter the string to be encrypted")
s=input()
print("Enter the key for encryption")
t=input()
r=0
s=list(s)
t=list(t)
key=[]
encrypted=[]
decrypted=[]
#This is the loop for making the key string
for i in range(0,len(s),len(t)):
    r=i
    for j in range(0,len(t),1):
        if(i<len(s)):
            if(len(key)<len(s)):
                    key.append(t[j])
        i=i+1
    i=r
print("The encrypted key is: ")
key=''.join(key)
print(key)
#This is the code for encrypting the message with the key string
for i in range(0,len(s)):
    x = (ord(s[i]) + ord(key[i])) % 26
    x += ord('A') 
    encrypted.append(chr(x))
print("The encrypted string is: ")
encrypted=''.join(encrypted)
print(encrypted)
#For decryption
for i in range(0,len(s)):
    x = (ord(encrypted[i]) - ord(key[i])+26) % 26
    x += ord('A') 
    decrypted.append(chr(x))
print("The decrypted string is: ")
decrypted=''.join(decrypted)
print(decrypted)

这里Key字符串指的是->

字符串输入 - 西瓜

钥匙 - 柠檬

钥匙串 - LEMONLEMON

但它不适用于句子。我尝试输入类似

的代码
if(s[i]==' '):
    continue

但是没用

【问题讨论】:

  • 代码不可用,除了你的问题是你正在创建与字符串匹配的密钥,你应该在加密之前删除空格。
  • 该代码仅可用于大写字符和大写键但没有空格,在解密过程中我将如何在加密后放置空格...编辑它以使其工作,发布它可能已经改变有点
  • 不是那个意思,尝试将代码复制粘贴到一个新文件中,您就会明白我的意思了。你很可能有混合缩进或其他东西,看看第一个循环,r=i 是“过度缩进
  • 代码现在有望修复

标签: python python-3.x encryption cryptography


【解决方案1】:

可能的解决方案,希望不要太python2

from itertools import cycle
# if python2 uncomment the following
# from itertools import izip as zip

# you can replace these with calls for input() 
data = "attack at dawn"
key = "lemon"

# sanitize input
data = "".join(data.upper().split()) # trick to remove all white-space chars
key = key.upper()


print data
print key

ord_A = ord('A')

# encripting 
encrypted = []

# looping together the input and the key
# cycle gives an infinite loop over an iterable 
for dc, kc in zip(data, cycle(key.upper())):
    ec = ord_A + (ord(dc) + ord(kc)) % 26
    encrypted.append(chr(ec))
encrypted =  "".join(encrypted) 
print(encrypted)

# decrypting
decrypted = []
for ec, kc in zip(encrypted, cycle(key.upper())):
    dc = ord_A + (ord(ec) - ord(kc)) % 26
    decrypted.append(chr(dc))
decrypted =  "".join(decrypted)
print(decrypted)```

【讨论】:

  • 什么是 izip?尝试复制粘贴并尝试,但它显示 izip 错误
  • 抱歉,这似乎是 python2 特定的,zip 将多个“iterables”连接在一起,返回一个元组列表,其中每个元素/元组包含每个参数的第 n 个元素,@987654323 @ 返回一个“类似生成器”的对象,而不是具有较小占用空间的完整列表,似乎在 python3 中,izip 已被删除,因为 zip 已经“优化”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-18
  • 1970-01-01
  • 2019-06-27
  • 2018-07-29
相关资源
最近更新 更多