[英]Vigenere Cipher in Python bug
我正在尝试实现Vigenere的Cipher。 我希望能够混淆文件中的每个字符,而不仅仅是字母字符。
我想我缺少使用不同类型的编码的东西。 我做了一些测试用例,并且某些字符在最终结果中被严重替换。
这是一个测试用例:
,.- ´12341234abcde ^ * {}“¿?!”·$%&/ \\º
结束
这就是我得到的结果:
).- 4`1234678abcde ^ * {}“ ??!” 7 $%&/:
结束
如您所见,','被严重替换为')'以及其他一些字符。
我的猜测是其他字符(例如,用'?'代替的'?')来自原始字符,不在[0,127]范围内,因此其正常值会更改。 但是我不明白为什么','失败了。
我的意图是混淆CSV文件,因此“,”问题是我主要关注的问题。
在下面的代码中,我使用的是模数128,但不确定是否正确。 要执行它,请将名为“ OriginalFile.txt”的文件放入要加密并运行脚本的内容所在的文件夹中。 将生成两个文件,Ciphered.txt和Deciphered.txt。
"""
Attempt to implement Vigenere cipher in Python.
"""
import os
key = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
fileOriginal = "OriginalFile.txt"
fileCiphered = "Ciphered.txt"
fileDeciphered = "Deciphered.txt"
# CIPHER PHASE
if os.path.isfile(fileCiphered):
os.remove(fileCiphered)
keyToUse = 0
with open(fileOriginal, "r") as original:
with open(fileCiphered, "a") as ciphered:
while True:
c = original.read(1) # read char
if not c:
break
k = key[keyToUse]
protected = chr((ord(c) + ord(k))%128)
ciphered.write(protected)
keyToUse = (keyToUse + 1)%len(key)
print("Cipher successful")
# DECIPHER PHASE
if os.path.isfile(fileDeciphered):
os.remove(fileDeciphered)
keyToUse = 0
with open(fileCiphered, "r") as ciphered:
with open(fileDeciphered, "a") as deciphered:
while True:
c = ciphered.read(1) # read char
if not c:
break
k = key[keyToUse]
unprotected = chr((128 + ord(c) - ord(k))%128) # +128 so that we don't get into negative numbers
deciphered.write(unprotected)
keyToUse = (keyToUse + 1)%len(key)
print("Decipher successful")
假设:您正在尝试生成一个新的有效CSV,其中包含通过Vigenere加密的单元格的内容,而不是加密整个文件。
在这种情况下,您应该检出csv
模块,该模块将为您正确处理CSV文件(包括在值中包含逗号的单元格,如您所见,在对单元格内容进行加密后可能会发生)。 简而言之,您可以执行以下操作:
with open("...", "r") as fpin, open("...", "w") as fpout:
reader = csv.reader(fpin)
writer = csv.writer(fpout)
for row in reader:
# row will be a list of strings, one per column in the row
ciphered = [encipher(cell) for cell in row]
writer.writerow(ciphered)
使用csv
模块时,您应该了解“ 方言 ”的概念-不同程序(通常是类似于电子表格的东西,例如Excel)处理CSV数据的方式。 csv.reader()
通常可以很好地推断输入文件中的方言,但是您可能需要告诉csv.writer()
您想要输出文件中的方言。 您可以使用csv.list_dialects()
获取内置的方言列表,也可以通过创建自定义Dialect
对象来制作自己的Dialect
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.