Skip to main content
 首页 » 编程设计

python之XOR 加密在*大部分*时间都有效

2025年05月04日6lidabo

我的任务是用密码保护一个 Java 应用程序,而对真正的安全性几乎不关心。因此,将用户名/密码对存储在文本文件中然后对其进行加密似乎是明智的。对于加密,使用 XOR 密码似乎是合适的,因为它们既简单又快速(记住——它只是要阻止临时用户,而不是防弹)。

我编写了所有合适的 Java,然后意识到我需要一种方法来加密配置文件。我写了一个额外的方法,但使用超过一两次就很笨拙(而且似乎只对某些输入有效),所以我决定最好用 Python 写一些东西,以便在 REPL 中使用。

这是我最终得到的:

from itertools import izip, cycle 
 
KEY = "stackoverflow" 
 
def encrypt(text): 
    return ''.join(chr(ord(x) ^ ord(y)) for (x,y) in izip(text,cycle(KEY))) 
 
def decrypt(text): 
    return encrypt(text) 
 
def export(users, file): 
    with open(file, "w") as f: 
        for user, password in users.items(): 
            f.write(encrypt('"%s" "%s"'%(user, password)) + "\n") 
 
def import_data(file): 
    with open(file) as f: 
        return [decrypt(i) for i in f.readlines()] 

从表面上看,它有效:

>>> x = encrypt("Hello world!") 
>>> x 
';\x11\r\x0f\x04O\x01\n\x00\n\x08N' 
>>> decrypt(x) 
'Hello world!' 

但随后事情开始分崩离析:

>>> export({"foo" : "bar", "baz" : "quux", "spam" : "eggs"}, "users.dat") 
>>> import_data("users.dat") 
['"foo" "bar"e', '"baz" "quux"}', '"spam" "eggs"y'] 

这是 vim 读取它的方式 -

然后:

>>> export({"what" : "not", "this" : "that", "admin_istrator" : "quux"}, "users2.dat") 
>>> import_data("users2.dat") 
['"thi', "k97$ma{~'l", '"what" "not"}', '"admin_istrator" "quux', '7~'] 

Vim :

我突然想到,我可能对字符的加密形式作为换行符有疑问,但据我所知,这并不能解释第一个示例或所有中的古怪行为第二个古怪的行为。

关于换行符,我的 B 计划是加密整个文件——换行符和所有文件——然后将其备份、解密、拆分为“\n”,然后继续我的基于行的解析。

提前致谢。


更新:这是我对 B 计划的实现(前两段所述)。

def import2(file): 
    with open(file) as f: 
        return decrypt(f.read()) 

然后:

>>> export({"foo" : "bar", "this" : "that", "admin_istrator" : "letmein"}, "users2.dat") 
>>> import2("users2.dat") 
'"this" "that"y%smg&91uux!}"admin_istrator" "letmein"y' 

更新二:二进制。

[代码同上,只是所有的open都是open(file, "rb")或者open(file, "wb")。]

>>> export({"foo" : "bar", "this" : "that", "admin_istrator" : "letmein"}, "users2.dat") 
>>> import2("users2.dat") 
'"this" "that"y%smg&91uux!}"admin_istrator" "letmein"y' 
>>> import_data("users2.dat") 
['"t', "k97$ma{~'", '"foo" "bar"', '"admin_istrator" "letmein"'] 

最终更新:Base 64,其他恶作剧。

def import2(file): 
    with open(file, "rb") as f: 
        return filter(str.strip, [decrypt(i) for i in f.readlines()]) 

其中 encrypt 和 decrypt encode in/decode base 64。

请您参考如下方法:

您正在尝试将二进制文件存储在文本模式文件中。使用 open(file, "wb")用于写作和open(file, "rb")用于读取以二进制模式打开文件并修复问题。

在文本模式下每"\r" , "\n"和 "\r\n"序列被视为换行符,因此它们被转换为您本地操作系统的行结束约定("\r\n" 适用于 Windows,"\n" 适用于 Unix,"\r" 适用于旧 Mac)。如果您从文本文件中读取它们,您将始终得到 "\n"相反,如果你写它们,我不记得实际的行为,但你肯定也会弄得一团糟,而不是你的数据:)

使用 XOR 加密,您很可能会遇到这种情况:)

如果您被迫不使用二进制文件,请尝试使用 base64 编码(例如 "some\0te\n\nxt with bi\x01naries".encode('base64'))。解码使用 .decode (谢谢,Captain Obvious!)。