如何将泡菜输出变成不可读的格式

How to turn pickle output into an unreadable format

将 pickle 库与我创建的一些 classes 一起使用时,输出对用户来说相当容易阅读。例如,如果我有一个名为 saves 的填充,并将我所有的 class 数据保存到其中的一个 .save 文件中,当使用文本编辑器打开该文件时,您可以模糊地看到所有变量并且没有太多的努力, 将它们更改为所需的结果。

这是我用 pickle 创建的保存文件的片段(这是一个游戏):

S'Strength'
p4
I5
sS'Health'
p8
I100

这里'Health'的值为100,'Strength'的值为5,如果用户要编辑保存文件(因为它会保存在本地),他们可以轻松更改任何他们想要欺骗游戏的变量。

因为我正在创建一个游戏,其中保存游戏是我计划实现的功能之一,所以这已成为一个问题。

我确实考虑过使用加密,但使用第二个外部库是最后的手段,因为它可能非常乏味,所以我想知道是否还有其他方法可以做到这一点,或者 pickle 是否附带为此的内置函数(研究后我还没有看到none)。

一个稍微混淆的想法是简单的十六进制转换或您选择的编码。对于十六进制,我会这样做(我猜 +12 是随机噪声)

mylist_obf = map(lambda item:int(item.encode('hex'))+12,mylist)

反向操作取回原件

my_original_list = map(lambda item: str(int(item)-12).decode('hex'),mylist_obf)

请注意,这非常不安全,只会让玩家认为它实际上是加密的。

与其试图让您的数据不可读,您可以简单地签署数据,然后在读取时验证它。

节省

这里使用hmac来计算哈希值。然后我们将散列与数据一起保存:

import hmac, pickle

# pickle the data
pickled = pickle.dumps(data)
digest =  hmac.new("some-shared-key", pickled, 
                   digestmod=<my choice of hasher>
                   ).hexdigest()

# now save the hashed digest and the pickled data
with open("some-file", "wb") as f:
    # save these in some way you can distinguish them when you read them
    print(digest, file=f)
    print(pickled, file=f)

加载中

为了验证数据,我们重新计算腌制数据的摘要,并将其与与其一起保存的摘要进行比较。

import hmac, pickle

with open("some-file", "rb") as f:
    digest = f.readline()
    pickled = f.read()

# confirm integrity
recomputed = hmac.new("some-shared-key", pickle, 
                       digestmod=<my choice of hasher>
                      ).hexdigest()
if not compare_digest(digest, recomputed):
    raise SomeOneIsCheatingOhNoException