【发布时间】:2016-05-06 11:15:53
【问题描述】:
我正在尝试实现 Vigenere 的密码。我希望能够混淆文件中的每个字符,而不仅仅是字母字符。
我想我在不同类型的编码中遗漏了一些东西。我做了一些测试用例,一些字符在最终结果中被严重替换。
这是一个测试用例:
,.-´`1234678abcde^*{}"¿?!"·$%&/\º
结束
这是我得到的结果:
).-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")
【问题讨论】:
-
(哪个键为您提供了示例输出?)即使范围限制为 128,您也会遇到问题,因为空格“之前”的字符也很特殊。围绕 ASCII 的“普通”部分的最佳循环:只有从 32 到 126 的序数。
-
对于逗号:您是要忽略它并像往常一样编码,还是要维护它们并只编码正确的 CSV 条目? (在这种情况下,您应该注意不要将任何内容编码为逗号!)
-
@RadLexus 我也想要逗号编码。我不希望攻击者知道它的 CSV 文件。也许我必须对你所说的 [32, 126] 做一些解决方法。我会尝试并尽快更新。
-
多亏了它才能让它工作。谢谢@RadLexus!
-
太棒了!这只是我的一个建议,所以您可以使用适合您的代码self-answer您的问题。